Compare commits

...

139 Commits

Author SHA1 Message Date
Arthur Meyre
cb1a95e20d chore(tfhe): bump version to 0.2.4 2023-05-09 16:07:55 +02:00
dependabot[bot]
1d19fcfdb9 chore(deps): bump JS-DevTools/npm-publish from 2.0.0 to 2.1.0
Bumps [JS-DevTools/npm-publish](https://github.com/JS-DevTools/npm-publish) from 2.0.0 to 2.1.0.
- [Release notes](https://github.com/JS-DevTools/npm-publish/releases)
- [Changelog](https://github.com/JS-DevTools/npm-publish/blob/main/CHANGELOG.md)
- [Commits](0be441d808...541aa6b21b)

---
updated-dependencies:
- dependency-name: JS-DevTools/npm-publish
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-09 12:01:49 +02:00
sarah el kazdadi
c93bb51714 fix(pbs): fix bug in rounding code in f128 pbs 2023-05-09 11:21:30 +02:00
Arthur Meyre
b1788cc9df chore(core): re-enable split pbs for u128 2023-04-26 09:23:17 +02:00
Arthur Meyre
6000ef39ab chore(doc): fix docstring ref 2023-04-26 09:23:17 +02:00
Arthur Meyre
c087858f65 refactor(integer): remove usage of Mutex for determinism 2023-04-25 17:16:30 +02:00
sarah el kazdadi
62d6852d07 fix(split): fix split pbs backward conversion 2023-04-25 11:17:44 +02:00
Arthur Meyre
85e8988f29 chore(core): change rng tests to better avoid false failures
- we still check we generate non zero values but add retry conditions or
have less stringent checks, to allow some values to be zero for example as
it's a valid value that can be generated
- each test suite (test and doctest) for these tests ran 1000 times without
failure
2023-04-24 14:49:14 +02:00
dependabot[bot]
ac04ed0893 chore(deps): bump JS-DevTools/npm-publish from 1.4.3 to 2.0.0
Bumps [JS-DevTools/npm-publish](https://github.com/JS-DevTools/npm-publish) from 1.4.3 to 2.0.0.
- [Release notes](https://github.com/JS-DevTools/npm-publish/releases)
- [Changelog](https://github.com/JS-DevTools/npm-publish/blob/main/CHANGELOG.md)
- [Commits](0f451a9417...0be441d808)

---
updated-dependencies:
- dependency-name: JS-DevTools/npm-publish
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-24 14:49:01 +02:00
Arthur Meyre
60385f1489 chore(tfhe): bump version to 0.2.3 2023-04-24 10:48:30 +02:00
Arthur Meyre
7c8926b645 chore(doc): fix typo 2023-04-24 09:30:08 +02:00
David Testé
e5cf51230a chore(ci): publish tfhe release on-demand
This will perform on-demand release publication.
It will publish on the following channels:
 * crates.io
 * web and node package on npmjs

(cherry picked from commit 25a2586eae)
2023-04-21 15:56:09 +02:00
Arthur Meyre
cdc25d6c60 chore(core): add more sanity checks on RNG 2023-04-21 13:16:18 +02:00
Arthur Meyre
ab59514b0d fix(core): fix rng 2023-04-21 13:16:18 +02:00
tmontaigu
7c2fa7529c feat(boolean): add BooleanEngine::replace_thread_local
This new associated function allows to replace
the engine used in the thread.
2023-04-20 17:22:37 +02:00
Arthur Meyre
945ce4617f chore(tfhe): bump version to 0.2.2 2023-04-20 09:21:53 +02:00
Arthur Meyre
ff84e70ca9 chore(core): disable split pbs128 2023-04-20 09:21:53 +02:00
tmontaigu
956c4080f5 feat(hlapi): add trivial encryptions 2023-04-19 11:12:45 +02:00
tmontaigu
fea1b4db92 feat(integer): add trivial encryption 2023-04-19 11:12:45 +02:00
Arthur Meyre
13c1fcb6e7 chore(tfhe): bump version to 0.2.1 2023-04-19 10:18:51 +02:00
tmontaigu
69b9bd3860 fix(hlapi): use correct number of blocks for FheUint32
The FheUint32 was wrongly defined as being 32 blocks of 2 bits
when it should have been 16 blocks.
2023-04-19 10:18:30 +02:00
Arthur Meyre
747693e889 chore(doc): updated benchmarks for min to reflect the fix done to min/max 2023-04-19 10:16:44 +02:00
Arthur Meyre
e452d5d6d2 chore(bench): only run avx512 benches 2023-04-18 16:37:38 +02:00
Arthur Meyre
5425ba5199 fix(integer): fix mul correctness
- update benches accordingly
2023-04-18 16:37:38 +02:00
dependabot[bot]
aeda381f12 chore(deps): bump actions/checkout from 3.5.0 to 3.5.2
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.5.0 to 3.5.2.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](8f4b7f8486...8e5e7e5ab8)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-18 10:46:04 +02:00
Arthur Meyre
9b2cccfee6 chore(integer): restore empty carry check for default comparator tests
- only extract assign message instead of doing a full propagate as carries
are not supposed to be non zero (though the degree will have grown)
2023-04-18 10:35:20 +02:00
J-B Orfila
b534f6a406 chore(doc): fix typo 2023-04-14 15:28:29 +02:00
J-B Orfila
7a72dd2619 chore(doc): fix TOML 2023-04-14 14:50:50 +02:00
J-B Orfila
343f31e070 chore(doc): fix dead links 2023-04-13 17:56:01 +02:00
J-B Orfila
a2384e0d1f chore(doc): last fixes 2023-04-13 14:38:42 +02:00
J-B Orfila
37da2f1f1e chore(doc): bench integers added 2023-04-13 14:38:42 +02:00
J-B Orfila
8c775e5a27 chore(doc): add default benches 2023-04-13 14:38:42 +02:00
J-B Orfila
43ba7e103d chore(doc): 0.2 doc 2023-04-13 14:38:42 +02:00
Arthur Meyre
448e634748 fix(integer): fix scalar mul bug when representing integers > 64 bits
- a product was overflowing, we now compute a progressive division with
the same effect and stop once we reach zero to limit the number of
generated tasks
2023-04-13 13:26:48 +02:00
Arthur Meyre
6268752ac9 fix(integer): fix radix wopbs table size issue 2023-04-13 11:03:33 +02:00
David Testé
e0ed2d91c6 chore(ci): add shortint default ops to benchmarks 2023-04-12 19:11:15 +02:00
Arthur Meyre
fef389e002 chore(core): more reasonable LWE sub test
- otherwise we are just checking that x.wrapping_sub(x) == 0
2023-04-12 16:21:20 +02:00
Arthur Meyre
ae30f7c086 chore(bench): use clean inputs for default ops bench
- by design default ops are made to work best on clean CTs
2023-04-12 15:48:00 +02:00
Arthur Meyre
3f719a30f6 chore(tfhe): update check toolchain 2023-04-12 15:47:46 +02:00
tmontaigu
d28880ac30 chore(makefile): allow passing cargo profile
This allows to invoke the Makefile with a cargo profile
eg:
- `make CARGO_PROFILE=devo build_integer`
- `make CARGO_PROFILE=dev build_integer`
- `make CARGO_PROFILE=release build_integer`

By default still use release profile.
2023-04-12 12:39:54 +02:00
Arthur Meyre
ca9cdc0e73 chore(tfhe): add fpcc target to have a fast pcc locally 2023-04-12 11:21:10 +02:00
Arthur Meyre
f768e62d89 refactor(tfhe): add support for power of 2 q for LWE linalg + KS + PBS 2023-04-11 23:01:25 +02:00
tmontaigu
ee96a0ff18 chore(hlapi): use 'default' ops 2023-04-11 21:56:01 +02:00
J-B Orfila
ee944b3129 chore(ci): add default op 2023-04-11 21:35:56 +02:00
David Testé
672f855770 chore(ci): make curl based job step fails upon 4xx or 5xx response 2023-04-11 21:35:56 +02:00
David Testé
362992a4ba chore(ci): benchmark only fastest integer operations
This is done to speed-up execution and to avoid having benchmark
job running for more than 6 hours in GitHub Actions. The selected
operations set gathers the ones that most user would look for, i.e
the fastest and smartest ones.
2023-04-11 21:35:56 +02:00
David Testé
2b24eb304d chore(ci): record benchmarks parameters to be stored in database
This is done to comply with the new Zama benchmark standard.
Exhaustive parameters list is stored so once it's parsed and send
to database, one can easily filter results on such parameters in
visualization tool.
2023-04-11 21:35:56 +02:00
Arthur Meyre
b484b8a851 chore(core): add multi bit PBS bench structure 2023-04-11 21:35:56 +02:00
Arthur Meyre
6dea738725 chore(integer): fix default scalar_mul missing full propagate 2023-04-11 21:29:12 +02:00
Arthur Meyre
3bb342879f chore(tfhe): temporarily disable integer 3_3 tests 2023-04-11 21:29:12 +02:00
Jérémy Zaccherini
9f024e2dac chore(tfhe): update design and links of the README.md 2023-04-11 21:28:44 +02:00
tmontaigu
190b483d23 chore(tfhe): rename typed_api to high_level_api
high_level_api makes it easier to understand
what this api brings (at least more than typed_api does)
and is term used in the documenation
2023-04-11 20:57:36 +02:00
Arthur Meyre
e799d240a7 chore(c_api): allow to build in a simple cargo command, requires nightly 2023-04-11 19:51:51 +02:00
Arthur Meyre
16596137c1 chore(integer): disable smart_add for params 1_1 which is very slow 2023-04-11 19:05:17 +02:00
Arthur Meyre
03cd7ef15a feat(integer): add default scalar shift ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
4cda0a7211 feat(integer): add default sub op 2023-04-11 19:05:17 +02:00
Arthur Meyre
9b668c1d50 feat(integer): add default scalar ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
dc4d9c7968 feat(integer): add default neg op 2023-04-11 19:05:17 +02:00
Arthur Meyre
e3e7abd652 feat(integer): add default mul ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
4265fbe67e feat(integer): add "default" radix_parallel comparison ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
337400ce3d feat(integer): add "default" radix_parallel bitwise ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
be650d8e6b feat(integer): add "default" radix_parallel add ops 2023-04-11 19:05:17 +02:00
Arthur Meyre
47604a6297 feat(shortint): add "default" sub operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
95d6fc5b1b feat(shortint): add "default" shift operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
19a6855b82 chore(shortint): add default scalar ops tests 2023-04-11 19:01:12 +02:00
Arthur Meyre
f894c33bfd feat(shortint): add "default" scalar sub operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
6578aff8a4 feat(shortint): add "default" scalar mul operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
9096c62f32 feat(shortint): add "default" scalar add operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
22f186af17 feat(shortint): add "default" neg operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
7820523d1f feat(shortint): add "default" mul ops 2023-04-11 19:01:12 +02:00
Arthur Meyre
c0386c7e54 feat(shortint): add "default" div and mod operations 2023-04-11 19:01:12 +02:00
Arthur Meyre
1ea73a68c4 feat(shortint): add "default" comp_op 2023-04-11 19:01:12 +02:00
Arthur Meyre
6a02ae04e1 feat(shortint): add "default" bitwise ops 2023-04-11 19:01:12 +02:00
Arthur Meyre
becd11b45f feat(shortint): add "default" add and add_assign operators 2023-04-11 19:01:12 +02:00
Arthur Meyre
366964f1e6 feat(shortint): add function to check if a ciphertext has an empty carry 2023-04-11 19:01:12 +02:00
Arthur Meyre
32f8561af1 chore(tfhe): add devo profile to be able to iterate faster on tests 2023-04-11 19:01:12 +02:00
tmontaigu
063ad26b9e feat(tfhe): add CompressedPublicKey 2023-04-11 18:04:42 +02:00
tmontaigu
dba18a889a feat(hlapi): add 32, 64, 128 bits types 2023-04-11 16:58:32 +02:00
tmontaigu
0f5e1f0141 feat(c_api): add a C API of the high level API
One notable change is that since this C API
relies a lot on macro_rules! to be generated
we have to activate cbindgen's `expand` option,
which will use cargo-expand to expand macros.

However this means we can't call bindgen from the build.rs
as it seems to lead to a infinite-loop
(build.rs calls bindgen which calls cargo-expand which calls build.rs...)

So we call the cbindgen binary via the makefile.
2023-04-11 13:41:18 +02:00
J-B Orfila
d4c7aff90b fix(integer): fix unchecked_add in unchecked_mul 2023-04-07 15:55:08 +02:00
Arthur Meyre
1d9f8c57da chore(core): fix multi bit parameters 2023-04-07 11:55:33 +02:00
J-B Orfila
aa58748d33 refactor(integer): simplify PubliKey API 2023-04-07 11:55:33 +02:00
tmontaigu
412463ed27 chore(shortint): remove the Default impl for Parameters
The rationale behind this is that, `shortint::Parameters::default()`
does not convey the information about how much bit of message
and carry this parameter provides, and so might lead to
errors/confusions.

Instead user will be forced to use the param name like
`PARAM_MESSAGE_2_CARRY_2` which is less ambiguous.

This is obviously a breaking change.
2023-04-07 10:26:33 +02:00
sarah el kazdadi
72e7f16179 feat(core): implement 128bit pbs 2023-04-06 17:14:11 +02:00
Arthur Meyre
a1fcfcc55e chore(core): lower the noise in multibit test to avoid bad decryptions 2023-04-06 15:50:03 +02:00
Arthur Meyre
5ede4d6b0c chore(core): reverse the order in which we encrypt KS levels
- allows to avoid reversing the iterator, potentially improving cache
access during a keyswitch

BREAKING CHANGE: the keyswitch key level order has been reversed

TODO: fix the mismatch between DecompositionTerm and DecompositionIter for
the meaning of a decomposition level see
https://github.com/zama-ai/tfhe-rs-internal/issues/72
2023-04-06 14:47:29 +02:00
tmontaigu
9430e6dcf8 chore(integer): annotate decrypt_radix type in tests
When working on the integer part of the crate,
if you introduced a compile error (as is common when working stuff out)
the type inference of rust would not fully work and call to
`let dec = cks.decrypt_radix(&ctxt);` would fail to deduce the type
of `dec`.

This resulted on many errors in the compiler output about
"type annotation needed", requiring to scroll up a certain amount
to be able to see the errors messages you actually care about.

This commit adds these missing type annotation the the errors won't
appear, so as to have less noise.
2023-04-06 10:56:19 +02:00
tmontaigu
74f47e3655 feat(tfhe): add compressed ciphertexts in HL API 2023-04-05 16:55:28 +02:00
tmontaigu
0d57da7608 chore(tfhe): add typed_api test in ci 2023-04-05 16:48:42 +02:00
tmontaigu
25a43181e0 doc(tfhe): add high level api docs 2023-04-05 16:14:43 +02:00
tmontaigu
b8e64377fa doc(tfhe): add integer example + mention --release 2023-04-04 13:45:01 +02:00
David Testé
c206aa89b8 chore(ci): test core_crypto with avx512 2023-04-04 09:03:27 +02:00
Arthur Meyre
f39e318019 chore(core): update parameters for multi-bit PBS tests 2023-04-03 17:41:59 +02:00
Arthur Meyre
40b9497dbf chore(core): remove feature gate for multi-bit PBS 2023-04-03 17:41:59 +02:00
tmontaigu
e1cfb0e3f7 doc(integer): reorganize user documentation 2023-04-03 13:32:28 +02:00
tmontaigu
a410aaaed6 feat(typed_api): add missing Serialize/Deserialize
The "top level" key types (ClientKey, ServerKey and PublicKey)
were missing serde::{Serialize, Deserialize} implementations
2023-03-31 18:02:54 +02:00
tmontaigu
d7a4e87efb feat(typed_api): plug choice of big/small ciphertext 2023-03-31 16:29:34 +02:00
tmontaigu
3bc1536fa6 feat(integer): improve RadixClientKey 2023-03-31 16:29:33 +02:00
Arthur Meyre
6633496e7b chore(tfhe): remove mut keyword for cks and sks that don't need them 2023-03-30 16:19:17 +02:00
tmontaigu
14f7ca7492 feat(integer): plug shortint big/small in integer 2023-03-30 12:06:56 +02:00
David Testé
accd3cfb3f chore(ci): add windows as target build platform 2023-03-29 15:44:59 +02:00
Arthur Meyre
7f050c0fe9 chore(core_crypto): enable the choice of a single fixed fft algorithm 2023-03-29 12:48:49 +02:00
tmontaigu
c4769cbc0f fix(js): bump nvm 2023-03-27 12:17:07 +02:00
tmontaigu
1633eb573f feat(integer): parallelized bitwise operations 2023-03-27 12:17:07 +02:00
sarah el kazdadi
10174cdac6 feat(fft): update concrete-fft to 0.2.1 2023-03-27 11:00:37 +02:00
tmontaigu
475b838943 chore(makefile): add --all-targets switch to build command
This adds the --all-targets to the cargo build commands
invoked by the makefile so that when running
`make build_boolean`, lib, tests, benches, examples are built.

See the `cargo help build`

```
--all-targets
    Build all targets. This is equivalent to specifying --lib --bins --tests --benches --examples.
```
2023-03-27 10:59:49 +02:00
dependabot[bot]
1bdc447915 chore(deps): bump actions/checkout from 3.4.0 to 3.5.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.4.0 to 3.5.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](24cb908017...8f4b7f8486)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-27 09:49:45 +02:00
Arthur Meyre
a04d68f1fb feat(shortint): add support for small LWE key encryption 2023-03-23 16:45:39 +01:00
tmontaigu
42b569bcd7 feat(tfhe): add typed API
the `typed_api` module is basically the concrete 0.2 codebase
with modifications
2023-03-23 11:49:50 +01:00
tmontaigu
8999ea3766 chore(integer): add getters to client keys 2023-03-22 13:14:17 +01:00
tmontaigu
b0d059eef1 chore(boolean): add missing PublicKey derives 2023-03-22 13:14:16 +01:00
Arthur Meyre
64f9dc0813 refactor(tfhe): rename with_z function to with_correcting_term 2023-03-22 11:40:58 +01:00
David Testé
52afc382a0 fix(integer): stop decomposing before overflow
This only happens on binary scalar operations over 64bits of
precision.
2023-03-22 10:43:57 +01:00
tmontaigu
1e94d80044 fix(shortint): correct incoherences in bivariate pbs shifts
A bivariate PBS is a univariate PBS where we encode
the lhs, and rhs values into a singular value:
`univariate_value = (lhs * shift) + rhs`

Some places shifted the lhs by the parameter's message modulus
while others shifted by rhs.degree + 1, this could leed to incoherences
and wrong result in some cases.

The commits adds a `BivariateAccumulator` that stores the shift
value that was used to create the LUT, to avoid said incoherences.

Also, bivariate function family that expected
a univariate closure `Fn(u64) -> u64` will now expect a
bivariate closure `Fn(u64, u64) -> u64` so that they are less
error prone as the user does not need to figure out the
shift to be used.
2023-03-21 13:25:48 +01:00
Arthur Meyre
68fa6b78a4 feat(tfhe): introduce experimental feature approach for multi_bit_pbs 2023-03-20 16:47:33 +01:00
Arthur Meyre
75f05c0f3a feat(core): add multi-bit BSK generation and PBS threaded implementation 2023-03-20 16:47:33 +01:00
Arthur Meyre
bf6f699e8c refactor(fft): update fft code to use FourierPolynomialSize 2023-03-20 16:47:33 +01:00
Arthur Meyre
d3b3c5ab21 chore(core): fix ciphertext typo 2023-03-20 16:47:33 +01:00
Arthur Meyre
ceb26def05 feat(core): add constant GGSW ciphertext decryption 2023-03-20 16:47:33 +01:00
Arthur Meyre
638f210555 chore(core): fix typo 2023-03-20 16:47:33 +01:00
tmontaigu
1294727b11 chore(core_crypto): fix overflows in tests
These overflows appeared in debug builds,
and are easly fixed by using explicit wrapping operation
or correct values.
2023-03-20 12:44:15 +01:00
Arthur Meyre
e954247f1b chore(ci): CI at the speed of ligth
- use a 128 vcpu instance
- update script to have a no compromise test run
- update Makefile to be able to run the "no compromise" CI mode
2023-03-20 11:24:37 +01:00
dependabot[bot]
8d9ba2a1f9 chore(deps): bump actions/checkout from 3.3.0 to 3.4.0
Bumps [actions/checkout](https://github.com/actions/checkout) from 3.3.0 to 3.4.0.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](ac59398561...24cb908017)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-03-20 10:16:16 +01:00
sarah el kazdadi
34fc96319d fix(tfhe): fix faulty comparison in avx512 code 2023-03-17 16:14:41 +01:00
Arthur Meyre
13ad7d5468 chore(ci): change ubuntu mirror urls as the original ones are too slow 2023-03-16 17:18:08 +01:00
Arthur Meyre
9151eb72b3 chore(ci): silence skipped M1 tests due to cla-bot label 2023-03-16 17:17:57 +01:00
Rui LOPES
8d8b8ab511 fix(build): remove -- flag from make targets that do not use wasm-pack 2023-03-16 17:09:15 +01:00
Rui LOPES
0c30e7525a fix(build): pass the --features arguments to the wasm-pack command in Makefile js targets 2023-03-16 17:09:15 +01:00
tmontaigu
385c907807 fix(shortint): remove wrong large_mod in cmp operations 2023-03-13 13:22:02 +01:00
Arthur Meyre
6266d18211 chore(tfhe): fix typos 2023-03-13 09:54:41 +01:00
tmontaigu
0a39f369d2 fix(integer): make radix encryption / decryption work on big endian 2023-03-10 14:09:13 +01:00
tmontaigu
bb6663cfe5 chore(integer): simplify radix decryption 2023-03-09 15:44:33 +01:00
tmontaigu
06713fa42d fix(integer): make radix encryption work on big endian 2023-03-09 15:44:33 +01:00
tmontaigu
b59afc7eee feat(integer): add PublicKey 2023-03-09 15:44:33 +01:00
tmontaigu
2ede9fb852 chore(integer): move u256 into its own mod 2023-03-09 15:44:33 +01:00
tmontaigu
ccf21c1716 feat(integer): add compressed ciphertexts 2023-03-09 15:44:33 +01:00
tmontaigu
f3dc9e52f6 feat(integer): add min,max and comparisons ops 2023-03-09 15:44:33 +01:00
tmontaigu
195efaf09c chore(integer): refactor benches 2023-03-09 15:44:32 +01:00
tmontaigu
3c9325f939 feat(tfhe): arbitrary sized integer encryption 2023-03-08 09:47:19 +01:00
362 changed files with 45027 additions and 6836 deletions

View File

@@ -44,7 +44,7 @@ jobs:
echo "Type: ${{ github.event.inputs.instance_type }}"
echo "Request ID: ${{ github.event.inputs.request_id }}"
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
- name: Set up home
run: |
@@ -62,7 +62,7 @@ jobs:
- name: Run integer tests
run: |
make test_integer_ci
BIG_TESTS_INSTANCE=TRUE make test_integer_ci
- name: Slack Notification
if: ${{ always() }}

View File

@@ -44,7 +44,7 @@ jobs:
echo "Type: ${{ github.event.inputs.instance_type }}"
echo "Request ID: ${{ github.event.inputs.request_id }}"
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
- name: Set up home
run: |
@@ -58,7 +58,7 @@ jobs:
- name: Run core tests
run: |
make test_core_crypto
AVX512_SUPPORT=ON make test_core_crypto
- name: Run boolean tests
run: |
@@ -82,7 +82,11 @@ jobs:
- name: Run shortint tests
run: |
make test_shortint_ci
BIG_TESTS_INSTANCE=TRUE make test_shortint_ci
- name: Run high-level API tests
run: |
BIG_TESTS_INSTANCE=TRUE make test_high_level_api
- name: Slack Notification
if: ${{ always() }}

View File

@@ -5,24 +5,20 @@ on:
workflow_dispatch:
inputs:
instance_id:
description: 'Instance ID'
description: "Instance ID"
type: string
instance_image_id:
description: 'Instance AMI ID'
description: "Instance AMI ID"
type: string
instance_type:
description: 'Instance product type'
description: "Instance product type"
type: string
runner_name:
description: 'Action runner name'
description: "Action runner name"
type: string
request_id:
description: 'Slab request ID'
description: "Slab request ID"
type: string
matrix_item:
description: 'Build matrix item'
type: string
env:
CARGO_TERM_COLOR: always
@@ -40,14 +36,13 @@ jobs:
echo "AMI: ${{ inputs.instance_image_id }}"
echo "Type: ${{ inputs.instance_type }}"
echo "Request ID: ${{ inputs.request_id }}"
echo "Matrix item: ${{ inputs.matrix_item }}"
- name: Get benchmark date
run: |
echo "BENCH_DATE=$(date --iso-8601=seconds)" >> "${GITHUB_ENV}"
- name: Checkout tfhe-rs repo with tags
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
@@ -62,38 +57,24 @@ jobs:
toolchain: nightly
override: true
- name: Run benchmarks
- name: Run benchmarks with AVX512
run: |
make bench_boolean
make AVX512_SUPPORT=ON bench_boolean
- name: Parse results
run: |
COMMIT_DATE="$(git --no-pager show -s --format=%cd --date=iso8601-strict ${{ github.sha }})"
COMMIT_HASH="$(git describe --tags --dirty)"
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--database tfhe_rs_benchmarks \
--database tfhe_rs \
--hardware ${{ inputs.instance_type }} \
--project-version "${COMMIT_HASH}" \
--branch ${{ github.ref_name }} \
--commit-date "${COMMIT_DATE}" \
--bench-date "${{ env.BENCH_DATE }}" \
--throughput
- name: Remove previous raw results
run: |
rm -rf target/criterion
- name: Run benchmarks with AVX512
run: |
make AVX512_SUPPORT=ON bench_boolean
- name: Parse AVX512 results
run: |
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--hardware ${{ inputs.instance_type }} \
--walk-subdirs \
--name-suffix avx512 \
--throughput \
--append-results
--throughput
- name: Measure key sizes
run: |
@@ -104,7 +85,7 @@ jobs:
python3 ./ci/benchmark_parser.py tfhe/boolean_key_sizes.csv ${{ env.RESULTS_FILENAME }} \
--key-sizes \
--append-results
- name: Upload parsed results artifact
uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce
with:
@@ -112,7 +93,7 @@ jobs:
path: ${{ env.RESULTS_FILENAME }}
- name: Checkout Slab repo
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
repository: zama-ai/slab
path: slab
@@ -120,14 +101,16 @@ jobs:
- name: Send data to Slab
shell: bash
env:
COMPRESSED_RESULTS: ${{ env.RESULTS_FILENAME }}.gz
run: |
echo "Computing HMac on downloaded artifact"
echo "Computing HMac on results file"
SIGNATURE="$(slab/scripts/hmac_calculator.sh ${{ env.RESULTS_FILENAME }} '${{ secrets.JOB_SECRET }}')"
echo "Sending results to Slab..."
curl -v -k \
-H "Content-Type: application/json" \
-H "X-Slab-Repository: ${{ github.repository }}" \
-H "X-Slab-Command: store_data" \
-H "X-Slab-Command: store_data_v2" \
-H "X-Hub-Signature-256: sha256=${SIGNATURE}" \
-d @${{ env.RESULTS_FILENAME }} \
${{ secrets.SLAB_URL }}

View File

@@ -17,21 +17,21 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest, macos-latest]
os: [ubuntu-latest, macos-latest, windows-latest]
fail-fast: false
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- name: Get rust toolchain to use for checks and lints
id: toolchain
run: |
echo "rs-toolchain=$(make rs_toolchain)" >> "${GITHUB_OUTPUT}"
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
- name: Run pcc checks
run: |
make pcc
- name: Build Release core
run: |
make build_core AVX512_SUPPORT=ON
make build_core_experimental AVX512_SUPPORT=ON
- name: Build Release boolean
run: |
make build_boolean

104
.github/workflows/integer_benchmark.yml vendored Normal file
View File

@@ -0,0 +1,104 @@
# Run integer benchmarks on an AWS instance and return parsed results to Slab CI bot.
name: Integer benchmarks
on:
workflow_dispatch:
inputs:
instance_id:
description: "Instance ID"
type: string
instance_image_id:
description: "Instance AMI ID"
type: string
instance_type:
description: "Instance product type"
type: string
runner_name:
description: "Action runner name"
type: string
request_id:
description: "Slab request ID"
type: string
env:
CARGO_TERM_COLOR: always
RESULTS_FILENAME: parsed_benchmark_results_${{ github.sha }}.json
jobs:
run-integer-benchmarks:
name: Execute integer benchmarks in EC2
runs-on: ${{ github.event.inputs.runner_name }}
if: ${{ !cancelled() }}
steps:
- name: Instance configuration used
run: |
echo "IDs: ${{ inputs.instance_id }}"
echo "AMI: ${{ inputs.instance_image_id }}"
echo "Type: ${{ inputs.instance_type }}"
echo "Request ID: ${{ inputs.request_id }}"
- name: Get benchmark date
run: |
echo "BENCH_DATE=$(date --iso-8601=seconds)" >> "${GITHUB_ENV}"
- name: Checkout tfhe-rs repo with tags
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
- name: Set up home
# "Install rust" step require root user to have a HOME directory which is not set.
run: |
echo "HOME=/home/ubuntu" >> "${GITHUB_ENV}"
- name: Install rust
uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af
with:
toolchain: nightly
override: true
- name: Run benchmarks with AVX512
run: |
make AVX512_SUPPORT=ON bench_integer
- name: Parse results
run: |
COMMIT_DATE="$(git --no-pager show -s --format=%cd --date=iso8601-strict ${{ github.sha }})"
COMMIT_HASH="$(git describe --tags --dirty)"
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--database tfhe_rs \
--hardware ${{ inputs.instance_type }} \
--project-version "${COMMIT_HASH}" \
--branch ${{ github.ref_name }} \
--commit-date "${COMMIT_DATE}" \
--bench-date "${{ env.BENCH_DATE }}" \
--walk-subdirs \
--name-suffix avx512 \
--throughput
- name: Upload parsed results artifact
uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce
with:
name: ${{ github.sha }}_integer
path: ${{ env.RESULTS_FILENAME }}
- name: Checkout Slab repo
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
repository: zama-ai/slab
path: slab
token: ${{ secrets.CONCRETE_ACTIONS_TOKEN }}
- name: Send data to Slab
shell: bash
run: |
echo "Computing HMac on results file"
SIGNATURE="$(slab/scripts/hmac_calculator.sh ${{ env.RESULTS_FILENAME }} '${{ secrets.JOB_SECRET }}')"
echo "Sending results to Slab..."
curl -v -k \
-H "Content-Type: application/json" \
-H "X-Slab-Repository: ${{ github.repository }}" \
-H "X-Slab-Command: store_data_v2" \
-H "X-Hub-Signature-256: sha256=${SIGNATURE}" \
-d @${{ env.RESULTS_FILENAME }} \
${{ secrets.SLAB_URL }}

View File

@@ -20,7 +20,7 @@ jobs:
runs-on: ["self-hosted", "m1mac"]
steps:
- uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
- uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
- name: Install latest stable
uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af
@@ -32,6 +32,10 @@ jobs:
run: |
make pcc
- name: Build Release core
run: |
make build_core
- name: Build Release boolean
run: |
make build_boolean
@@ -96,7 +100,7 @@ jobs:
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Slack Notification
if: ${{ always() }}
if: ${{ needs.cargo-builds.result != 'skipped' }}
continue-on-error: true
uses: rtCamp/action-slack-notify@12e36fc18b0689399306c2e0b3e0f2978b7f1ee7
env:

52
.github/workflows/make_release.yml vendored Normal file
View File

@@ -0,0 +1,52 @@
# Publish new release of tfhe-rs on various platform.
name: Publish release
on:
workflow_dispatch:
inputs:
dry_run:
description: "Dry-run"
type: boolean
default: true
jobs:
publish_release:
name: Publish Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
- name: Publish crate.io package
env:
CRATES_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
DRY_RUN: ${{ inputs.dry_run && '--dry-run' || '' }}
run: |
cargo publish -p tfhe --token ${{ env.CRATES_TOKEN }} ${{ env.DRY_RUN }}
- name: Build web package
run: |
make build_web_js_api
- name: Publish web package
uses: JS-DevTools/npm-publish@541aa6b21b4a1e9990c95a92c21adc16b35e9551
with:
token: ${{ secrets.NPM_TOKEN }}
package: tfhe/pkg/package.json
dry-run: ${{ inputs.dry_run }}
- name: Build Node package
run: |
rm -rf tfhe/pkg
make build_node_js_api
sed -i 's/"tfhe"/"node-tfhe"/g' tfhe/pkg/package.json
- name: Publish Node package
uses: JS-DevTools/npm-publish@541aa6b21b4a1e9990c95a92c21adc16b35e9551
with:
token: ${{ secrets.NPM_TOKEN }}
package: tfhe/pkg/package.json
dry-run: ${{ inputs.dry_run }}

View File

@@ -5,22 +5,21 @@ on:
workflow_dispatch:
inputs:
instance_id:
description: 'Instance ID'
description: "Instance ID"
type: string
instance_image_id:
description: 'Instance AMI ID'
description: "Instance AMI ID"
type: string
instance_type:
description: 'Instance product type'
description: "Instance product type"
type: string
runner_name:
description: 'Action runner name'
description: "Action runner name"
type: string
request_id:
description: 'Slab request ID'
description: "Slab request ID"
type: string
env:
CARGO_TERM_COLOR: always
RESULTS_FILENAME: parsed_benchmark_results_${{ github.sha }}.json
@@ -43,7 +42,7 @@ jobs:
echo "BENCH_DATE=$(date --iso-8601=seconds)" >> "${GITHUB_ENV}"
- name: Checkout tfhe-rs repo with tags
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
@@ -67,13 +66,14 @@ jobs:
COMMIT_DATE="$(git --no-pager show -s --format=%cd --date=iso8601-strict ${{ github.sha }})"
COMMIT_HASH="$(git describe --tags --dirty)"
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--database tfhe_rs_benchmarks \
--database tfhe_rs \
--hardware ${{ inputs.instance_type }} \
--project-version "${COMMIT_HASH}" \
--branch ${{ github.ref_name }} \
--commit-date "${COMMIT_DATE}" \
--bench-date "${{ env.BENCH_DATE }}" \
--name-suffix avx512 \
--walk-subdirs \
--throughput
- name: Upload parsed results artifact
@@ -83,7 +83,7 @@ jobs:
path: ${{ env.RESULTS_FILENAME }}
- name: Checkout Slab repo
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
repository: zama-ai/slab
path: slab
@@ -98,7 +98,7 @@ jobs:
curl -v -k \
-H "Content-Type: application/json" \
-H "X-Slab-Repository: ${{ github.repository }}" \
-H "X-Slab-Command: store_data" \
-H "X-Slab-Command: store_data_v2" \
-H "X-Hub-Signature-256: sha256=${SIGNATURE}" \
-d @${{ env.RESULTS_FILENAME }} \
${{ secrets.SLAB_URL }}

View File

@@ -5,24 +5,20 @@ on:
workflow_dispatch:
inputs:
instance_id:
description: 'Instance ID'
description: "Instance ID"
type: string
instance_image_id:
description: 'Instance AMI ID'
description: "Instance AMI ID"
type: string
instance_type:
description: 'Instance product type'
description: "Instance product type"
type: string
runner_name:
description: 'Action runner name'
description: "Action runner name"
type: string
request_id:
description: 'Slab request ID'
description: "Slab request ID"
type: string
matrix_item:
description: 'Build matrix item'
type: string
env:
CARGO_TERM_COLOR: always
@@ -40,14 +36,13 @@ jobs:
echo "AMI: ${{ inputs.instance_image_id }}"
echo "Type: ${{ inputs.instance_type }}"
echo "Request ID: ${{ inputs.request_id }}"
echo "Matrix item: ${{ inputs.matrix_item }}"
- name: Get benchmark date
run: |
echo "BENCH_DATE=$(date --iso-8601=seconds)" >> "${GITHUB_ENV}"
- name: Checkout tfhe-rs repo with tags
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
@@ -62,40 +57,24 @@ jobs:
toolchain: nightly
override: true
- name: Run benchmarks
- name: Run benchmarks with AVX512
run: |
make bench_shortint
make AVX512_SUPPORT=ON bench_shortint
- name: Parse results
run: |
COMMIT_DATE="$(git --no-pager show -s --format=%cd --date=iso8601-strict ${{ github.sha }})"
COMMIT_HASH="$(git describe --tags --dirty)"
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--database tfhe_rs_benchmarks \
--database tfhe_rs \
--hardware ${{ inputs.instance_type }} \
--project-version "${COMMIT_HASH}" \
--branch ${{ github.ref_name }} \
--commit-date "${COMMIT_DATE}" \
--bench-date "${{ env.BENCH_DATE }}" \
--walk-subdirs \
--throughput
- name: Remove previous raw results
run: |
rm -rf target/criterion
- name: Run benchmarks with AVX512
run: |
make AVX512_SUPPORT=ON bench_shortint
- name: Parse AVX512 results
run: |
python3 ./ci/benchmark_parser.py target/criterion ${{ env.RESULTS_FILENAME }} \
--hardware ${{ inputs.instance_type }} \
--walk-subdirs \
--name-suffix avx512 \
--throughput \
--append-results
--throughput
- name: Measure key sizes
run: |
@@ -114,7 +93,7 @@ jobs:
path: ${{ env.RESULTS_FILENAME }}
- name: Checkout Slab repo
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
repository: zama-ai/slab
path: slab
@@ -123,13 +102,13 @@ jobs:
- name: Send data to Slab
shell: bash
run: |
echo "Computing HMac on downloaded artifact"
echo "Computing HMac on results file"
SIGNATURE="$(slab/scripts/hmac_calculator.sh ${{ env.RESULTS_FILENAME }} '${{ secrets.JOB_SECRET }}')"
echo "Sending results to Slab..."
curl -v -k \
-H "Content-Type: application/json" \
-H "X-Slab-Repository: ${{ github.repository }}" \
-H "X-Slab-Command: store_data" \
-H "X-Slab-Command: store_data_v2" \
-H "X-Hub-Signature-256: sha256=${SIGNATURE}" \
-d @${{ env.RESULTS_FILENAME }} \
${{ secrets.SLAB_URL }}

View File

@@ -11,11 +11,11 @@ jobs:
start-benchmarks:
strategy:
matrix:
command: [boolean_bench, shortint_bench, pbs_bench]
command: [boolean_bench, shortint_bench, integer_bench, pbs_bench]
runs-on: ubuntu-latest
steps:
- name: Checkout Slab repo
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
repository: zama-ai/slab
path: slab
@@ -23,11 +23,11 @@ jobs:
- name: Start AWS job in Slab
shell: bash
# TODO: step result must be correlated to HTTP return code.
run: |
echo -n '{"command": "${{ matrix.command }}", "git_ref": "${{ github.ref }}", "sha": "${{ github.sha }}"}' > command.json
SIGNATURE="$(slab/scripts/hmac_calculator.sh command.json '${{ secrets.JOB_SECRET }}')"
curl -v -k \
--fail-with-body \
-H "Content-Type: application/json" \
-H "X-Slab-Repository: ${{ github.repository }}" \
-H "X-Slab-Command: start_aws" \

View File

@@ -13,7 +13,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c
uses: actions/checkout@8e5e7e5ab8b370d6c329ec480221332ada57f0ab
with:
fetch-depth: 0
- name: Save repo

7
.gitignore vendored
View File

@@ -3,9 +3,12 @@ target/
.vscode/
# Path we use for internal-keycache during tests
keys/
./keys/
# In case of symlinked keys
keys
./keys
**/Cargo.lock
**/*.bin
# Some of our bench outputs
/tfhe/benchmarks_parameters

View File

@@ -7,3 +7,9 @@ lto = "fat"
[profile.release]
lto = "fat"
# Compiles much faster for tests and allows reasonable performance for iterating
[profile.devo]
inherits = "dev"
opt-level = 3
lto = "off"

121
Makefile
View File

@@ -1,13 +1,16 @@
SHELL:=$(shell /usr/bin/env which bash)
OS:=$(shell uname)
RS_CHECK_TOOLCHAIN:=$(shell cat toolchain.txt | tr -d '\n')
CARGO_RS_CHECK_TOOLCHAIN:=+$(RS_CHECK_TOOLCHAIN)
TARGET_ARCH_FEATURE:=$(shell ./scripts/get_arch_feature.sh)
RS_BUILD_TOOLCHAIN:=$(shell \
( (echo $(TARGET_ARCH_FEATURE) | grep -q x86) && echo stable) || echo $(RS_CHECK_TOOLCHAIN))
CARGO_RS_BUILD_TOOLCHAIN:=+$(RS_BUILD_TOOLCHAIN)
CARGO_PROFILE?=release
MIN_RUST_VERSION:=1.65
AVX512_SUPPORT?=OFF
WASM_RUSTFLAGS:=
BIG_TESTS_INSTANCE?=FALSE
# This is done to avoid forgetting it, we still precise the RUSTFLAGS in the commands to be able to
# copy paste the command in the terminal and change them if required without forgetting the flags
export RUSTFLAGS?=-C target-cpu=native
@@ -49,6 +52,12 @@ install_cargo_nextest: install_rs_build_toolchain
cargo $(CARGO_RS_BUILD_TOOLCHAIN) install cargo-nextest --locked || \
( echo "Unable to install cargo nextest, unknown error." && exit 1 )
.PHONY: install_wasm_pack # Install wasm-pack to build JS packages
install_wasm_pack: install_rs_build_toolchain
@wasm-pack --version > /dev/null 2>&1 || \
cargo $(CARGO_RS_BUILD_TOOLCHAIN) install wasm-pack || \
( echo "Unable to install cargo wasm-pack, unknown error." && exit 1 )
.PHONY: fmt # Format rust code
fmt: install_rs_check_toolchain
cargo "$(CARGO_RS_CHECK_TOOLCHAIN)" fmt
@@ -57,6 +66,15 @@ fmt: install_rs_check_toolchain
check_fmt: install_rs_check_toolchain
cargo "$(CARGO_RS_CHECK_TOOLCHAIN)" fmt --check
.PHONY: clippy_core # Run clippy lints on core_crypto with and without experimental features
clippy_core: install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo "$(CARGO_RS_CHECK_TOOLCHAIN)" clippy \
--features=$(TARGET_ARCH_FEATURE) \
-p tfhe -- --no-deps -D warnings
RUSTFLAGS="$(RUSTFLAGS)" cargo "$(CARGO_RS_CHECK_TOOLCHAIN)" clippy \
--features=$(TARGET_ARCH_FEATURE),experimental \
-p tfhe -- --no-deps -D warnings
.PHONY: clippy_boolean # Run clippy lints enabling the boolean features
clippy_boolean: install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo "$(CARGO_RS_CHECK_TOOLCHAIN)" clippy \
@@ -106,61 +124,87 @@ clippy_all_targets:
.PHONY: clippy_all # Run all clippy targets
clippy_all: clippy clippy_boolean clippy_shortint clippy_integer clippy_all_targets clippy_c_api \
clippy_js_wasm_api clippy_tasks
clippy_js_wasm_api clippy_tasks clippy_core
.PHONY: clippy_fast # Run main clippy targets
clippy_fast: clippy clippy_all_targets clippy_c_api clippy_js_wasm_api clippy_tasks clippy_core
.PHONY: gen_key_cache # Run the script to generate keys and cache them for shortint tests
gen_key_cache: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) run --release \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) run --profile $(CARGO_PROFILE) \
--example generates_test_keys \
--features=$(TARGET_ARCH_FEATURE),shortint,internal-keycache -p tfhe
.PHONY: build_core # Build core_crypto without experimental features
build_core: install_rs_build_toolchain install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE) -p tfhe
@if [[ "$(AVX512_SUPPORT)" == "ON" ]]; then \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),$(AVX512_FEATURE) -p tfhe; \
fi
.PHONY: build_core_experimental # Build core_crypto with experimental features
build_core_experimental: install_rs_build_toolchain install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),experimental -p tfhe
@if [[ "$(AVX512_SUPPORT)" == "ON" ]]; then \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),experimental,$(AVX512_FEATURE) -p tfhe; \
fi
.PHONY: build_boolean # Build with boolean enabled
build_boolean: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --release \
--features=$(TARGET_ARCH_FEATURE),boolean -p tfhe
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),boolean -p tfhe --all-targets
.PHONY: build_shortint # Build with shortint enabled
build_shortint: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --release \
--features=$(TARGET_ARCH_FEATURE),shortint -p tfhe
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),shortint -p tfhe --all-targets
.PHONY: build_integer # Build with integer enabled
build_integer: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --release \
--features=$(TARGET_ARCH_FEATURE),integer -p tfhe
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),integer -p tfhe --all-targets
.PHONY: build_tfhe_full # Build with boolean, shortint and integer enabled
build_tfhe_full: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --release \
--features=$(TARGET_ARCH_FEATURE),boolean,shortint,integer -p tfhe
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),boolean,shortint,integer -p tfhe --all-targets
.PHONY: build_c_api # Build the C API for boolean and shortint
build_c_api: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) build --release \
--features=$(TARGET_ARCH_FEATURE),boolean-c-api,shortint-c-api -p tfhe
build_c_api: install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) build --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),boolean-c-api,shortint-c-api,high-level-c-api \
-p tfhe
.PHONY: build_web_js_api # Build the js API targeting the web browser
build_web_js_api: install_rs_build_toolchain
build_web_js_api: install_rs_build_toolchain install_wasm_pack
cd tfhe && \
RUSTFLAGS="$(WASM_RUSTFLAGS)" rustup run "$(RS_BUILD_TOOLCHAIN)" \
wasm-pack build --release --target=web \
--features=boolean-client-js-wasm-api,shortint-client-js-wasm-api
-- --features=boolean-client-js-wasm-api,shortint-client-js-wasm-api
.PHONY: build_node_js_api # Build the js API targeting nodejs
build_node_js_api: install_rs_build_toolchain
build_node_js_api: install_rs_build_toolchain install_wasm_pack
cd tfhe && \
RUSTFLAGS="$(WASM_RUSTFLAGS)" rustup run "$(RS_BUILD_TOOLCHAIN)" \
wasm-pack build --release --target=nodejs \
--features=boolean-client-js-wasm-api,shortint-client-js-wasm-api
-- --features=boolean-client-js-wasm-api,shortint-client-js-wasm-api
.PHONY: test_core_crypto # Run the tests of the core_crypto module
test_core_crypto: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --release \
--features=$(TARGET_ARCH_FEATURE) -p tfhe -- core_crypto::
.PHONY: test_core_crypto # Run the tests of the core_crypto module including experimental ones
test_core_crypto: install_rs_build_toolchain install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),experimental -p tfhe -- core_crypto::
@if [[ "$(AVX512_SUPPORT)" == "ON" ]]; then \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),experimental,$(AVX512_FEATURE) -p tfhe -- core_crypto::; \
fi
.PHONY: test_boolean # Run the tests of the boolean module
test_boolean: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --release \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),boolean -p tfhe -- boolean::
.PHONY: test_c_api # Run the tests for the C API
@@ -169,25 +213,32 @@ test_c_api: build_c_api
.PHONY: test_shortint_ci # Run the tests for shortint ci
test_shortint_ci: install_rs_build_toolchain install_cargo_nextest
./scripts/shortint-tests.sh $(CARGO_RS_BUILD_TOOLCHAIN)
BIG_TESTS_INSTANCE="$(BIG_TESTS_INSTANCE)" \
./scripts/shortint-tests.sh $(CARGO_RS_BUILD_TOOLCHAIN)
.PHONY: test_shortint # Run all the tests for shortint
test_shortint: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --release \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),shortint,internal-keycache -p tfhe -- shortint::
.PHONY: test_integer_ci # Run the tests for integer ci
test_integer_ci: install_rs_build_toolchain install_cargo_nextest
./scripts/integer-tests.sh $(CARGO_RS_BUILD_TOOLCHAIN)
BIG_TESTS_INSTANCE="$(BIG_TESTS_INSTANCE)" \
./scripts/integer-tests.sh $(CARGO_RS_BUILD_TOOLCHAIN)
.PHONY: test_integer # Run all the tests for integer
test_integer: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --release \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),integer,internal-keycache -p tfhe -- integer::
.PHONY: test_high_level_api # Run all the tests for high_level_api
test_high_level_api: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) \
--features=$(TARGET_ARCH_FEATURE),boolean,shortint,integer,internal-keycache -p tfhe -- high_level_api::
.PHONY: test_user_doc # Run tests from the .md documentation
test_user_doc: install_rs_build_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --release --doc \
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --profile $(CARGO_PROFILE) --doc \
--features=$(TARGET_ARCH_FEATURE),boolean,shortint,integer,internal-keycache -p tfhe \
-- test_user_docs::
@@ -209,8 +260,11 @@ format_doc_latex:
.PHONY: check_compile_tests # Build tests in debug without running them
check_compile_tests: build_c_api
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_BUILD_TOOLCHAIN) test --no-run \
--features=$(TARGET_ARCH_FEATURE),boolean,shortint,integer,internal-keycache -p tfhe && \
./scripts/c_api_tests.sh --build-only
--features=$(TARGET_ARCH_FEATURE),experimental,boolean,shortint,integer,internal-keycache \
-p tfhe
@if [[ "$(OS)" == "Linux" || "$(OS)" == "Darwin" ]]; then \
./scripts/c_api_tests.sh --build-only; \
fi
.PHONY: build_nodejs_test_docker # Build a docker image with tools to run nodejs tests for wasm API
build_nodejs_test_docker:
@@ -236,6 +290,12 @@ test_nodejs_wasm_api: build_node_js_api
no_tfhe_typo:
@./scripts/no_tfhe_typo.sh
.PHONY: bench_integer # Run benchmarks for integer
bench_integer: install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) bench \
--bench integer-bench \
--features=$(TARGET_ARCH_FEATURE),integer,internal-keycache,$(AVX512_FEATURE) -p tfhe
.PHONY: bench_shortint # Run benchmarks for shortint
bench_shortint: install_rs_check_toolchain
RUSTFLAGS="$(RUSTFLAGS)" cargo $(CARGO_RS_CHECK_TOOLCHAIN) bench \
@@ -269,6 +329,9 @@ measure_boolean_key_sizes: install_rs_check_toolchain
.PHONY: pcc # pcc stands for pre commit checks
pcc: no_tfhe_typo check_fmt doc clippy_all check_compile_tests
.PHONY: fpcc # pcc stands for pre commit checks, the f stands for fast
fpcc: no_tfhe_typo check_fmt doc clippy_fast check_compile_tests
.PHONY: conformance # Automatically fix problems that can be fixed
conformance: fmt

View File

@@ -1,31 +1,25 @@
<p align="center">
<!-- product name logo -->
<img width=600 src="https://user-images.githubusercontent.com/86411313/201107820-b1b861be-6b3f-46cc-bccd-ed051201781a.png">
<img width=600 src="https://user-images.githubusercontent.com/5758427/231206749-8f146b97-3c5a-4201-8388-3ffa88580415.png">
</p>
<hr/>
<p align="center">
<a href="https://docs.zama.ai/tfhe-rs"> 📒 Read documentation</a> | <a href="https://zama.ai/community"> 💛 Community support</a>
</p>
<p align="center">
<!-- Version badge using shields.io -->
<a href="https://github.com/zama-ai/tfhe-rs/releases">
<img src="https://img.shields.io/github/v/release/zama-ai/tfhe-rs?style=flat-square">
</a>
<!-- Link to docs badge using shields.io -->
<a href="https://docs.zama.ai/tfhe-rs">
<img src="https://img.shields.io/badge/read-documentation-yellow?style=flat-square">
</a>
<!-- Community forum badge using shields.io -->
<a href="https://community.zama.ai">
<img src="https://img.shields.io/badge/community%20forum-online-brightgreen?style=flat-square">
</a>
<!-- Open source badge using shields.io -->
<a href="https://docs.zama.ai/tfhe-rs/developers/contributing">
<img src="https://img.shields.io/badge/we're%20open%20source-contributing.md-blue?style=flat-square">
</a>
<!-- Follow on twitter badge using shields.io -->
<a href="https://twitter.com/zama_fhe">
<img src="https://img.shields.io/badge/follow-zama_fhe-blue?logo=twitter&style=flat-square">
<!-- Zama Bounty Program -->
<a href="https://github.com/zama-ai/bounty-program">
<img src="https://img.shields.io/badge/Contribute-Zama%20Bounty%20Program-yellow?style=flat-square">
</a>
</p>
<hr/>
**TFHE-rs** is a pure Rust implementation of TFHE for boolean and small integer
**TFHE-rs** is a pure Rust implementation of TFHE for boolean and integer
arithmetics over encrypted data. It includes:
- a **Rust** API
- a **C** API
@@ -63,27 +57,31 @@ tfhe = { version = "*", features = ["boolean", "shortint", "integer", "x86_64"]
Note: aarch64-based machines are not yet supported for Windows as it's currently missing an entropy source to be able to seed the [CSPRNGs](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) used in TFHE-rs
Note that when running code that uses `tfhe-rs`, it is highly recommended
to run in release mode with cargo's `--release` flag to have the best performances possible,
eg: `cargo run --release`.
Here is a full example evaluating a Boolean circuit:
```rust
use tfhe::boolean::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
// We generate a set of client/server keys, using the default parameters:
let (mut client_key, mut server_key) = gen_keys();
// We use the client secret key to encrypt two messages:
// We use the client secret key to encrypt two messages:
let ct_1 = client_key.encrypt(true);
let ct_2 = client_key.encrypt(false);
// We use the server public key to execute a boolean circuit:
// if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
// We use the server public key to execute a boolean circuit:
// if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
let ct_3 = server_key.not(&ct_2);
let ct_4 = server_key.and(&ct_1, &ct_2);
let ct_5 = server_key.nand(&ct_3, &ct_4);
let ct_6 = server_key.mux(&ct_5, &ct_3, &ct_4);
// We use the client key to decrypt the output of the circuit:
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_6);
assert_eq!(output, true);
}
@@ -95,8 +93,9 @@ Another example of how the library can be used with shortints:
use tfhe::shortint::prelude::*;
fn main() {
// Generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(Parameters::default());
// Generate a set of client/server keys
// with 2 bits of message and 2 bits of carry
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 3;
let msg2 = 2;
@@ -116,7 +115,7 @@ fn main() {
let acc = server_key.generate_accumulator(f);
// Compute the function over the ciphertext using the PBS
let ct_res = server_key.keyswitch_programmable_bootstrap(&ct_add, &acc);
let ct_res = server_key.apply_lookup_table(&ct_add, &acc);
// Decrypt the ciphertext using the (private) client key
let output = client_key.decrypt(&ct_res);
@@ -124,6 +123,30 @@ fn main() {
}
```
An example using integer:
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We create keys to create 16 bits integers
// using 8 blocks of 2 bits
let (cks, sks) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, 8);
let clear_a = 2382u16;
let clear_b = 29374u16;
let mut a = cks.encrypt(clear_a as u64);
let mut b = cks.encrypt(clear_b as u64);
let encrypted_max = sks.smart_max_parallelized(&mut a, &mut b);
let decrypted_max: u64 = cks.decrypt(&encrypted_max);
assert_eq!(decrypted_max as u16, clear_a.max(clear_b))
}
```
## Contributing
There are two ways to contribute to TFHE-rs:
@@ -139,6 +162,11 @@ Only approved contributors can send pull requests, so please make sure to get in
This library uses several dependencies and we would like to thank the contributors of those
libraries.
## Need support?
<a target="_blank" href="https://community.zama.ai">
<img src="https://user-images.githubusercontent.com/5758427/231115030-21195b55-2629-4c01-9809-be5059243999.png">
</a>
## License
This software is distributed under the BSD-3-Clause-Clear license. If you have any questions,

View File

@@ -42,6 +42,8 @@ parser.add_argument('--key-sizes', dest='key_sizes', action='store_true',
parser.add_argument('--throughput', dest='throughput', action='store_true',
help='Compute and append number of operations per millisecond and'
'operations per dollar')
parser.add_argument('--backend', dest='backend', default='cpu',
help='Backend on which benchmarks have run')
def recursive_parse(directory, walk_subdirs=False, name_suffix="", compute_throughput=False,
@@ -57,39 +59,95 @@ def recursive_parse(directory, walk_subdirs=False, name_suffix="", compute_throu
dollar
:param hardware_hourly_cost: hourly cost of the hardware used in dollar
:return: :class:`list` of data points
:return: tuple of :class:`list` as (data points, parsing failures)
"""
excluded_directories = ["child_generate", "fork", "parent_generate", "report"]
result_values = []
parsing_failures = []
bench_class = "evaluate"
for dire in directory.iterdir():
if dire.name in excluded_directories or not dire.is_dir():
continue
for subdir in dire.iterdir():
if walk_subdirs:
subdir = subdir.joinpath("new")
if not subdir.exists():
continue
if subdir.name == "new":
pass
else:
subdir = subdir.joinpath("new")
if not subdir.exists():
continue
elif subdir.name != "new":
continue
test_name = parse_benchmark_file(subdir)
full_name, test_name = parse_benchmark_file(subdir)
if test_name is None:
parsing_failures.append((full_name, "'function_id' field is null in report"))
continue
try:
params, display_name, operator = get_parameters(test_name)
except Exception as err:
parsing_failures.append((full_name, f"failed to get parameters: {err}"))
continue
for stat_name, value in parse_estimate_file(subdir).items():
test_name_parts = list(filter(None, [test_name, stat_name, name_suffix]))
result_values.append({"value": value, "test": "_".join(test_name_parts)})
result_values.append(
_create_point(
value,
"_".join(test_name_parts),
bench_class,
"latency",
operator,
params,
display_name=display_name
)
)
if stat_name == "mean" and compute_throughput:
test_name_parts.append("ops-per-ms")
result_values.append({"value": compute_ops_per_millisecond(value),
"test": "_".join(test_name_parts)})
test_suffix = "ops-per-ms"
test_name_parts.append(test_suffix)
result_values.append(
_create_point(
compute_ops_per_millisecond(value),
"_".join(test_name_parts),
bench_class,
"throughput",
operator,
params,
display_name="_".join([display_name, test_suffix])
)
)
test_name_parts.pop()
if hardware_hourly_cost is not None:
test_name_parts.append("ops-per-dollar")
result_values.append({
"value": compute_ops_per_dollar(value, hardware_hourly_cost),
"test": "_".join(test_name_parts)})
test_suffix = "ops-per-dollar"
test_name_parts.append(test_suffix)
result_values.append(
_create_point(
compute_ops_per_dollar(value, hardware_hourly_cost),
"_".join(test_name_parts),
bench_class,
"throughput",
operator,
params,
display_name="_".join([display_name, test_suffix])
)
)
return result_values
return result_values, parsing_failures
def _create_point(value, test_name, bench_class, bench_type, operator, params, display_name=None):
return {
"value": value,
"test": test_name,
"name": display_name,
"class": bench_class,
"type": bench_type,
"operator": operator,
"params": params}
def parse_benchmark_file(directory):
@@ -101,7 +159,7 @@ def parse_benchmark_file(directory):
:return: name of the test as :class:`str`
"""
raw_res = _parse_file_to_json(directory, "benchmark.json")
return raw_res["full_id"].replace(" ", "_")
return raw_res["full_id"], raw_res["function_id"]
def parse_estimate_file(directory):
@@ -125,15 +183,51 @@ def parse_key_sizes(result_file):
:param result_file: results file as :class:`pathlib.Path`
:return: :class:`list` of data points
:return: tuple of :class:`list` as (data points, parsing failures)
"""
result_values = []
parsing_failures = []
with result_file.open() as csv_file:
reader = csv.reader(csv_file)
for (test_name, value) in reader:
result_values.append({"value": int(value), "test": test_name})
try:
params, display_name, operator = get_parameters(test_name)
except Exception as err:
parsing_failures.append((test_name, f"failed to get parameters: {err}"))
continue
return result_values
result_values.append({
"value": int(value),
"test": test_name,
"name": display_name,
"class": "keygen",
"type": "keysize",
"operator": operator,
"params": params})
return result_values, parsing_failures
def get_parameters(bench_id):
"""
Get benchmarks parameters recorded for a given benchmark case.
:param bench_id: function name used for the benchmark case
:return: :class:`tuple` as ``(benchmark parameters, display name, operator type)``
"""
params_dir = pathlib.Path("tfhe", "benchmarks_parameters", bench_id)
params = _parse_file_to_json(params_dir, "parameters.json")
display_name = params.pop("display_name")
operator = params.pop("operator_type")
# Put cryptographic parameters at the same level as the others parameters
crypto_params = params.pop("crypto_parameters")
params.update(crypto_params)
return params, display_name, operator
def compute_ops_per_dollar(data_point, product_hourly_cost):
@@ -172,6 +266,9 @@ def dump_results(parsed_results, filename, input_args):
:param filename: filename for dump file as :class:`pathlib.Path`
:param input_args: CLI input arguments
"""
for point in parsed_results:
point["backend"] = input_args.backend
if input_args.append_results:
parsed_content = json.loads(filename.read_text())
parsed_content["points"].extend(parsed_results)
@@ -219,6 +316,7 @@ if __name__ == "__main__":
args = parser.parse_args()
check_mandatory_args(args)
#failures = []
raw_results = pathlib.Path(args.results)
if not args.key_sizes:
print("Parsing benchmark results... ")
@@ -234,11 +332,11 @@ if __name__ == "__main__":
print(f"Cannot find hardware hourly cost for '{args.hardware}'")
sys.exit(1)
results = recursive_parse(raw_results, args.walk_subdirs, args.name_suffix, args.throughput,
hardware_cost)
results, failures = recursive_parse(raw_results, args.walk_subdirs, args.name_suffix,
args.throughput, hardware_cost)
else:
print("Parsing key sizes results... ")
results = parse_key_sizes(raw_results)
results, failures = parse_key_sizes(raw_results)
print("Parsing results done")
output_file = pathlib.Path(args.output_file)
@@ -246,3 +344,10 @@ if __name__ == "__main__":
dump_results(results, output_file, args)
print("Done")
if failures:
print("\nParsing failed for some results")
print("-------------------------------")
for name, error in failures:
print(f"[{name}] {error}")
sys.exit(1)

View File

@@ -1,7 +1,7 @@
[profile.cpu-big]
region = "eu-west-3"
image_id = "ami-04deffe45b5b236fd"
instance_type = "c6i.8xlarge"
instance_type = "m6i.32xlarge"
[profile.bench]
region = "eu-west-3"
@@ -18,6 +18,11 @@ workflow = "aws_tfhe_integer_tests.yml"
profile = "cpu-big"
check_run_name = "CPU Integer AWS Tests"
[command.integer_bench]
workflow = "integer_benchmark.yml"
profile = "bench"
check_run_name = "Integer CPU AWS Benchmarks"
[command.shortint_bench]
workflow = "shortint_benchmark.yml"
profile = "bench"

View File

@@ -5,8 +5,8 @@ RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# Replace default archive.ubuntu.com with fr mirror
# original archive showed performance issues and is farther away
RUN sed -i 's|^deb http://archive|deb http://fr.archive|g' /etc/apt/sources.list && \
sed -i 's|^deb http://security|deb http://fr.archive|g' /etc/apt/sources.list
RUN sed -i 's|^deb http://archive.ubuntu.com/ubuntu/|deb http://mirror.ubuntu.ikoula.com/|g' /etc/apt/sources.list && \
sed -i 's|^deb http://security.ubuntu.com/ubuntu/|deb http://mirror.ubuntu.ikoula.com/|g' /etc/apt/sources.list
ENV CARGO_TARGET_DIR=/root/tfhe-rs-target
@@ -18,7 +18,10 @@ RUN apt-get update && \
apt-get install -y \
build-essential \
curl \
git && \
git \
python3 \
python3-pip \
python3-venv && \
rm -rf /var/lib/apt/lists/*
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > install-rustup.sh && \
@@ -29,7 +32,7 @@ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > install-rustup.s
chmod +x install-wasm-pack.sh && \
. "$HOME/.cargo/env" && \
./install-wasm-pack.sh -y && \
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.2/install.sh > install-node.sh && \
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.3/install.sh > install-node.sh && \
chmod +x install-node.sh && \
./install-node.sh && \
. "$HOME/.nvm/nvm.sh" && \

View File

@@ -48,4 +48,12 @@ if [[ "${BUILD_ONLY}" == "1" ]]; then
exit 0
fi
make "test"
nproc_bin=nproc
# macOS detects CPUs differently
if [[ $(uname) == "Darwin" ]]; then
nproc_bin="sysctl -n hw.logicalcpu"
fi
# Let's go parallel
ARGS="-j$("${nproc_bin}")" make test

View File

@@ -24,35 +24,60 @@ else
n_threads=6
fi
# block pbs are too slow for high params
# mul_crt_4_4 is extremely flaky (~80% failure)
# test_wopbs_bivariate_crt_wopbs_param_message generate tables that are too big at the moment
# same for test_wopbs_bivariate_radix_wopbs_param_message_4_carry_4
# test_integer_smart_mul_param_message_4_carry_4 is too slow
filter_expression=''\
if [[ "${BIG_TESTS_INSTANCE}" != TRUE ]]; then
# block pbs are too slow for high params
# mul_crt_4_4 is extremely flaky (~80% failure)
# test_wopbs_bivariate_crt_wopbs_param_message generate tables that are too big at the moment
# test_integer_smart_mul_param_message_4_carry_4 is too slow
filter_expression=''\
'test(/^integer::.*$/)'\
'and not test(/.*_block_pbs(_base)?_param_message_[34]_carry_[34]$/)'\
'and not test(~mul_crt_param_message_4_carry_4)'\
'and not test(/.*test_wopbs_bivariate_crt_wopbs_param_message_[34]_carry_[34]$/)'\
'and not test(/.*test_wopbs_bivariate_radix_wopbs_param_message_4_carry_4$/)'\
'and not test(/.*test_integer_smart_mul_param_message_4_carry_4$/)'
export RUSTFLAGS="-C target-cpu=native"
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--test-threads "${n_threads}" \
-E "$filter_expression"
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--test-threads "${n_threads}" \
-E "$filter_expression"
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--doc \
integer::
else
# block pbs are too slow for high params
# mul_crt_4_4 is extremely flaky (~80% failure)
# test_wopbs_bivariate_crt_wopbs_param_message generate tables that are too big at the moment
# test_integer_smart_mul_param_message_4_carry_4 is too slow
filter_expression=''\
'test(/^integer::.*$/)'\
'and not test(/.*_block_pbs(_base)?_param_message_[34]_carry_[34]$/)'\
'and not test(~mul_crt_param_message_4_carry_4)'\
'and not test(/.*test_wopbs_bivariate_crt_wopbs_param_message_[34]_carry_[34]$/)'\
'and not test(/.*test_integer_smart_mul_param_message_4_carry_4$/)'
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--doc \
integer::
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--test-threads "$(${nproc_bin})" \
-E "$filter_expression"
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",integer,internal-keycache \
--doc \
integer:: -- --test-threads="$(${nproc_bin})"
fi
echo "Test ran in $SECONDS seconds"

View File

@@ -6,7 +6,7 @@ THIS_SCRIPT_NAME="$(basename "$0")"
TMP_FILE="$(mktemp)"
COUNT="$(git grep -rniI "thfe" . | grep -v "${THIS_SCRIPT_NAME}" | \
COUNT="$(git grep -rniI "thfe\|tfhr\|thfr" . | grep -v "${THIS_SCRIPT_NAME}" | \
tee "${TMP_FILE}" | wc -l | tr -d '[:space:]')"
cat "${TMP_FILE}"

View File

@@ -30,7 +30,8 @@ else
n_threads_big=13
fi
filter_expression_small_params=''\
if [[ "${BIG_TESTS_INSTANCE}" != TRUE ]]; then
filter_expression_small_params=''\
'('\
' test(/^shortint::.*_param_message_1_carry_1$/)'\
'or test(/^shortint::.*_param_message_1_carry_2$/)'\
@@ -47,37 +48,73 @@ filter_expression_small_params=''\
')'\
'and not test(~smart_add_and_mul)' # This test is too slow
# Run tests only no examples or benches with small params and more threads
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--test-threads "${n_threads_small}" \
-E "${filter_expression_small_params}"
# Run tests only no examples or benches with small params and more threads
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--test-threads "${n_threads_small}" \
-E "${filter_expression_small_params}"
filter_expression_big_params=''\
filter_expression_big_params=''\
'('\
' test(/^shortint::.*_param_message_4_carry_4$/)'\
')'\
'and not test(~smart_add_and_mul)'
# Run tests only no examples or benches with big params and less threads
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--test-threads "${n_threads_big}" \
-E "${filter_expression_big_params}"
# Run tests only no examples or benches with big params and less threads
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--test-threads "${n_threads_big}" \
-E "${filter_expression_big_params}"
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--doc \
shortint::
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--doc \
shortint::
else
filter_expression=''\
'('\
' test(/^shortint::.*_param_message_1_carry_1$/)'\
'or test(/^shortint::.*_param_message_1_carry_2$/)'\
'or test(/^shortint::.*_param_message_1_carry_3$/)'\
'or test(/^shortint::.*_param_message_1_carry_4$/)'\
'or test(/^shortint::.*_param_message_1_carry_5$/)'\
'or test(/^shortint::.*_param_message_1_carry_6$/)'\
'or test(/^shortint::.*_param_message_2_carry_1$/)'\
'or test(/^shortint::.*_param_message_2_carry_2$/)'\
'or test(/^shortint::.*_param_message_2_carry_3$/)'\
'or test(/^shortint::.*_param_message_3_carry_1$/)'\
'or test(/^shortint::.*_param_message_3_carry_2$/)'\
'or test(/^shortint::.*_param_message_3_carry_3$/)'\
'or test(/^shortint::.*_param_message_4_carry_4$/)'\
')'\
'and not test(~smart_add_and_mul)' # This test is too slow
# Run tests only no examples or benches with small params and more threads
cargo ${1:+"${1}"} nextest run \
--tests \
--release \
--package tfhe \
--profile ci \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--test-threads "$(${nproc_bin})" \
-E "${filter_expression}"
cargo ${1:+"${1}"} test \
--release \
--package tfhe \
--features="${ARCH_FEATURE}",shortint,internal-keycache \
--doc \
shortint:: -- --test-threads="$(${nproc_bin})"
fi
echo "Test ran in $SECONDS seconds"

View File

@@ -1,6 +1,6 @@
[package]
name = "tfhe"
version = "0.2.0"
version = "0.2.4"
edition = "2021"
readme = "../README.md"
keywords = ["fully", "homomorphic", "encryption", "fhe", "cryptography"]
@@ -23,9 +23,12 @@ paste = "1.0.7"
lazy_static = { version = "1.4.0" }
criterion = "0.4.0"
doc-comment = "0.3.3"
serde_json = "1.0.94"
# Used in user documentation
bincode = "1.3.3"
fs2 = { version = "0.4.3" }
itertools = "0.10.5"
num_cpus = "1.15"
[build-dependencies]
cbindgen = { version = "0.24.3", optional = true }
@@ -39,9 +42,10 @@ lazy_static = { version = "1.4.0", optional = true }
serde = { version = "1.0", features = ["derive"] }
rayon = { version = "1.5.0" }
bincode = { version = "1.3.3", optional = true }
concrete-fft = { version = "0.1", features = ["serde"] }
concrete-fft = { version = "0.2.1", features = ["serde", "fft128"] }
pulp = "0.11"
aligned-vec = { version = "0.5", features = ["serde"] }
dyn-stack = { version = "0.8" }
dyn-stack = { version = "0.9" }
once_cell = "1.13"
paste = "1.0.7"
fs2 = { version = "0.4.3", optional = true }
@@ -56,6 +60,7 @@ js-sys = { version = "0.3", optional = true }
console_error_panic_hook = { version = "0.1.7", optional = true }
serde-wasm-bindgen = { version = "0.4", optional = true }
getrandom = { version = "0.2.8", optional = true }
bytemuck = "1.13.1"
[features]
boolean = []
@@ -63,9 +68,15 @@ shortint = []
integer = ["shortint"]
internal-keycache = ["lazy_static", "fs2", "bincode"]
# Experimental section
experimental = []
experimental-force_fft_algo_dif4 = []
# End experimental section
__c_api = ["cbindgen", "bincode"]
boolean-c-api = ["boolean", "__c_api"]
shortint-c-api = ["shortint", "__c_api"]
high-level-c-api = ["boolean", "shortint", "integer", "__c_api"]
__wasm_api = [
"wasm-bindgen",
@@ -79,7 +90,7 @@ __wasm_api = [
boolean-client-js-wasm-api = ["boolean", "__wasm_api"]
shortint-client-js-wasm-api = ["shortint", "__wasm_api"]
nightly-avx512 = ["concrete-fft/nightly"]
nightly-avx512 = ["concrete-fft/nightly", "pulp/nightly"]
# Enable the x86_64 specific accelerated implementation of the random generator for the default
# backend
@@ -122,6 +133,17 @@ path = "benches/core_crypto/pbs_bench.rs"
harness = false
required-features = ["boolean", "shortint", "internal-keycache"]
[[bench]]
name = "dev-bench"
path = "benches/core_crypto/dev_bench.rs"
harness = false
required-features = ["experimental", "internal-keycache"]
[[bench]]
name = "pbs128-bench"
path = "benches/core_crypto/pbs128_bench.rs"
harness = false
[[bench]]
name = "boolean-bench"
path = "benches/boolean/bench.rs"
@@ -144,6 +166,13 @@ required-features = ["integer", "internal-keycache"]
name = "keygen"
path = "benches/keygen/bench.rs"
harness = false
required-features = ["shortint", "internal-keycache"]
[[bench]]
name = "utilities"
path = "benches/utilities.rs"
harness = false
required-features = ["boolean", "shortint", "integer", "internal-keycache"]
[[example]]
name = "generates_test_keys"

View File

@@ -1,3 +1,7 @@
#[path = "../utilities.rs"]
mod utilities;
use crate::utilities::{write_to_json, OperatorType};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use tfhe::boolean::client_key::ClientKey;
use tfhe::boolean::parameters::{BooleanParameters, DEFAULT_PARAMETERS, TFHE_LIB_PARAMETERS};
@@ -14,7 +18,9 @@ criterion_main!(gates_benches);
// Put all `bench_function` in one place
// so the keygen is only run once per parameters saving time.
fn bench_gates(c: &mut Criterion, params: BooleanParameters, parameter_name: &str) {
fn benchs(c: &mut Criterion, params: BooleanParameters, parameter_name: &str) {
let mut bench_group = c.benchmark_group("gates_benches");
let cks = ClientKey::new(&params);
let sks = ServerKey::new(&cks);
@@ -22,32 +28,41 @@ fn bench_gates(c: &mut Criterion, params: BooleanParameters, parameter_name: &st
let ct2 = cks.encrypt(false);
let ct3 = cks.encrypt(true);
let id = format!("AND gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.and(&ct1, &ct2))));
let operator = OperatorType::Atomic;
let id = format!("NAND gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.nand(&ct1, &ct2))));
let id = format!("AND::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.and(&ct1, &ct2))));
write_to_json(&id, params, parameter_name, "and", &operator);
let id = format!("OR gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.or(&ct1, &ct2))));
let id = format!("NAND::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.nand(&ct1, &ct2))));
write_to_json(&id, params, parameter_name, "nand", &operator);
let id = format!("XOR gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.xor(&ct1, &ct2))));
let id = format!("OR::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.or(&ct1, &ct2))));
write_to_json(&id, params, parameter_name, "or", &operator);
let id = format!("XNOR gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.xnor(&ct1, &ct2))));
let id = format!("XOR::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.xor(&ct1, &ct2))));
write_to_json(&id, params, parameter_name, "xor", &operator);
let id = format!("NOT gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.not(&ct1))));
let id = format!("XNOR::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.xnor(&ct1, &ct2))));
write_to_json(&id, params, parameter_name, "xnor", &operator);
let id = format!("MUX gate {parameter_name}");
c.bench_function(&id, |b| b.iter(|| black_box(sks.mux(&ct1, &ct2, &ct3))));
let id = format!("NOT::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.not(&ct1))));
write_to_json(&id, params, parameter_name, "not", &operator);
let id = format!("MUX::{parameter_name}");
bench_group.bench_function(&id, |b| b.iter(|| black_box(sks.mux(&ct1, &ct2, &ct3))));
write_to_json(&id, params, parameter_name, "mux", &operator);
}
fn bench_default_parameters(c: &mut Criterion) {
bench_gates(c, DEFAULT_PARAMETERS, "DEFAULT_PARAMETERS");
benchs(c, DEFAULT_PARAMETERS, "DEFAULT_PARAMETERS");
}
fn bench_tfhe_lib_parameters(c: &mut Criterion) {
bench_gates(c, TFHE_LIB_PARAMETERS, "TFHE_LIB_PARAMETERS");
benchs(c, TFHE_LIB_PARAMETERS, "TFHE_LIB_PARAMETERS");
}

View File

@@ -0,0 +1,332 @@
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use tfhe::core_crypto::prelude::*;
criterion_group!(
boolean_like_pbs_group,
multi_bit_pbs::<u32>,
pbs::<u32>,
mem_optimized_pbs::<u32>
);
criterion_group!(
shortint_like_pbs_group,
multi_bit_pbs::<u64>,
pbs::<u64>,
mem_optimized_pbs::<u64>
);
criterion_main!(boolean_like_pbs_group, shortint_like_pbs_group);
fn get_bench_params<Scalar: Numeric>() -> (
LweDimension,
StandardDev,
DecompositionBaseLog,
DecompositionLevelCount,
GlweDimension,
PolynomialSize,
LweBskGroupingFactor,
ThreadCount,
) {
if Scalar::BITS == 64 {
(
LweDimension(742),
StandardDev(0.000007069849454709433),
DecompositionBaseLog(3),
DecompositionLevelCount(5),
GlweDimension(1),
PolynomialSize(1024),
LweBskGroupingFactor(2),
ThreadCount(5),
)
} else if Scalar::BITS == 32 {
(
LweDimension(778),
StandardDev(0.000003725679281679651),
DecompositionBaseLog(18),
DecompositionLevelCount(1),
GlweDimension(3),
PolynomialSize(512),
LweBskGroupingFactor(2),
ThreadCount(5),
)
} else {
unreachable!()
}
}
fn multi_bit_pbs<Scalar: UnsignedTorus + CastInto<usize> + CastFrom<usize> + Sync>(
c: &mut Criterion,
) {
// DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
// computations
// Define parameters for LweBootstrapKey creation
let (
mut input_lwe_dimension,
lwe_modular_std_dev,
decomp_base_log,
decomp_level_count,
glwe_dimension,
polynomial_size,
grouping_factor,
thread_count,
) = get_bench_params::<Scalar>();
let ciphertext_modulus = CiphertextModulus::new_native();
while input_lwe_dimension.0 % grouping_factor.0 != 0 {
input_lwe_dimension = LweDimension(input_lwe_dimension.0 + 1);
}
// Create the PRNG
let mut seeder = new_seeder();
let seeder = seeder.as_mut();
let mut encryption_generator =
EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
let mut secret_generator =
SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
// Create the LweSecretKey
let input_lwe_secret_key =
allocate_and_generate_new_binary_lwe_secret_key(input_lwe_dimension, &mut secret_generator);
let output_glwe_secret_key: GlweSecretKeyOwned<Scalar> =
allocate_and_generate_new_binary_glwe_secret_key(
glwe_dimension,
polynomial_size,
&mut secret_generator,
);
let output_lwe_secret_key = output_glwe_secret_key.into_lwe_secret_key();
let multi_bit_bsk = FourierLweMultiBitBootstrapKey::new(
input_lwe_dimension,
glwe_dimension.to_glwe_size(),
polynomial_size,
decomp_base_log,
decomp_level_count,
grouping_factor,
);
// Allocate a new LweCiphertext and encrypt our plaintext
let lwe_ciphertext_in = allocate_and_encrypt_new_lwe_ciphertext(
&input_lwe_secret_key,
Plaintext(Scalar::ZERO),
lwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
let accumulator = GlweCiphertext::new(
Scalar::ZERO,
glwe_dimension.to_glwe_size(),
polynomial_size,
ciphertext_modulus,
);
// Allocate the LweCiphertext to store the result of the PBS
let mut out_pbs_ct = LweCiphertext::new(
Scalar::ZERO,
output_lwe_secret_key.lwe_dimension().to_lwe_size(),
ciphertext_modulus,
);
let id = format!("Multi Bit PBS {}", Scalar::BITS);
#[allow(clippy::unit_arg)]
{
c.bench_function(&id, |b| {
b.iter(|| {
multi_bit_programmable_bootstrap_lwe_ciphertext(
&lwe_ciphertext_in,
&mut out_pbs_ct,
&accumulator.as_view(),
&multi_bit_bsk,
thread_count,
);
black_box(&mut out_pbs_ct);
})
});
}
}
fn pbs<Scalar: UnsignedTorus + CastInto<usize>>(c: &mut Criterion) {
// DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
// computations
// Define parameters for LweBootstrapKey creation
let (
input_lwe_dimension,
lwe_modular_std_dev,
decomp_base_log,
decomp_level_count,
glwe_dimension,
polynomial_size,
_,
_,
) = get_bench_params::<Scalar>();
let ciphertext_modulus = CiphertextModulus::new_native();
// Create the PRNG
let mut seeder = new_seeder();
let seeder = seeder.as_mut();
let mut encryption_generator =
EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
let mut secret_generator =
SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
// Create the LweSecretKey
let input_lwe_secret_key =
allocate_and_generate_new_binary_lwe_secret_key(input_lwe_dimension, &mut secret_generator);
let output_glwe_secret_key: GlweSecretKeyOwned<Scalar> =
allocate_and_generate_new_binary_glwe_secret_key(
glwe_dimension,
polynomial_size,
&mut secret_generator,
);
let output_lwe_secret_key = output_glwe_secret_key.into_lwe_secret_key();
// Create the empty bootstrapping key in the Fourier domain
let fourier_bsk = FourierLweBootstrapKey::new(
input_lwe_dimension,
glwe_dimension.to_glwe_size(),
polynomial_size,
decomp_base_log,
decomp_level_count,
);
// Allocate a new LweCiphertext and encrypt our plaintext
let lwe_ciphertext_in = allocate_and_encrypt_new_lwe_ciphertext(
&input_lwe_secret_key,
Plaintext(Scalar::ZERO),
lwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
let accumulator = GlweCiphertext::new(
Scalar::ZERO,
glwe_dimension.to_glwe_size(),
polynomial_size,
ciphertext_modulus,
);
// Allocate the LweCiphertext to store the result of the PBS
let mut out_pbs_ct = LweCiphertext::new(
Scalar::ZERO,
output_lwe_secret_key.lwe_dimension().to_lwe_size(),
ciphertext_modulus,
);
let id = format!("PBS {}", Scalar::BITS);
{
c.bench_function(&id, |b| {
b.iter(|| {
programmable_bootstrap_lwe_ciphertext(
&lwe_ciphertext_in,
&mut out_pbs_ct,
&accumulator.as_view(),
&fourier_bsk,
);
black_box(&mut out_pbs_ct);
})
});
}
}
fn mem_optimized_pbs<Scalar: UnsignedTorus + CastInto<usize>>(c: &mut Criterion) {
// DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
// computations
// Define parameters for LweBootstrapKey creation
let (
input_lwe_dimension,
lwe_modular_std_dev,
decomp_base_log,
decomp_level_count,
glwe_dimension,
polynomial_size,
_,
_,
) = get_bench_params::<Scalar>();
// Create the PRNG
let mut seeder = new_seeder();
let seeder = seeder.as_mut();
let mut encryption_generator =
EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
let mut secret_generator =
SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
// Create the LweSecretKey
let input_lwe_secret_key =
allocate_and_generate_new_binary_lwe_secret_key(input_lwe_dimension, &mut secret_generator);
let output_glwe_secret_key: GlweSecretKeyOwned<Scalar> =
allocate_and_generate_new_binary_glwe_secret_key(
glwe_dimension,
polynomial_size,
&mut secret_generator,
);
let output_lwe_secret_key = output_glwe_secret_key.into_lwe_secret_key();
// Create the empty bootstrapping key in the Fourier domain
let fourier_bsk = FourierLweBootstrapKey::new(
input_lwe_dimension,
glwe_dimension.to_glwe_size(),
polynomial_size,
decomp_base_log,
decomp_level_count,
);
// Allocate a new LweCiphertext and encrypt our plaintext
let lwe_ciphertext_in = allocate_and_encrypt_new_lwe_ciphertext(
&input_lwe_secret_key,
Plaintext(Scalar::ZERO),
lwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
let accumulator = GlweCiphertext::new(
Scalar::ZERO,
glwe_dimension.to_glwe_size(),
polynomial_size,
ciphertext_modulus,
);
// Allocate the LweCiphertext to store the result of the PBS
let mut out_pbs_ct = LweCiphertext::new(
Scalar::ZERO,
output_lwe_secret_key.lwe_dimension().to_lwe_size(),
ciphertext_modulus,
);
let mut buffers = ComputationBuffers::new();
let fft = Fft::new(fourier_bsk.polynomial_size());
let fft = fft.as_view();
buffers.resize(
programmable_bootstrap_lwe_ciphertext_mem_optimized_requirement::<Scalar>(
fourier_bsk.glwe_size(),
fourier_bsk.polynomial_size(),
fft,
)
.unwrap()
.unaligned_bytes_required(),
);
let id = format!("PBS mem-optimized {}", Scalar::BITS);
{
c.bench_function(&id, |b| {
b.iter(|| {
programmable_bootstrap_lwe_ciphertext_mem_optimized(
&lwe_ciphertext_in,
&mut out_pbs_ct,
&accumulator.as_view(),
&fourier_bsk,
fft,
buffers.stack(),
);
black_box(&mut out_pbs_ct);
})
});
}
}

View File

@@ -0,0 +1,108 @@
use criterion::{criterion_group, criterion_main, Criterion};
use dyn_stack::PodStack;
fn sqr(x: f64) -> f64 {
x * x
}
fn criterion_bench(c: &mut Criterion) {
{
use tfhe::core_crypto::fft_impl::fft128::crypto::bootstrap::bootstrap_scratch;
use tfhe::core_crypto::prelude::*;
type Scalar = u128;
let small_lwe_dimension = LweDimension(742);
let glwe_dimension = GlweDimension(1);
let polynomial_size = PolynomialSize(2048);
let lwe_modular_std_dev = StandardDev(sqr(0.000007069849454709433));
let pbs_base_log = DecompositionBaseLog(23);
let pbs_level = DecompositionLevelCount(1);
let ciphertext_modulus = CiphertextModulus::new_native();
let mut boxed_seeder = new_seeder();
let seeder = boxed_seeder.as_mut();
let mut secret_generator =
SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
let mut encryption_generator =
EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
let small_lwe_sk =
LweSecretKey::generate_new_binary(small_lwe_dimension, &mut secret_generator);
let glwe_sk = GlweSecretKey::<Vec<Scalar>>::generate_new_binary(
glwe_dimension,
polynomial_size,
&mut secret_generator,
);
let big_lwe_sk = glwe_sk.into_lwe_secret_key();
let fourier_bsk = Fourier128LweBootstrapKey::new(
small_lwe_dimension,
glwe_dimension.to_glwe_size(),
polynomial_size,
pbs_base_log,
pbs_level,
);
let fft = Fft128::new(polynomial_size);
let fft = fft.as_view();
let message_modulus: Scalar = 1 << 4;
let input_message: Scalar = 3;
let delta: Scalar = (1 << (Scalar::BITS - 1)) / message_modulus;
let plaintext = Plaintext(input_message * delta);
let lwe_ciphertext_in: LweCiphertextOwned<Scalar> = allocate_and_encrypt_new_lwe_ciphertext(
&small_lwe_sk,
plaintext,
lwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
let accumulator: GlweCiphertextOwned<Scalar> = GlweCiphertextOwned::new(
Scalar::ONE,
glwe_dimension.to_glwe_size(),
polynomial_size,
ciphertext_modulus,
);
let mut pbs_out: LweCiphertext<Vec<Scalar>> = LweCiphertext::new(
0,
big_lwe_sk.lwe_dimension().to_lwe_size(),
ciphertext_modulus,
);
let mut buf = vec![
0u8;
bootstrap_scratch::<Scalar>(
fourier_bsk.glwe_size(),
fourier_bsk.polynomial_size(),
fft
)
.unwrap()
.unaligned_bytes_required()
];
c.bench_function("pbs128", |b| {
b.iter(|| {
fourier_bsk.bootstrap(
&mut pbs_out,
&lwe_ciphertext_in,
&accumulator,
fft,
PodStack::new(&mut buf),
)
});
});
}
}
criterion_group!(benches, criterion_bench);
criterion_main!(benches);

View File

@@ -1,3 +1,7 @@
#[path = "../utilities.rs"]
mod utilities;
use crate::utilities::{write_to_json, CryptoParametersRecord, OperatorType};
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use tfhe::boolean::parameters::{BooleanParameters, DEFAULT_PARAMETERS, TFHE_LIB_PARAMETERS};
use tfhe::core_crypto::prelude::*;
@@ -24,8 +28,8 @@ const SHORTINT_BENCH_PARAMS: [Parameters; 15] = [
];
const BOOLEAN_BENCH_PARAMS: [(&str, BooleanParameters); 2] = [
("boolean_default_params", DEFAULT_PARAMETERS),
("boolean_tfhe_lib_params", TFHE_LIB_PARAMETERS),
("BOOLEAN_DEFAULT_PARAMS", DEFAULT_PARAMETERS),
("BOOLEAN_TFHE_LIB_PARAMS", TFHE_LIB_PARAMETERS),
];
criterion_group!(
@@ -34,53 +38,19 @@ criterion_group!(
targets = mem_optimized_pbs::<u64>, mem_optimized_pbs::<u32>
);
criterion_main!(pbs_group);
criterion_group!(
name = multi_bit_pbs_group;
config = Criterion::default().sample_size(2000);
targets = multi_bit_pbs::<u64>, multi_bit_pbs::<u32>
);
struct BenchmarkPbsParameters {
input_lwe_dimension: LweDimension,
lwe_modular_std_dev: StandardDev,
decomp_base_log: DecompositionBaseLog,
decomp_level_count: DecompositionLevelCount,
glwe_dimension: GlweDimension,
polynomial_size: PolynomialSize,
}
criterion_main!(pbs_group, multi_bit_pbs_group);
impl From<BooleanParameters> for BenchmarkPbsParameters {
fn from(params: BooleanParameters) -> Self {
BenchmarkPbsParameters {
input_lwe_dimension: params.lwe_dimension,
lwe_modular_std_dev: params.lwe_modular_std_dev,
decomp_base_log: params.pbs_base_log,
decomp_level_count: params.pbs_level,
glwe_dimension: params.glwe_dimension,
polynomial_size: params.polynomial_size,
}
}
}
impl From<Parameters> for BenchmarkPbsParameters {
fn from(params: Parameters) -> Self {
BenchmarkPbsParameters {
input_lwe_dimension: params.lwe_dimension,
lwe_modular_std_dev: params.lwe_modular_std_dev,
decomp_base_log: params.pbs_base_log,
decomp_level_count: params.pbs_level,
glwe_dimension: params.glwe_dimension,
polynomial_size: params.polynomial_size,
}
}
}
fn benchmark_parameters<Scalar: Numeric>() -> Vec<(String, BenchmarkPbsParameters)> {
fn benchmark_parameters<Scalar: Numeric>() -> Vec<(String, CryptoParametersRecord)> {
if Scalar::BITS == 64 {
SHORTINT_BENCH_PARAMS
.iter()
.map(|params| {
(
format!("shortint_{}", params.name().to_lowercase()),
params.to_owned().into(),
)
})
.map(|params| (params.name(), params.to_owned().into()))
.collect()
} else if Scalar::BITS == 32 {
BOOLEAN_BENCH_PARAMS
@@ -92,7 +62,53 @@ fn benchmark_parameters<Scalar: Numeric>() -> Vec<(String, BenchmarkPbsParameter
}
}
fn multi_bit_benchmark_parameters<Scalar: Numeric>(
) -> Vec<(String, (CryptoParametersRecord, LweBskGroupingFactor))> {
if Scalar::BITS == 64 {
vec![
(
"4_bits_multi_bit_group_2".to_string(),
(
CryptoParametersRecord {
lwe_dimension: Some(LweDimension(788)),
lwe_modular_std_dev: Some(StandardDev(0.000003871078133364534)),
pbs_base_log: Some(DecompositionBaseLog(22)),
pbs_level: Some(DecompositionLevelCount(1)),
glwe_dimension: Some(GlweDimension(2)),
glwe_modular_std_dev: Some(StandardDev(0.0000000000000003152931493498455)),
polynomial_size: Some(PolynomialSize(1024)),
..Default::default()
},
LweBskGroupingFactor(2),
),
),
(
"4_bits_multi_bit_group_3".to_string(),
(
CryptoParametersRecord {
lwe_dimension: Some(LweDimension(789)),
lwe_modular_std_dev: Some(StandardDev(0.0000038003596741624174)),
pbs_base_log: Some(DecompositionBaseLog(22)),
pbs_level: Some(DecompositionLevelCount(1)),
glwe_dimension: Some(GlweDimension(2)),
glwe_modular_std_dev: Some(StandardDev(0.0000000000000003152931493498455)),
polynomial_size: Some(PolynomialSize(1024)),
..Default::default()
},
LweBskGroupingFactor(3),
),
),
]
} else {
// For now there are no parameters available to test multi bit PBS on 32 bits.
vec![]
}
}
fn mem_optimized_pbs<Scalar: UnsignedTorus + CastInto<usize>>(c: &mut Criterion) {
let bench_name = "PBS_mem-optimized";
let mut bench_group = c.benchmark_group(bench_name);
// Create the PRNG
let mut seeder = new_seeder();
let seeder = seeder.as_mut();
@@ -104,44 +120,47 @@ fn mem_optimized_pbs<Scalar: UnsignedTorus + CastInto<usize>>(c: &mut Criterion)
for (name, params) in benchmark_parameters::<Scalar>().iter() {
// Create the LweSecretKey
let input_lwe_secret_key = allocate_and_generate_new_binary_lwe_secret_key(
params.input_lwe_dimension,
params.lwe_dimension.unwrap(),
&mut secret_generator,
);
let output_glwe_secret_key: GlweSecretKeyOwned<Scalar> =
allocate_and_generate_new_binary_glwe_secret_key(
params.glwe_dimension,
params.polynomial_size,
params.glwe_dimension.unwrap(),
params.polynomial_size.unwrap(),
&mut secret_generator,
);
let output_lwe_secret_key = output_glwe_secret_key.into_lwe_secret_key();
// Create the empty bootstrapping key in the Fourier domain
let fourier_bsk = FourierLweBootstrapKey::new(
params.input_lwe_dimension,
params.glwe_dimension.to_glwe_size(),
params.polynomial_size,
params.decomp_base_log,
params.decomp_level_count,
params.lwe_dimension.unwrap(),
params.glwe_dimension.unwrap().to_glwe_size(),
params.polynomial_size.unwrap(),
params.pbs_base_log.unwrap(),
params.pbs_level.unwrap(),
);
// Allocate a new LweCiphertext and encrypt our plaintext
let lwe_ciphertext_in: LweCiphertextOwned<Scalar> = allocate_and_encrypt_new_lwe_ciphertext(
&input_lwe_secret_key,
Plaintext(Scalar::ZERO),
params.lwe_modular_std_dev,
params.lwe_modular_std_dev.unwrap(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
&mut encryption_generator,
);
let accumulator = GlweCiphertext::new(
Scalar::ZERO,
params.glwe_dimension.to_glwe_size(),
params.polynomial_size,
params.glwe_dimension.unwrap().to_glwe_size(),
params.polynomial_size.unwrap(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
);
// Allocate the LweCiphertext to store the result of the PBS
let mut out_pbs_ct = LweCiphertext::new(
Scalar::ZERO,
output_lwe_secret_key.lwe_dimension().to_lwe_size(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
);
let mut buffers = ComputationBuffers::new();
@@ -159,21 +178,106 @@ fn mem_optimized_pbs<Scalar: UnsignedTorus + CastInto<usize>>(c: &mut Criterion)
.unaligned_bytes_required(),
);
let id = format!("PBS_mem-optimized_{name}");
#[allow(clippy::unit_arg)]
let id = format!("{bench_name}_{name}");
{
c.bench_function(&id, |b| {
bench_group.bench_function(&id, |b| {
b.iter(|| {
black_box(programmable_bootstrap_lwe_ciphertext_mem_optimized(
programmable_bootstrap_lwe_ciphertext_mem_optimized(
&lwe_ciphertext_in,
&mut out_pbs_ct,
&accumulator.as_view(),
&fourier_bsk,
fft,
buffers.stack(),
))
);
black_box(&mut out_pbs_ct);
})
});
}
write_to_json(&id, *params, name, "pbs", &OperatorType::Atomic);
}
}
fn multi_bit_pbs<Scalar: UnsignedTorus + CastInto<usize> + CastFrom<usize> + Sync>(
c: &mut Criterion,
) {
// DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
// computations
// Define parameters for LweBootstrapKey creation
let bench_name = "multi_bits_PBS";
let mut bench_group = c.benchmark_group(bench_name);
// Create the PRNG
let mut seeder = new_seeder();
let seeder = seeder.as_mut();
let mut encryption_generator =
EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
let mut secret_generator =
SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
for (name, (params, grouping_factor)) in multi_bit_benchmark_parameters::<Scalar>().iter() {
// Create the LweSecretKey
let input_lwe_secret_key = allocate_and_generate_new_binary_lwe_secret_key(
params.lwe_dimension.unwrap(),
&mut secret_generator,
);
let output_glwe_secret_key: GlweSecretKeyOwned<Scalar> =
allocate_and_generate_new_binary_glwe_secret_key(
params.glwe_dimension.unwrap(),
params.polynomial_size.unwrap(),
&mut secret_generator,
);
let output_lwe_secret_key = output_glwe_secret_key.into_lwe_secret_key();
let multi_bit_bsk = FourierLweMultiBitBootstrapKey::new(
params.lwe_dimension.unwrap(),
params.glwe_dimension.unwrap().to_glwe_size(),
params.polynomial_size.unwrap(),
params.pbs_base_log.unwrap(),
params.pbs_level.unwrap(),
*grouping_factor,
);
// Allocate a new LweCiphertext and encrypt our plaintext
let lwe_ciphertext_in = allocate_and_encrypt_new_lwe_ciphertext(
&input_lwe_secret_key,
Plaintext(Scalar::ZERO),
params.lwe_modular_std_dev.unwrap(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
&mut encryption_generator,
);
let accumulator = GlweCiphertext::new(
Scalar::ZERO,
params.glwe_dimension.unwrap().to_glwe_size(),
params.polynomial_size.unwrap(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
);
// Allocate the LweCiphertext to store the result of the PBS
let mut out_pbs_ct = LweCiphertext::new(
Scalar::ZERO,
output_lwe_secret_key.lwe_dimension().to_lwe_size(),
tfhe::core_crypto::prelude::CiphertextModulus::new_native(),
);
let id = format!("{bench_name}_{name}_parallelized");
bench_group.bench_function(&id, |b| {
b.iter(|| {
multi_bit_programmable_bootstrap_lwe_ciphertext(
&lwe_ciphertext_in,
&mut out_pbs_ct,
&accumulator.as_view(),
&multi_bit_bsk,
// Leave one thread to the OS and one for the ext product loop
ThreadCount(2.max(num_cpus::get_physical() - 2)),
);
black_box(&mut out_pbs_ct);
})
});
write_to_json(&id, *params, name, "pbs", &OperatorType::Atomic);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@ use criterion::*;
use tfhe::core_crypto::commons::generators::DeterministicSeeder;
use tfhe::core_crypto::prelude::{
allocate_and_generate_new_binary_glwe_secret_key,
par_allocate_and_generate_new_lwe_bootstrap_key, ActivatedRandomGenerator,
par_allocate_and_generate_new_lwe_bootstrap_key, ActivatedRandomGenerator, CiphertextModulus,
EncryptionRandomGenerator, SecretRandomGenerator,
};
use tfhe::core_crypto::seeders::new_seeder;
@@ -34,6 +34,7 @@ fn criterion_bench(c: &mut Criterion) {
parameters.pbs_base_log,
parameters.pbs_level,
parameters.glwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut encryption_generator,
);
});

View File

@@ -1,7 +1,11 @@
#[path = "../utilities.rs"]
mod utilities;
use crate::utilities::{write_to_json, OperatorType};
use criterion::{criterion_group, criterion_main, Criterion};
use tfhe::shortint::keycache::NamedParam;
use tfhe::shortint::parameters::*;
use tfhe::shortint::{Ciphertext, Parameters, ServerKey};
use tfhe::shortint::{CiphertextBig, Parameters, ServerKey};
use rand::Rng;
use tfhe::shortint::keycache::KEY_CACHE;
@@ -37,10 +41,11 @@ const SERVER_KEY_BENCH_PARAMS_EXTENDED: [Parameters; 15] = [
fn bench_server_key_unary_function<F>(
c: &mut Criterion,
bench_name: &str,
display_name: &str,
unary_op: F,
params: &[Parameters],
) where
F: Fn(&ServerKey, &mut Ciphertext),
F: Fn(&ServerKey, &mut CiphertextBig),
{
let mut bench_group = c.benchmark_group(bench_name);
@@ -62,6 +67,14 @@ fn bench_server_key_unary_function<F>(
unary_op(sks, &mut ct);
})
});
write_to_json(
&bench_id,
*param,
param.name(),
display_name,
&OperatorType::Atomic,
);
}
bench_group.finish()
@@ -70,10 +83,11 @@ fn bench_server_key_unary_function<F>(
fn bench_server_key_binary_function<F>(
c: &mut Criterion,
bench_name: &str,
display_name: &str,
binary_op: F,
params: &[Parameters],
) where
F: Fn(&ServerKey, &mut Ciphertext, &mut Ciphertext),
F: Fn(&ServerKey, &mut CiphertextBig, &mut CiphertextBig),
{
let mut bench_group = c.benchmark_group(bench_name);
@@ -97,6 +111,14 @@ fn bench_server_key_binary_function<F>(
binary_op(sks, &mut ct_0, &mut ct_1);
})
});
write_to_json(
&bench_id,
*param,
param.name(),
display_name,
&OperatorType::Atomic,
);
}
bench_group.finish()
@@ -105,10 +127,11 @@ fn bench_server_key_binary_function<F>(
fn bench_server_key_binary_scalar_function<F>(
c: &mut Criterion,
bench_name: &str,
display_name: &str,
binary_op: F,
params: &[Parameters],
) where
F: Fn(&ServerKey, &mut Ciphertext, u8),
F: Fn(&ServerKey, &mut CiphertextBig, u8),
{
let mut bench_group = c.benchmark_group(bench_name);
@@ -131,6 +154,14 @@ fn bench_server_key_binary_scalar_function<F>(
binary_op(sks, &mut ct_0, clear_1 as u8);
})
});
write_to_json(
&bench_id,
*param,
param.name(),
display_name,
&OperatorType::Atomic,
);
}
bench_group.finish()
@@ -139,10 +170,11 @@ fn bench_server_key_binary_scalar_function<F>(
fn bench_server_key_binary_scalar_division_function<F>(
c: &mut Criterion,
bench_name: &str,
display_name: &str,
binary_op: F,
params: &[Parameters],
) where
F: Fn(&ServerKey, &mut Ciphertext, u8),
F: Fn(&ServerKey, &mut CiphertextBig, u8),
{
let mut bench_group = c.benchmark_group(bench_name);
@@ -169,6 +201,14 @@ fn bench_server_key_binary_scalar_division_function<F>(
binary_op(sks, &mut ct_0, clear_1 as u8);
})
});
write_to_json(
&bench_id,
*param,
param.name(),
display_name,
&OperatorType::Atomic,
);
}
bench_group.finish()
@@ -192,9 +232,17 @@ fn carry_extract(c: &mut Criterion) {
let bench_id = format!("ServerKey::carry_extract::{}", param.name());
bench_group.bench_function(&bench_id, |b| {
b.iter(|| {
sks.carry_extract(&ct_0);
let _ = sks.carry_extract(&ct_0);
})
});
write_to_json(
&bench_id,
param,
param.name(),
"carry_extract",
&OperatorType::Atomic,
);
}
bench_group.finish()
@@ -217,19 +265,21 @@ fn programmable_bootstrapping(c: &mut Criterion) {
let ctxt = cks.encrypt(clear_0);
let id = format!("ServerKey::programmable_bootstrap::{}", param.name());
let bench_id = format!("ServerKey::programmable_bootstrap::{}", param.name());
bench_group.bench_function(&id, |b| {
bench_group.bench_function(&bench_id, |b| {
b.iter(|| {
sks.keyswitch_programmable_bootstrap(&ctxt, &acc);
let _ = sks.apply_lookup_table(&ctxt, &acc);
})
});
write_to_json(&bench_id, param, param.name(), "pbs", &OperatorType::Atomic);
}
bench_group.finish();
}
fn bench_wopbs_param_message_8_norm2_5(c: &mut Criterion) {
fn _bench_wopbs_param_message_8_norm2_5(c: &mut Criterion) {
let mut bench_group = c.benchmark_group("programmable_bootstrap");
let param = WOPBS_PARAM_MESSAGE_4_NORM2_6;
@@ -247,7 +297,7 @@ fn bench_wopbs_param_message_8_norm2_5(c: &mut Criterion) {
bench_group.bench_function(&id, |b| {
b.iter(|| {
wopbs_key.programmable_bootstrapping_native_crt(&mut ct, &vec_lut);
let _ = wopbs_key.programmable_bootstrapping_native_crt(&mut ct, &vec_lut);
})
});
@@ -255,82 +305,310 @@ fn bench_wopbs_param_message_8_norm2_5(c: &mut Criterion) {
}
macro_rules! define_server_key_unary_bench_fn (
($server_key_method:ident, $params:expr) => {
(method_name:$server_key_method:ident, display_name:$name:ident, $params:expr) => {
fn $server_key_method(c: &mut Criterion) {
bench_server_key_unary_function(
c,
concat!("ServerKey::", stringify!($server_key_method)),
stringify!($name),
|server_key, lhs| {
server_key.$server_key_method(lhs);},
let _ = server_key.$server_key_method(lhs);},
$params)
}
}
);
macro_rules! define_server_key_bench_fn (
($server_key_method:ident, $params:expr) => {
(method_name:$server_key_method:ident, display_name:$name:ident, $params:expr) => {
fn $server_key_method(c: &mut Criterion) {
bench_server_key_binary_function(
c,
concat!("ServerKey::", stringify!($server_key_method)),
stringify!($name),
|server_key, lhs, rhs| {
server_key.$server_key_method(lhs, rhs);},
let _ = server_key.$server_key_method(lhs, rhs);},
$params)
}
}
);
macro_rules! define_server_key_scalar_bench_fn (
($server_key_method:ident, $params:expr) => {
(method_name:$server_key_method:ident, display_name:$name:ident, $params:expr) => {
fn $server_key_method(c: &mut Criterion) {
bench_server_key_binary_scalar_function(
c,
concat!("ServerKey::", stringify!($server_key_method)),
stringify!($name),
|server_key, lhs, rhs| {
server_key.$server_key_method(lhs, rhs);},
let _ = server_key.$server_key_method(lhs, rhs);},
$params)
}
}
);
macro_rules! define_server_key_scalar_div_bench_fn (
($server_key_method:ident, $params:expr) => {
(method_name:$server_key_method:ident, display_name:$name:ident, $params:expr) => {
fn $server_key_method(c: &mut Criterion) {
bench_server_key_binary_scalar_division_function(
c,
concat!("ServerKey::", stringify!($server_key_method)),
stringify!($name),
|server_key, lhs, rhs| {
server_key.$server_key_method(lhs, rhs);},
let _ = server_key.$server_key_method(lhs, rhs);},
$params)
}
}
);
define_server_key_unary_bench_fn!(unchecked_neg, &SERVER_KEY_BENCH_PARAMS);
define_server_key_unary_bench_fn!(
method_name: unchecked_neg,
display_name: negation,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(unchecked_add, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_bench_fn!(unchecked_sub, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_bench_fn!(unchecked_mul_lsb, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_bench_fn!(unchecked_mul_msb, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(unchecked_div, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_bench_fn!(smart_bitand, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(smart_bitor, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(smart_bitxor, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(smart_add, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(smart_sub, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(smart_mul_lsb, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(unchecked_greater, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(unchecked_less, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(unchecked_equal, &SERVER_KEY_BENCH_PARAMS);
define_server_key_bench_fn!(
method_name: unchecked_add,
display_name: add,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_bench_fn!(
method_name: unchecked_sub,
display_name: sub,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_bench_fn!(
method_name: unchecked_mul_lsb,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_bench_fn!(
method_name: unchecked_mul_msb,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: unchecked_div,
display_name: div,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_bench_fn!(
method_name: smart_bitand,
display_name: bitand,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: smart_bitor,
display_name: bitor,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: smart_bitxor,
display_name: bitxor,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: smart_add,
display_name: add,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: smart_sub,
display_name: sub,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: smart_mul_lsb,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: bitand,
display_name: bitand,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: bitor,
display_name: bitor,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: bitxor,
display_name: bitxor,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: add,
display_name: add,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: sub,
display_name: sub,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: mul,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: div,
display_name: div,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: greater,
display_name: greater,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: greater_or_equal,
display_name: greater_or_equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: less,
display_name: less,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: less_or_equal,
display_name: less_or_equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: equal,
display_name: equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: not_equal,
display_name: not_equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_unary_bench_fn!(
method_name: neg,
display_name: negation,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: unchecked_greater,
display_name: greater_than,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: unchecked_less,
display_name: less_than,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_bench_fn!(
method_name: unchecked_equal,
display_name: equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(unchecked_scalar_add, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_scalar_bench_fn!(unchecked_scalar_sub, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_scalar_bench_fn!(unchecked_scalar_mul, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_scalar_bench_fn!(unchecked_scalar_left_shift, &SERVER_KEY_BENCH_PARAMS);
define_server_key_scalar_bench_fn!(unchecked_scalar_right_shift, &SERVER_KEY_BENCH_PARAMS);
define_server_key_scalar_bench_fn!(
method_name: unchecked_scalar_add,
display_name: add,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_scalar_bench_fn!(
method_name: unchecked_scalar_sub,
display_name: sub,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_scalar_bench_fn!(
method_name: unchecked_scalar_mul,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_scalar_bench_fn!(
method_name: unchecked_scalar_left_shift,
display_name: left_shift,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: unchecked_scalar_right_shift,
display_name: right_shift,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_div_bench_fn!(unchecked_scalar_div, &SERVER_KEY_BENCH_PARAMS_EXTENDED);
define_server_key_scalar_div_bench_fn!(unchecked_scalar_mod, &SERVER_KEY_BENCH_PARAMS);
define_server_key_scalar_div_bench_fn!(
method_name: unchecked_scalar_div,
display_name: div,
&SERVER_KEY_BENCH_PARAMS_EXTENDED
);
define_server_key_scalar_div_bench_fn!(
method_name: unchecked_scalar_mod,
display_name: modulo,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_add,
display_name: add,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_sub,
display_name: sub,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_mul,
display_name: mul,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_left_shift,
display_name: left_shift,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_right_shift,
display_name: right_shift,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_div_bench_fn!(
method_name: scalar_div,
display_name: div,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_div_bench_fn!(
method_name: scalar_mod,
display_name: modulo,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_greater,
display_name: greater,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_greater_or_equal,
display_name: greater_or_equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_less,
display_name: less,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_bench_fn!(
method_name: scalar_less_or_equal,
display_name: less_or_equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_div_bench_fn!(
method_name: scalar_equal,
display_name: equal,
&SERVER_KEY_BENCH_PARAMS
);
define_server_key_scalar_div_bench_fn!(
method_name: scalar_not_equal,
display_name: not_equal,
&SERVER_KEY_BENCH_PARAMS
);
criterion_group!(
arithmetic_operation,
@@ -354,7 +632,7 @@ criterion_group!(
// multivalue_programmable_bootstrapping
//bench_two_block_pbs
//wopbs_v0_norm2_2,
bench_wopbs_param_message_8_norm2_5,
//bench_wopbs_param_message_8_norm2_5,
programmable_bootstrapping
);
@@ -369,4 +647,44 @@ criterion_group!(
unchecked_scalar_right_shift,
);
criterion_main!(arithmetic_operation, arithmetic_scalar_operation);
criterion_group!(
default_ops,
neg,
bitand,
bitor,
bitxor,
add,
sub,
div,
mul,
greater,
greater_or_equal,
less,
less_or_equal,
equal,
not_equal
);
criterion_group!(
default_scalar_ops,
scalar_add,
scalar_sub,
scalar_div,
scalar_mul,
scalar_mod,
scalar_left_shift,
scalar_right_shift,
scalar_greater,
scalar_greater_or_equal,
scalar_less,
scalar_less_or_equal,
scalar_equal,
scalar_not_equal
);
criterion_main!(
// arithmetic_operation,
// arithmetic_scalar_operation,
default_ops,
default_scalar_ops,
);

184
tfhe/benches/utilities.rs Normal file
View File

@@ -0,0 +1,184 @@
use serde::Serialize;
use std::fs;
use std::path::PathBuf;
#[cfg(feature = "boolean")]
use tfhe::boolean::parameters::BooleanParameters;
use tfhe::core_crypto::prelude::*;
#[cfg(feature = "shortint")]
use tfhe::shortint::Parameters;
#[derive(Clone, Copy, Default, Serialize)]
pub struct CryptoParametersRecord {
pub lwe_dimension: Option<LweDimension>,
pub glwe_dimension: Option<GlweDimension>,
pub polynomial_size: Option<PolynomialSize>,
pub lwe_modular_std_dev: Option<StandardDev>,
pub glwe_modular_std_dev: Option<StandardDev>,
pub pbs_base_log: Option<DecompositionBaseLog>,
pub pbs_level: Option<DecompositionLevelCount>,
pub ks_base_log: Option<DecompositionBaseLog>,
pub ks_level: Option<DecompositionLevelCount>,
pub pfks_level: Option<DecompositionLevelCount>,
pub pfks_base_log: Option<DecompositionBaseLog>,
pub pfks_modular_std_dev: Option<StandardDev>,
pub cbs_level: Option<DecompositionLevelCount>,
pub cbs_base_log: Option<DecompositionBaseLog>,
pub message_modulus: Option<usize>,
pub carry_modulus: Option<usize>,
}
#[cfg(feature = "boolean")]
impl From<BooleanParameters> for CryptoParametersRecord {
fn from(params: BooleanParameters) -> Self {
CryptoParametersRecord {
lwe_dimension: Some(params.lwe_dimension),
glwe_dimension: Some(params.glwe_dimension),
polynomial_size: Some(params.polynomial_size),
lwe_modular_std_dev: Some(params.lwe_modular_std_dev),
glwe_modular_std_dev: Some(params.glwe_modular_std_dev),
pbs_base_log: Some(params.pbs_base_log),
pbs_level: Some(params.pbs_level),
ks_base_log: Some(params.ks_base_log),
ks_level: Some(params.ks_level),
pfks_level: None,
pfks_base_log: None,
pfks_modular_std_dev: None,
cbs_level: None,
cbs_base_log: None,
message_modulus: None,
carry_modulus: None,
}
}
}
#[cfg(feature = "shortint")]
impl From<Parameters> for CryptoParametersRecord {
fn from(params: Parameters) -> Self {
CryptoParametersRecord {
lwe_dimension: Some(params.lwe_dimension),
glwe_dimension: Some(params.glwe_dimension),
polynomial_size: Some(params.polynomial_size),
lwe_modular_std_dev: Some(params.lwe_modular_std_dev),
glwe_modular_std_dev: Some(params.glwe_modular_std_dev),
pbs_base_log: Some(params.pbs_base_log),
pbs_level: Some(params.pbs_level),
ks_base_log: Some(params.ks_base_log),
ks_level: Some(params.ks_level),
pfks_level: Some(params.pfks_level),
pfks_base_log: Some(params.pfks_base_log),
pfks_modular_std_dev: Some(params.pfks_modular_std_dev),
cbs_level: Some(params.cbs_level),
cbs_base_log: Some(params.cbs_base_log),
message_modulus: Some(params.message_modulus.0),
carry_modulus: Some(params.carry_modulus.0),
}
}
}
#[derive(Serialize)]
enum PolynomialMultiplication {
Fft,
// Ntt,
}
#[derive(Serialize)]
enum IntegerRepresentation {
Radix,
// Crt,
// Hybrid,
}
#[derive(Serialize)]
enum ExecutionType {
Sequential,
Parallel,
}
#[derive(Serialize)]
enum KeySetType {
Single,
// Multi,
}
#[derive(Serialize)]
enum OperandType {
CipherText,
PlainText,
}
#[derive(Clone, Serialize)]
pub enum OperatorType {
Atomic,
// AtomicPattern,
}
#[derive(Serialize)]
struct BenchmarkParametersRecord {
display_name: String,
crypto_parameters_alias: String,
crypto_parameters: CryptoParametersRecord,
message_modulus: Option<usize>,
carry_modulus: Option<usize>,
ciphertext_modulus: usize,
polynomial_multiplication: PolynomialMultiplication,
precision: u32,
error_probability: f64,
integer_representation: IntegerRepresentation,
decomposition_basis: u32,
pbs_algorithm: Option<String>,
execution_type: ExecutionType,
key_set_type: KeySetType,
operand_type: OperandType,
operator_type: OperatorType,
}
/// Writes benchmarks parameters to disk in JSON format.
pub fn write_to_json<T: Into<CryptoParametersRecord>>(
bench_id: &str,
params: T,
params_alias: impl Into<String>,
display_name: impl Into<String>,
operator_type: &OperatorType,
) {
let params = params.into();
let execution_type = match bench_id.contains("parallelized") {
true => ExecutionType::Parallel,
false => ExecutionType::Sequential,
};
let operand_type = match bench_id.contains("scalar") {
true => OperandType::PlainText,
false => OperandType::CipherText,
};
let record = BenchmarkParametersRecord {
display_name: display_name.into(),
crypto_parameters_alias: params_alias.into(),
crypto_parameters: params.to_owned(),
message_modulus: params.message_modulus,
carry_modulus: params.carry_modulus,
ciphertext_modulus: 64,
polynomial_multiplication: PolynomialMultiplication::Fft,
precision: (params.message_modulus.unwrap_or(2) as u32).ilog2(),
error_probability: 2f64.powf(-41.0),
integer_representation: IntegerRepresentation::Radix,
decomposition_basis: (params.message_modulus.unwrap_or(2) as u32).ilog2(),
pbs_algorithm: None, // To be added in future version
execution_type,
key_set_type: KeySetType::Single,
operand_type,
operator_type: operator_type.to_owned(),
};
let mut params_directory = ["benchmarks_parameters", bench_id]
.iter()
.collect::<PathBuf>();
fs::create_dir_all(&params_directory).unwrap();
params_directory.push("parameters.json");
fs::write(params_directory, serde_json::to_string(&record).unwrap()).unwrap();
}
// Empty main to please clippy.
#[allow(dead_code)]
pub fn main() {}

View File

@@ -1,10 +1,12 @@
// tfhe/build.rs
#[cfg(feature = "__c_api")]
fn gen_c_api() {
use std::env;
use std::path::PathBuf;
if std::env::var("_CBINDGEN_IS_RUNNING").is_ok() {
return;
}
/// Find the location of the `target/` directory. Note that this may be
/// overridden by `cmake`, so we also need to check the `CARGO_TARGET_DIR`
/// variable.
@@ -24,7 +26,35 @@ fn gen_c_api() {
.display()
.to_string();
cbindgen::generate(crate_dir)
let parse_expand_features_vec = vec![
#[cfg(feature = "__c_api")]
"__c_api",
#[cfg(feature = "boolean-c-api")]
"boolean-c-api",
#[cfg(feature = "shortint-c-api")]
"shortint-c-api",
#[cfg(feature = "high-level-c-api")]
"high-level-c-api",
#[cfg(feature = "boolean")]
"boolean",
#[cfg(feature = "shortint")]
"shortint",
#[cfg(feature = "integer")]
"integer",
];
let parse_expand_vec = if parse_expand_features_vec.is_empty() {
vec![]
} else {
vec![package_name.as_str()]
};
cbindgen::Builder::new()
.with_crate(crate_dir.clone())
.with_config(cbindgen::Config::from_root_or_default(crate_dir))
.with_parse_expand(&parse_expand_vec)
.with_parse_expand_features(&parse_expand_features_vec)
.generate()
.unwrap()
.write_to_file(output_file);
}

View File

@@ -0,0 +1,117 @@
#include <tfhe.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
int uint128_client_key(const ClientKey *client_key) {
int ok;
FheUint128 *lhs = NULL;
FheUint128 *rhs = NULL;
FheUint128 *result = NULL;
ok = fhe_uint128_try_encrypt_with_client_key_u128(10, 20, client_key, &lhs);
assert(ok == 0);
ok = fhe_uint128_try_encrypt_with_client_key_u128(1, 2, client_key, &rhs);
assert(ok == 0);
ok = fhe_uint128_sub(lhs, rhs, &result);
assert(ok == 0);
uint64_t w0, w1;
ok = fhe_uint128_decrypt(result, client_key, &w0, &w1);
assert(ok == 0);
assert(w0 == 9);
assert(w1 == 18);
fhe_uint128_destroy(lhs);
fhe_uint128_destroy(rhs);
fhe_uint128_destroy(result);
return ok;
}
int uint128_encrypt_trivial(const ClientKey *client_key) {
int ok;
FheUint128 *lhs = NULL;
FheUint128 *rhs = NULL;
FheUint128 *result = NULL;
ok = fhe_uint128_try_encrypt_trivial_u128(10, 20, &lhs);
assert(ok == 0);
ok = fhe_uint128_try_encrypt_trivial_u128(1, 2, &rhs);
assert(ok == 0);
ok = fhe_uint128_sub(lhs, rhs, &result);
assert(ok == 0);
uint64_t w0, w1;
ok = fhe_uint128_decrypt(result, client_key, &w0, &w1);
assert(ok == 0);
assert(w0 == 9);
assert(w1 == 18);
fhe_uint128_destroy(lhs);
fhe_uint128_destroy(rhs);
fhe_uint128_destroy(result);
return ok;
}
int uint128_public_key(const ClientKey *client_key, const PublicKey *public_key) {
int ok;
FheUint128 *lhs = NULL;
FheUint128 *rhs = NULL;
FheUint128 *result = NULL;
ok = fhe_uint128_try_encrypt_with_public_key_u128(1, 2, public_key, &lhs);
assert(ok == 0);
ok = fhe_uint128_try_encrypt_with_public_key_u128(10, 20, public_key, &rhs);
assert(ok == 0);
ok = fhe_uint128_add(lhs, rhs, &result);
assert(ok == 0);
uint64_t w0, w1;
ok = fhe_uint128_decrypt(result, client_key, &w0, &w1);
assert(ok == 0);
assert(w0 == 11);
assert(w1 == 22);
fhe_uint128_destroy(lhs);
fhe_uint128_destroy(rhs);
fhe_uint128_destroy(result);
return ok;
}
int main(void) {
int ok = 0;
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_uint128_small(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
PublicKey *public_key = NULL;
generate_keys(config, &client_key, &server_key);
public_key_new(client_key, &public_key);
set_server_key(server_key);
uint128_client_key(client_key);
uint128_encrypt_trivial(client_key);
uint128_public_key(client_key, public_key);
client_key_destroy(client_key);
public_key_destroy(public_key);
server_key_destroy(server_key);
return ok;
}

View File

@@ -0,0 +1,165 @@
#include <tfhe.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
int uint256_client_key(const ClientKey *client_key) {
int ok;
FheUint256 *lhs = NULL;
FheUint256 *rhs = NULL;
FheUint256 *result = NULL;
U256 *lhs_clear = NULL;
U256 *rhs_clear = NULL;
U256 *result_clear = NULL;
ok = u256_from_u64_words(1, 2, 3, 4, &lhs_clear);
assert(ok == 0);
ok = u256_from_u64_words(5, 6, 7, 8, &rhs_clear);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_with_client_key_u256(lhs_clear, client_key, &lhs);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_with_client_key_u256(rhs_clear, client_key, &rhs);
assert(ok == 0);
ok = fhe_uint256_add(lhs, rhs, &result);
assert(ok == 0);
ok = fhe_uint256_decrypt(result, client_key, &result_clear);
assert(ok == 0);
uint64_t w0, w1, w2, w3;
ok = u256_to_u64_words(result_clear, &w0, &w1, &w2, &w3);
assert(ok == 0);
assert(w0 == 6);
assert(w1 == 8);
assert(w2 == 10);
assert(w3 == 12);
u256_destroy(lhs_clear);
u256_destroy(rhs_clear);
u256_destroy(result_clear);
fhe_uint256_destroy(lhs);
fhe_uint256_destroy(rhs);
fhe_uint256_destroy(result);
return ok;
}
int uint256_encrypt_trivial(const ClientKey *client_key) {
int ok;
FheUint256 *lhs = NULL;
FheUint256 *rhs = NULL;
FheUint256 *result = NULL;
U256 *lhs_clear = NULL;
U256 *rhs_clear = NULL;
U256 *result_clear = NULL;
ok = u256_from_u64_words(1, 2, 3, 4, &lhs_clear);
assert(ok == 0);
ok = u256_from_u64_words(5, 6, 7, 8, &rhs_clear);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_trivial_u256(lhs_clear, &lhs);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_trivial_u256(rhs_clear, &rhs);
assert(ok == 0);
ok = fhe_uint256_add(lhs, rhs, &result);
assert(ok == 0);
ok = fhe_uint256_decrypt(result, client_key, &result_clear);
assert(ok == 0);
uint64_t w0, w1, w2, w3;
ok = u256_to_u64_words(result_clear, &w0, &w1, &w2, &w3);
assert(ok == 0);
assert(w0 == 6);
assert(w1 == 8);
assert(w2 == 10);
assert(w3 == 12);
u256_destroy(lhs_clear);
u256_destroy(rhs_clear);
u256_destroy(result_clear);
fhe_uint256_destroy(lhs);
fhe_uint256_destroy(rhs);
fhe_uint256_destroy(result);
return ok;
}
int uint256_public_key(const ClientKey *client_key, const PublicKey *public_key) {
int ok;
FheUint256 *lhs = NULL;
FheUint256 *rhs = NULL;
FheUint256 *result = NULL;
U256 *lhs_clear = NULL;
U256 *rhs_clear = NULL;
U256 *result_clear = NULL;
ok = u256_from_u64_words(5, 6, 7, 8, &lhs_clear);
assert(ok == 0);
ok = u256_from_u64_words(1, 2, 3, 4, &rhs_clear);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_with_public_key_u256(lhs_clear, public_key, &lhs);
assert(ok == 0);
ok = fhe_uint256_try_encrypt_with_public_key_u256(rhs_clear, public_key, &rhs);
assert(ok == 0);
ok = fhe_uint256_sub(lhs, rhs, &result);
assert(ok == 0);
ok = fhe_uint256_decrypt(result, client_key, &result_clear);
assert(ok == 0);
uint64_t w0, w1, w2, w3;
ok = u256_to_u64_words(result_clear, &w0, &w1, &w2, &w3);
assert(ok == 0);
assert(w0 == 4);
assert(w1 == 4);
assert(w2 == 4);
assert(w3 == 4);
u256_destroy(lhs_clear);
u256_destroy(rhs_clear);
u256_destroy(result_clear);
fhe_uint256_destroy(lhs);
fhe_uint256_destroy(rhs);
fhe_uint256_destroy(result);
return ok;
}
int main(void) {
int ok = 0;
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_uint256_small(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
PublicKey *public_key = NULL;
generate_keys(config, &client_key, &server_key);
public_key_new(client_key, &public_key);
set_server_key(server_key);
uint256_client_key(client_key);
uint256_encrypt_trivial(client_key);
uint256_public_key(client_key, public_key);
client_key_destroy(client_key);
public_key_destroy(public_key);
server_key_destroy(server_key);
return ok;
}

View File

@@ -0,0 +1,129 @@
#include <tfhe.h>
#include <stdio.h>
#include <inttypes.h>
#include <assert.h>
int client_key_test(const ClientKey *client_key) {
int ok;
FheBool *lhs = NULL;
FheBool *rhs = NULL;
FheBool *result = NULL;
bool lhs_clear = 0;
bool rhs_clear = 1;
ok = fhe_bool_try_encrypt_with_client_key_bool(lhs_clear, client_key, &lhs);
assert(ok == 0);
ok = fhe_bool_try_encrypt_with_client_key_bool(rhs_clear, client_key, &rhs);
assert(ok == 0);
ok = fhe_bool_bitand(lhs, rhs, &result);
assert(ok == 0);
bool clear;
ok = fhe_bool_decrypt(result, client_key, &clear);
assert(ok == 0);
assert(clear == (lhs_clear & rhs_clear));
fhe_bool_destroy(lhs);
fhe_bool_destroy(rhs);
fhe_bool_destroy(result);
return ok;
}
int public_key_test(const ClientKey *client_key, const PublicKey *public_key) {
int ok;
FheBool *lhs = NULL;
FheBool *rhs = NULL;
FheBool *result = NULL;
bool lhs_clear = 0;
bool rhs_clear = 1;
ok = fhe_bool_try_encrypt_with_public_key_bool(lhs_clear, public_key, &lhs);
assert(ok == 0);
ok = fhe_bool_try_encrypt_with_public_key_bool(rhs_clear, public_key, &rhs);
assert(ok == 0);
ok = fhe_bool_bitand(lhs, rhs, &result);
assert(ok == 0);
bool clear;
ok = fhe_bool_decrypt(result, client_key, &clear);
assert(ok == 0);
assert(clear == (lhs_clear & rhs_clear));
fhe_bool_destroy(lhs);
fhe_bool_destroy(rhs);
fhe_bool_destroy(result);
return ok;
}
int trivial_encrypt_test(const ClientKey *client_key) {
int ok;
FheBool *lhs = NULL;
FheBool *rhs = NULL;
FheBool *result = NULL;
bool lhs_clear = 0;
bool rhs_clear = 1;
ok = fhe_bool_try_encrypt_trivial_bool(lhs_clear, &lhs);
assert(ok == 0);
ok = fhe_bool_try_encrypt_trivial_bool(rhs_clear, &rhs);
assert(ok == 0);
ok = fhe_bool_bitand(lhs, rhs, &result);
assert(ok == 0);
bool clear;
ok = fhe_bool_decrypt(result, client_key, &clear);
assert(ok == 0);
assert(clear == (lhs_clear & rhs_clear));
fhe_bool_destroy(lhs);
fhe_bool_destroy(rhs);
fhe_bool_destroy(result);
return ok;
}
int main(void)
{
ConfigBuilder *builder;
Config *config;
config_builder_all_disabled(&builder);
config_builder_enable_default_bool(&builder);
config_builder_build(builder, &config);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
PublicKey *public_key = NULL;
generate_keys(config, &client_key, &server_key);
public_key_new(client_key, &public_key);
set_server_key(server_key);
client_key_test(client_key);
public_key_test(client_key, public_key);
trivial_encrypt_test(client_key);
client_key_destroy(client_key);
public_key_destroy(public_key);
server_key_destroy(server_key);
return EXIT_SUCCESS;
}

View File

@@ -0,0 +1,213 @@
#include <tfhe.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
int uint8_client_key(const ClientKey *client_key) {
int ok;
FheUint8 *lhs = NULL;
FheUint8 *rhs = NULL;
FheUint8 *result = NULL;
uint8_t lhs_clear = 123;
uint8_t rhs_clear = 14;
ok = fhe_uint8_try_encrypt_with_client_key_u8(lhs_clear, client_key, &lhs);
assert(ok == 0);
ok = fhe_uint8_try_encrypt_with_client_key_u8(rhs_clear, client_key, &rhs);
assert(ok == 0);
ok = fhe_uint8_add(lhs, rhs, &result);
assert(ok == 0);
uint8_t clear;
ok = fhe_uint8_decrypt(result, client_key, &clear);
assert(ok == 0);
assert(clear == (lhs_clear + rhs_clear));
fhe_uint8_destroy(lhs);
fhe_uint8_destroy(rhs);
fhe_uint8_destroy(result);
return ok;
}
int uint8_public_key(const ClientKey *client_key, const PublicKey *public_key) {
int ok;
FheUint8 *lhs = NULL;
FheUint8 *rhs = NULL;
FheUint8 *result = NULL;
uint8_t lhs_clear = 123;
uint8_t rhs_clear = 14;
ok = fhe_uint8_try_encrypt_with_public_key_u8(lhs_clear, public_key, &lhs);
assert(ok == 0);
ok = fhe_uint8_try_encrypt_with_public_key_u8(rhs_clear, public_key, &rhs);
assert(ok == 0);
ok = fhe_uint8_sub(lhs, rhs, &result);
assert(ok == 0);
uint8_t clear;
ok = fhe_uint8_decrypt(result, client_key, &clear);
assert(ok == 0);
assert(clear == (lhs_clear - rhs_clear));
fhe_uint8_destroy(lhs);
fhe_uint8_destroy(rhs);
fhe_uint8_destroy(result);
return ok;
}
int uint8_serialization(const ClientKey *client_key) {
int ok;
FheUint8 *lhs = NULL;
FheUint8 *deserialized_lhs = NULL;
FheUint8 *result = NULL;
Buffer value_buffer = {.pointer = NULL, .length = 0};
Buffer cks_buffer = {.pointer = NULL, .length = 0};
BufferView deser_view = {.pointer = NULL, .length = 0};
ClientKey *deserialized_client_key = NULL;
uint8_t lhs_clear = 123;
ok = client_key_serialize(client_key, &cks_buffer);
assert(ok == 0);
deser_view.pointer = cks_buffer.pointer;
deser_view.length = cks_buffer.length;
ok = client_key_deserialize(deser_view, &deserialized_client_key);
assert(ok == 0);
ok = fhe_uint8_try_encrypt_with_client_key_u8(lhs_clear, deserialized_client_key, &lhs);
assert(ok == 0);
ok = fhe_uint8_serialize(lhs, &value_buffer);
assert(ok == 0);
deser_view.pointer = value_buffer.pointer;
deser_view.length = value_buffer.length;
ok = fhe_uint8_deserialize(deser_view, &deserialized_lhs);
assert(ok == 0);
uint8_t clear;
ok = fhe_uint8_decrypt(deserialized_lhs, deserialized_client_key, &clear);
assert(ok == 0);
assert(clear == lhs_clear);
if (value_buffer.pointer != NULL) {
destroy_buffer(&value_buffer);
}
fhe_uint8_destroy(lhs);
fhe_uint8_destroy(deserialized_lhs);
fhe_uint8_destroy(result);
return ok;
}
int uint8_compressed(const ClientKey *client_key) {
int ok;
FheUint8 *lhs = NULL;
FheUint8 *result = NULL;
CompressedFheUint8 *clhs = NULL;
uint8_t lhs_clear = 123;
ok = compressed_fhe_uint8_try_encrypt_with_client_key_u8(lhs_clear, client_key, &clhs);
assert(ok == 0);
ok = compressed_fhe_uint8_decompress(clhs, &lhs);
assert(ok == 0);
uint8_t clear;
ok = fhe_uint8_decrypt(lhs, client_key, &clear);
assert(ok == 0);
assert(clear == lhs_clear);
fhe_uint8_destroy(lhs);
compressed_fhe_uint8_destroy(clhs);
fhe_uint8_destroy(result);
return ok;
}
int main(void) {
int ok = 0;
{
ConfigBuilder *builder;
Config *config;
ok = config_builder_all_disabled(&builder);
assert(ok == 0);
ok = config_builder_enable_default_uint8(&builder);
assert(ok == 0);
ok = config_builder_build(builder, &config);
assert(ok == 0);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
PublicKey *public_key = NULL;
ok = generate_keys(config, &client_key, &server_key);
assert(ok == 0);
ok = public_key_new(client_key, &public_key);
assert(ok == 0);
ok = uint8_serialization(client_key);
assert(ok == 0);
ok = uint8_compressed(client_key);
assert(ok == 0);
ok = set_server_key(server_key);
assert(ok == 0);
ok = uint8_client_key(client_key);
assert(ok == 0);
ok = uint8_public_key(client_key, public_key);
assert(ok == 0);
client_key_destroy(client_key);
public_key_destroy(public_key);
server_key_destroy(server_key);
}
{
ConfigBuilder *builder;
Config *config;
ok = config_builder_all_disabled(&builder);
assert(ok == 0);
ok = config_builder_enable_default_uint8_small(&builder);
assert(ok == 0);
ok = config_builder_build(builder, &config);
assert(ok == 0);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
PublicKey *public_key = NULL;
ok = generate_keys(config, &client_key, &server_key);
assert(ok == 0);
ok = public_key_new(client_key, &public_key);
assert(ok == 0);
ok = set_server_key(server_key);
assert(ok == 0);
ok = uint8_client_key(client_key);
assert(ok == 0);
ok = uint8_public_key(client_key, public_key);
assert(ok == 0);
client_key_destroy(client_key);
public_key_destroy(public_key);
server_key_destroy(server_key);
}
return ok;
}

View File

@@ -88,7 +88,7 @@ void test_server_key_trivial_encrypt(void) {
int gen_keys_ok = shortint_gen_keys_with_parameters(params, &cks, &sks);
assert(gen_keys_ok == 0);
int encrypt_ok = shortint_server_key_create_trivial(sks, 3, &ct);
int encrypt_ok = shortint_server_key_create_trivial(sks, 3, ShortintCiphertextBig, &ct);
assert(encrypt_ok == 0);
uint64_t result = -1;
@@ -109,7 +109,7 @@ void test_custom_keygen(void) {
ShortintParameters *params = NULL;
int params_ok = shortint_create_parameters(10, 1, 1024, 10e-100, 10e-100, 2, 3, 2, 3, 2, 3,
10e-100, 2, 3, 2, 2, &params);
10e-100, 2, 3, 2, 2, SHORTINT_NATIVE_MODULUS, &params);
assert(params_ok == 0);
int gen_keys_ok = shortint_gen_keys_with_parameters(params, &cks, &sks);
@@ -121,7 +121,7 @@ void test_custom_keygen(void) {
destroy_shortint_server_key(sks);
}
void test_public_keygen(void) {
void test_public_keygen(ShortintPublicKeyKind pk_kind) {
ShortintClientKey *cks = NULL;
ShortintPublicKey *pks = NULL;
ShortintPublicKey *pks_deser = NULL;
@@ -135,7 +135,7 @@ void test_public_keygen(void) {
int gen_keys_ok = shortint_gen_client_key(params, &cks);
assert(gen_keys_ok == 0);
int gen_pks = shortint_gen_public_key(cks, &pks);
int gen_pks = shortint_gen_public_key(cks, pk_kind, &pks);
assert(gen_pks == 0);
int pks_ser = shortint_serialize_public_key(pks, &pks_ser_buff);
@@ -164,7 +164,7 @@ void test_public_keygen(void) {
destroy_shortint_ciphertext(ct);
}
void test_compressed_public_keygen(void) {
void test_compressed_public_keygen(ShortintPublicKeyKind pk_kind) {
ShortintClientKey *cks = NULL;
ShortintCompressedPublicKey *cpks = NULL;
ShortintPublicKey *pks = NULL;
@@ -177,7 +177,7 @@ void test_compressed_public_keygen(void) {
int gen_keys_ok = shortint_gen_client_key(params, &cks);
assert(gen_keys_ok == 0);
int gen_cpks = shortint_gen_compressed_public_key(cks, &cpks);
int gen_cpks = shortint_gen_compressed_public_key(cks, pk_kind, &cpks);
assert(gen_cpks == 0);
uint64_t msg = 2;
@@ -213,8 +213,10 @@ void test_compressed_public_keygen(void) {
int main(void) {
test_predefined_keygen_w_serde();
test_custom_keygen();
test_public_keygen();
test_compressed_public_keygen();
test_public_keygen(ShortintPublicKeyBig);
test_public_keygen(ShortintPublicKeySmall);
test_compressed_public_keygen(ShortintPublicKeyBig);
test_compressed_public_keygen(ShortintPublicKeySmall);
test_server_key_trivial_encrypt();
return EXIT_SUCCESS;
}

View File

@@ -38,7 +38,7 @@ uint64_t get_max_value_of_bivariate_accumulator_generator(uint64_t (*accumulator
}
void test_shortint_pbs_2_bits_message(void) {
ShortintPBSAccumulator *accumulator = NULL;
ShortintPBSLookupTable *accumulator = NULL;
ShortintClientKey *cks = NULL;
ShortintServerKey *sks = NULL;
ShortintParameters *params = NULL;
@@ -115,7 +115,7 @@ void test_shortint_pbs_2_bits_message(void) {
}
void test_shortint_bivariate_pbs_2_bits_message(void) {
ShortintBivariatePBSAccumulator *accumulator = NULL;
ShortintBivariatePBSLookupTable *accumulator = NULL;
ShortintClientKey *cks = NULL;
ShortintServerKey *sks = NULL;
ShortintParameters *params = NULL;

View File

@@ -5,250 +5,365 @@
#include <stdlib.h>
#include <tgmath.h>
typedef int (*BinaryCallback)(const ShortintServerKey *, ShortintCiphertext *, ShortintCiphertext *,
ShortintCiphertext **);
typedef int (*BinaryAssignCallback)(const ShortintServerKey *, ShortintCiphertext *,
ShortintCiphertext *);
typedef int (*BinaryScalarCallback)(const ShortintServerKey *, ShortintCiphertext *, uint8_t,
ShortintCiphertext **);
typedef int (*UnaryCallback)(const ShortintServerKey *, ShortintCiphertext *,
ShortintCiphertext **);
typedef int (*UnaryAssignCallback)(const ShortintServerKey *, ShortintCiphertext *);
void test_shortint_unary_op(const ShortintClientKey *cks, const ShortintServerKey *sks,
const ShortintClientKey *cks_small, const ShortintServerKey *sks_small,
const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t),
int (*api_fun)(const ShortintServerKey *, ShortintCiphertext *,
ShortintCiphertext **)) {
uint64_t (*c_fun)(uint64_t), UnaryCallback api_fun) {
int message_max = 1 << message_bits;
for (int val_in = 0; val_in < message_max; ++val_in) {
ShortintCiphertext *ct_in = NULL;
ShortintCiphertext *ct_result = NULL;
uint64_t in = (uint64_t)val_in;
uint64_t expected = c_fun(in) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, in, &ct_in);
assert(encrypt_left_ok == 0);
int api_call_ok = api_fun(sks, ct_in, &ct_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks, ct_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_in);
destroy_shortint_ciphertext(ct_result);
}
}
void test_shortint_unary_op_assign(const ShortintClientKey *cks, const ShortintServerKey *sks,
const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t),
int (*api_fun)(const ShortintServerKey *,
ShortintCiphertext *)) {
int message_max = 1 << message_bits;
for (int in = 0; in < message_max; ++in) {
ShortintCiphertext *ct_in_and_result = NULL;
uint64_t in = (uint64_t)in;
uint64_t expected = c_fun(in) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, in, &ct_in_and_result);
assert(encrypt_left_ok == 0);
int api_call_ok = api_fun(sks, ct_in_and_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks, ct_in_and_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_in_and_result);
}
}
void test_shortint_binary_op(const ShortintClientKey *cks, const ShortintServerKey *sks,
const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t, uint64_t),
int (*api_fun)(const ShortintServerKey *, ShortintCiphertext *,
ShortintCiphertext *, ShortintCiphertext **)) {
int message_max = 1 << message_bits;
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left = NULL;
ShortintCiphertext *ct_right = NULL;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int val_in = 0; val_in < message_max; ++val_in) {
ShortintCiphertext *ct_in = NULL;
ShortintCiphertext *ct_result = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t left = (uint64_t)val_left;
uint64_t right = (uint64_t)val_right;
uint64_t in = (uint64_t)val_in;
uint64_t expected = c_fun(left, right) % message_max;
uint64_t expected = c_fun(in) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, left, &ct_left);
assert(encrypt_left_ok == 0);
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_right_ok = shortint_client_key_encrypt(cks, right, &ct_right);
assert(encrypt_right_ok == 0);
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, in, &ct_in);
assert(encrypt_left_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
int api_call_ok = api_fun(sks, ct_left, ct_right, &ct_result);
int encrypt_left_ok = shortint_client_key_encrypt_small(cks_in_use, in, &ct_in);
assert(encrypt_left_ok == 0);
}
int api_call_ok = api_fun(sks_in_use, ct_in, &ct_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks, ct_result, &decrypted_result);
int decrypt_ok = shortint_client_key_decrypt(cks_in_use, ct_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left);
destroy_shortint_ciphertext(ct_right);
destroy_shortint_ciphertext(ct_in);
destroy_shortint_ciphertext(ct_result);
}
}
}
void test_shortint_unary_op_assign(const ShortintClientKey *cks, const ShortintServerKey *sks,
const ShortintClientKey *cks_small,
const ShortintServerKey *sks_small, const uint32_t message_bits,
const uint32_t carry_bits, uint64_t (*c_fun)(uint64_t),
UnaryAssignCallback api_fun) {
int message_max = 1 << message_bits;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int in = 0; in < message_max; ++in) {
ShortintCiphertext *ct_in_and_result = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t in = (uint64_t)in;
uint64_t expected = c_fun(in) % message_max;
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, in, &ct_in_and_result);
assert(encrypt_left_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
int encrypt_left_ok = shortint_client_key_encrypt_small(cks_in_use, in, &ct_in_and_result);
assert(encrypt_left_ok == 0);
}
int api_call_ok = api_fun(sks_in_use, ct_in_and_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks_in_use, ct_in_and_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_in_and_result);
}
}
}
void test_shortint_binary_op(const ShortintClientKey *cks, const ShortintServerKey *sks,
const ShortintClientKey *cks_small, const ShortintServerKey *sks_small,
const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t, uint64_t), BinaryCallback api_fun) {
int message_max = 1 << message_bits;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left = NULL;
ShortintCiphertext *ct_right = NULL;
ShortintCiphertext *ct_result = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t left = (uint64_t)val_left;
uint64_t right = (uint64_t)val_right;
uint64_t expected = c_fun(left, right) % message_max;
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, left, &ct_left);
assert(encrypt_left_ok == 0);
int encrypt_right_ok = shortint_client_key_encrypt(cks_in_use, right, &ct_right);
assert(encrypt_right_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
int encrypt_left_ok = shortint_client_key_encrypt_small(cks_in_use, left, &ct_left);
assert(encrypt_left_ok == 0);
int encrypt_right_ok = shortint_client_key_encrypt_small(cks_in_use, right, &ct_right);
assert(encrypt_right_ok == 0);
}
int api_call_ok = api_fun(sks_in_use, ct_left, ct_right, &ct_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks_in_use, ct_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left);
destroy_shortint_ciphertext(ct_right);
destroy_shortint_ciphertext(ct_result);
}
}
}
}
void test_shortint_binary_op_assign(const ShortintClientKey *cks, const ShortintServerKey *sks,
const uint32_t message_bits, const uint32_t carry_bits,
const ShortintClientKey *cks_small,
const ShortintServerKey *sks_small, const uint32_t message_bits,
const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t, uint64_t),
int (*api_fun)(const ShortintServerKey *, ShortintCiphertext *,
ShortintCiphertext *)) {
BinaryAssignCallback api_fun) {
int message_max = 1 << message_bits;
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left_and_result = NULL;
ShortintCiphertext *ct_right = NULL;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left_and_result = NULL;
ShortintCiphertext *ct_right = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t left = (uint64_t)val_left;
uint64_t right = (uint64_t)val_right;
uint64_t left = (uint64_t)val_left;
uint64_t right = (uint64_t)val_right;
uint64_t expected = c_fun(left, right) % message_max;
uint64_t expected = c_fun(left, right) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_right_ok = shortint_client_key_encrypt(cks, right, &ct_right);
assert(encrypt_right_ok == 0);
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
int api_call_ok = api_fun(sks, ct_left_and_result, ct_right);
assert(api_call_ok == 0);
int encrypt_right_ok = shortint_client_key_encrypt(cks_in_use, right, &ct_right);
assert(encrypt_right_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
uint64_t decrypted_result = -1;
int encrypt_left_ok =
shortint_client_key_encrypt_small(cks_in_use, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
int decrypt_ok = shortint_client_key_decrypt(cks, ct_left_and_result, &decrypted_result);
assert(decrypt_ok == 0);
int encrypt_right_ok = shortint_client_key_encrypt_small(cks_in_use, right, &ct_right);
assert(encrypt_right_ok == 0);
}
assert(decrypted_result == expected);
int api_call_ok = api_fun(sks_in_use, ct_left_and_result, ct_right);
assert(api_call_ok == 0);
destroy_shortint_ciphertext(ct_left_and_result);
destroy_shortint_ciphertext(ct_right);
uint64_t decrypted_result = -1;
int decrypt_ok =
shortint_client_key_decrypt(cks_in_use, ct_left_and_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left_and_result);
destroy_shortint_ciphertext(ct_right);
}
}
}
}
void test_shortint_binary_scalar_op(
const ShortintClientKey *cks, const ShortintServerKey *sks, const uint32_t message_bits,
const uint32_t carry_bits, uint64_t (*c_fun)(uint64_t, uint8_t),
const ShortintClientKey *cks, const ShortintServerKey *sks, const ShortintClientKey *cks_small,
const ShortintServerKey *sks_small, const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t, uint8_t),
int (*api_fun)(const ShortintServerKey *, ShortintCiphertext *, uint8_t, ShortintCiphertext **),
uint8_t forbidden_scalar_values[], size_t forbidden_scalar_values_len) {
int message_max = 1 << message_bits;
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left = NULL;
ShortintCiphertext *ct_result = NULL;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left = NULL;
ShortintCiphertext *ct_result = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t left = (uint64_t)val_left;
uint8_t scalar_right = (uint8_t)val_right;
uint64_t left = (uint64_t)val_left;
uint8_t scalar_right = (uint8_t)val_right;
if (forbidden_scalar_values != NULL) {
bool found_forbidden_value = false;
for (int idx = 0; idx < forbidden_scalar_values_len; ++idx) {
if (forbidden_scalar_values[idx] == scalar_right) {
found_forbidden_value = true;
break;
if (forbidden_scalar_values != NULL) {
bool found_forbidden_value = false;
for (int idx = 0; idx < forbidden_scalar_values_len; ++idx) {
if (forbidden_scalar_values[idx] == scalar_right) {
found_forbidden_value = true;
break;
}
}
if (found_forbidden_value) {
continue;
}
}
if (found_forbidden_value) {
continue;
uint64_t expected = c_fun(left, scalar_right) % message_max;
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, left, &ct_left);
assert(encrypt_left_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
int encrypt_left_ok = shortint_client_key_encrypt_small(cks_in_use, left, &ct_left);
assert(encrypt_left_ok == 0);
}
int api_call_ok = api_fun(sks_in_use, ct_left, scalar_right, &ct_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks_in_use, ct_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left);
destroy_shortint_ciphertext(ct_result);
}
uint64_t expected = c_fun(left, scalar_right) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, left, &ct_left);
assert(encrypt_left_ok == 0);
int api_call_ok = api_fun(sks, ct_left, scalar_right, &ct_result);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks, ct_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left);
destroy_shortint_ciphertext(ct_result);
}
}
}
void test_shortint_binary_scalar_op_assign(
const ShortintClientKey *cks, const ShortintServerKey *sks, const uint32_t message_bits,
const uint32_t carry_bits, uint64_t (*c_fun)(uint64_t, uint8_t),
const ShortintClientKey *cks, const ShortintServerKey *sks, const ShortintClientKey *cks_small,
const ShortintServerKey *sks_small, const uint32_t message_bits, const uint32_t carry_bits,
uint64_t (*c_fun)(uint64_t, uint8_t),
int (*api_fun)(const ShortintServerKey *, ShortintCiphertext *, uint8_t),
uint8_t forbidden_scalar_values[], size_t forbidden_scalar_values_len) {
int message_max = 1 << message_bits;
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left_and_result = NULL;
for (int is_big = 0; is_big < 2; ++is_big) {
for (int val_left = 0; val_left < message_max; ++val_left) {
for (int val_right = 0; val_right < message_max; ++val_right) {
ShortintCiphertext *ct_left_and_result = NULL;
const ShortintClientKey *cks_in_use = NULL;
const ShortintServerKey *sks_in_use = NULL;
uint64_t left = (uint64_t)val_left;
uint8_t scalar_right = (uint8_t)val_right;
uint64_t left = (uint64_t)val_left;
uint8_t scalar_right = (uint8_t)val_right;
if (forbidden_scalar_values != NULL) {
bool found_forbidden_value = false;
for (int idx = 0; idx < forbidden_scalar_values_len; ++idx) {
if (forbidden_scalar_values[idx] == scalar_right) {
found_forbidden_value = true;
break;
if (forbidden_scalar_values != NULL) {
bool found_forbidden_value = false;
for (int idx = 0; idx < forbidden_scalar_values_len; ++idx) {
if (forbidden_scalar_values[idx] == scalar_right) {
found_forbidden_value = true;
break;
}
}
if (found_forbidden_value) {
continue;
}
}
if (found_forbidden_value) {
continue;
uint64_t expected = c_fun(left, scalar_right) % message_max;
if (is_big == 1) {
cks_in_use = cks;
sks_in_use = sks;
int encrypt_left_ok = shortint_client_key_encrypt(cks_in_use, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
} else {
cks_in_use = cks_small;
sks_in_use = sks_small;
int encrypt_left_ok =
shortint_client_key_encrypt_small(cks_in_use, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
}
int api_call_ok = api_fun(sks_in_use, ct_left_and_result, scalar_right);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok =
shortint_client_key_decrypt(cks_in_use, ct_left_and_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left_and_result);
}
uint64_t expected = c_fun(left, scalar_right) % message_max;
int encrypt_left_ok = shortint_client_key_encrypt(cks, left, &ct_left_and_result);
assert(encrypt_left_ok == 0);
int api_call_ok = api_fun(sks, ct_left_and_result, scalar_right);
assert(api_call_ok == 0);
uint64_t decrypted_result = -1;
int decrypt_ok = shortint_client_key_decrypt(cks, ct_left_and_result, &decrypted_result);
assert(decrypt_ok == 0);
assert(decrypted_result == expected);
destroy_shortint_ciphertext(ct_left_and_result);
}
}
}
@@ -305,6 +420,9 @@ void test_server_key(void) {
Buffer sks_ser_buffer = {.pointer = NULL, .length = 0};
ShortintServerKey *deser_sks = NULL;
ShortintParameters *params = NULL;
ShortintClientKey *cks_small = NULL;
ShortintServerKey *sks_small = NULL;
ShortintParameters *params_small = NULL;
const uint32_t message_bits = 2;
const uint32_t carry_bits = 2;
@@ -312,9 +430,18 @@ void test_server_key(void) {
int get_params_ok = shortint_get_parameters(message_bits, carry_bits, &params);
assert(get_params_ok == 0);
int get_params_small_ok = shortint_get_parameters(message_bits, carry_bits, &params_small);
assert(get_params_small_ok == 0);
int gen_cks_ok = shortint_gen_client_key(params, &cks);
assert(gen_cks_ok == 0);
int gen_cks_small_ok = shortint_gen_client_key(params_small, &cks_small);
assert(gen_cks_small_ok == 0);
int gen_sks_small_ok = shortint_gen_server_key(cks_small, &sks_small);
assert(gen_sks_small_ok == 0);
int gen_csks_ok = shortint_gen_compressed_server_key(cks, &csks);
assert(gen_csks_ok == 0);
@@ -348,225 +475,269 @@ void test_server_key(void) {
assert(deser_sks_ok == 0);
printf("add\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, add,
shortint_server_key_smart_add);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, add,
shortint_server_key_unchecked_add);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, add,
shortint_server_key_smart_add_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, add,
shortint_server_key_unchecked_add_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, add,
(BinaryCallback)shortint_server_key_smart_add);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, add,
(BinaryCallback)shortint_server_key_unchecked_add);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, add,
(BinaryAssignCallback)shortint_server_key_smart_add_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, add,
(BinaryAssignCallback)shortint_server_key_unchecked_add_assign);
printf("sub\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, sub,
shortint_server_key_smart_sub);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, sub,
shortint_server_key_unchecked_sub);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, sub,
shortint_server_key_smart_sub_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, sub,
shortint_server_key_unchecked_sub_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, sub,
(BinaryCallback)shortint_server_key_smart_sub);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, sub,
(BinaryCallback)shortint_server_key_unchecked_sub);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, sub,
(BinaryAssignCallback)shortint_server_key_smart_sub_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, sub,
(BinaryAssignCallback)shortint_server_key_unchecked_sub_assign);
printf("mul\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, mul,
shortint_server_key_smart_mul);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, mul,
shortint_server_key_unchecked_mul);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, mul,
shortint_server_key_smart_mul_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, mul,
shortint_server_key_unchecked_mul_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, mul,
(BinaryCallback)shortint_server_key_smart_mul);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, mul,
(BinaryCallback)shortint_server_key_unchecked_mul);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, mul,
(BinaryAssignCallback)shortint_server_key_smart_mul_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, mul,
(BinaryAssignCallback)shortint_server_key_unchecked_mul_assign);
printf("left_shift\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, left_shift,
shortint_server_key_smart_scalar_left_shift, NULL, 0);
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, left_shift,
shortint_server_key_unchecked_scalar_left_shift, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, left_shift,
shortint_server_key_smart_scalar_left_shift_assign, NULL,
0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, left_shift,
shortint_server_key_unchecked_scalar_left_shift_assign,
NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, left_shift,
(BinaryScalarCallback)shortint_server_key_smart_scalar_left_shift, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, left_shift,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_left_shift, NULL, 0);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, left_shift,
shortint_server_key_smart_scalar_left_shift_assign, NULL, 0);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, left_shift,
shortint_server_key_unchecked_scalar_left_shift_assign, NULL, 0);
printf("right_shift\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, right_shift,
shortint_server_key_smart_scalar_right_shift, NULL, 0);
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, right_shift,
shortint_server_key_unchecked_scalar_right_shift, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, right_shift,
shortint_server_key_smart_scalar_right_shift_assign, NULL,
0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, right_shift,
shortint_server_key_unchecked_scalar_right_shift_assign,
NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, right_shift,
(BinaryScalarCallback)shortint_server_key_smart_scalar_right_shift, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, right_shift,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_right_shift, NULL, 0);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, right_shift,
shortint_server_key_smart_scalar_right_shift_assign, NULL, 0);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, right_shift,
shortint_server_key_unchecked_scalar_right_shift_assign, NULL, 0);
printf("scalar_add\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_add,
shortint_server_key_smart_scalar_add, NULL, 0);
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_add,
shortint_server_key_unchecked_scalar_add, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_add,
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_add,
(BinaryScalarCallback)shortint_server_key_smart_scalar_add, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_add,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_add, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_add,
shortint_server_key_smart_scalar_add_assign, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_add,
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_add,
shortint_server_key_unchecked_scalar_add_assign, NULL, 0);
printf("scalar_sub\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_sub,
shortint_server_key_smart_scalar_sub, NULL, 0);
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_sub,
shortint_server_key_unchecked_scalar_sub, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_sub,
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_sub,
(BinaryScalarCallback)shortint_server_key_smart_scalar_sub, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_sub,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_sub, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_sub,
shortint_server_key_smart_scalar_sub_assign, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_sub,
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_sub,
shortint_server_key_unchecked_scalar_sub_assign, NULL, 0);
printf("scalar_mul\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_mul,
shortint_server_key_smart_scalar_mul, NULL, 0);
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_mul,
shortint_server_key_unchecked_scalar_mul, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_mul,
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_mul,
(BinaryScalarCallback)shortint_server_key_smart_scalar_mul, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_mul,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_mul, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_mul,
shortint_server_key_smart_scalar_mul_assign, NULL, 0);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_mul,
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_mul,
shortint_server_key_unchecked_scalar_mul_assign, NULL, 0);
printf("bitand\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitand,
shortint_server_key_smart_bitand);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitand,
shortint_server_key_unchecked_bitand);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitand,
shortint_server_key_smart_bitand_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitand,
shortint_server_key_unchecked_bitand_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitand, (BinaryCallback)shortint_server_key_smart_bitand);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitand, (BinaryCallback)shortint_server_key_unchecked_bitand);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitand,
(BinaryAssignCallback)shortint_server_key_smart_bitand_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitand,
(BinaryAssignCallback)shortint_server_key_unchecked_bitand_assign);
printf("bitxor\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitxor,
shortint_server_key_smart_bitxor);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitxor,
shortint_server_key_unchecked_bitxor);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitxor,
shortint_server_key_smart_bitxor_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitxor,
shortint_server_key_unchecked_bitxor_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
bitxor, (BinaryCallback)shortint_server_key_smart_bitxor);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
bitxor, (BinaryCallback)shortint_server_key_unchecked_bitxor);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitxor,
(BinaryAssignCallback)shortint_server_key_smart_bitxor_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitxor,
(BinaryAssignCallback)shortint_server_key_unchecked_bitxor_assign);
printf("bitor\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitor,
shortint_server_key_smart_bitor);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, bitor,
shortint_server_key_unchecked_bitor);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitor,
shortint_server_key_smart_bitor_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, bitor,
shortint_server_key_unchecked_bitor_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
bitor, (BinaryCallback)shortint_server_key_smart_bitor);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
bitor, (BinaryCallback)shortint_server_key_unchecked_bitor);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitor,
(BinaryAssignCallback)shortint_server_key_smart_bitor_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, bitor,
(BinaryAssignCallback)shortint_server_key_unchecked_bitor_assign);
printf("greater\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, greater,
shortint_server_key_smart_greater);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, greater,
shortint_server_key_unchecked_greater);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
greater, (BinaryCallback)shortint_server_key_smart_greater);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
greater, (BinaryCallback)shortint_server_key_unchecked_greater);
printf("greater_or_equal\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, greater_or_equal,
shortint_server_key_smart_greater_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, greater_or_equal,
shortint_server_key_unchecked_greater_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
greater_or_equal,
(BinaryCallback)shortint_server_key_smart_greater_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
greater_or_equal,
(BinaryCallback)shortint_server_key_unchecked_greater_or_equal);
printf("less\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, less,
shortint_server_key_smart_less);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, less,
shortint_server_key_unchecked_less);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
less, (BinaryCallback)shortint_server_key_smart_less);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
less, (BinaryCallback)shortint_server_key_unchecked_less);
printf("less_or_equal\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, less_or_equal,
shortint_server_key_smart_less_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, less_or_equal,
shortint_server_key_unchecked_less_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
less_or_equal, (BinaryCallback)shortint_server_key_smart_less_or_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
less_or_equal,
(BinaryCallback)shortint_server_key_unchecked_less_or_equal);
printf("equal\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, equal,
shortint_server_key_smart_equal);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, equal,
shortint_server_key_unchecked_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
equal, (BinaryCallback)shortint_server_key_smart_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
equal, (BinaryCallback)shortint_server_key_unchecked_equal);
printf("not_equal\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, not_equal,
shortint_server_key_smart_not_equal);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, not_equal,
shortint_server_key_unchecked_not_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
not_equal, (BinaryCallback)shortint_server_key_smart_not_equal);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
not_equal, (BinaryCallback)shortint_server_key_unchecked_not_equal);
printf("scalar_greater\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_greater,
shortint_server_key_smart_scalar_greater, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_greater,
(BinaryScalarCallback)shortint_server_key_smart_scalar_greater, NULL, 0);
printf("scalar_greater_or_equal\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits,
scalar_greater_or_equal,
shortint_server_key_smart_scalar_greater_or_equal, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_greater_or_equal,
(BinaryScalarCallback)shortint_server_key_smart_scalar_greater_or_equal, NULL, 0);
printf("scalar_less\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_less,
shortint_server_key_smart_scalar_less, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_less,
(BinaryScalarCallback)shortint_server_key_smart_scalar_less, NULL, 0);
printf("scalar_less_or_equal\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits,
scalar_less_or_equal,
shortint_server_key_smart_scalar_less_or_equal, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_less_or_equal,
(BinaryScalarCallback)shortint_server_key_smart_scalar_less_or_equal, NULL, 0);
printf("scalar_equal\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_equal,
shortint_server_key_smart_scalar_equal, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_equal,
(BinaryScalarCallback)shortint_server_key_smart_scalar_equal, NULL, 0);
printf("scalar_not_equal\n");
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_not_equal,
shortint_server_key_smart_scalar_not_equal, NULL, 0);
test_shortint_binary_scalar_op(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_not_equal,
(BinaryScalarCallback)shortint_server_key_smart_scalar_not_equal, NULL, 0);
printf("neg\n");
test_shortint_unary_op(deser_cks, deser_sks, message_bits, carry_bits, neg,
shortint_server_key_smart_neg);
test_shortint_unary_op(deser_cks, deser_sks, message_bits, carry_bits, neg,
shortint_server_key_unchecked_neg);
test_shortint_unary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, neg,
shortint_server_key_smart_neg_assign);
test_shortint_unary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, neg,
shortint_server_key_unchecked_neg_assign);
test_shortint_unary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, neg,
(UnaryCallback)shortint_server_key_smart_neg);
test_shortint_unary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, neg,
(UnaryCallback)shortint_server_key_unchecked_neg);
test_shortint_unary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, neg,
(UnaryAssignCallback)shortint_server_key_smart_neg_assign);
test_shortint_unary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, neg,
(UnaryAssignCallback)shortint_server_key_unchecked_neg_assign);
printf("div\n");
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, homomorphic_div,
shortint_server_key_smart_div);
test_shortint_binary_op(deser_cks, deser_sks, message_bits, carry_bits, homomorphic_div,
shortint_server_key_unchecked_div);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, homomorphic_div,
shortint_server_key_smart_div_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, message_bits, carry_bits, homomorphic_div,
shortint_server_key_unchecked_div_assign);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
homomorphic_div, (BinaryCallback)shortint_server_key_smart_div);
test_shortint_binary_op(deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits,
homomorphic_div, (BinaryCallback)shortint_server_key_unchecked_div);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, homomorphic_div,
(BinaryAssignCallback)shortint_server_key_smart_div_assign);
test_shortint_binary_op_assign(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, homomorphic_div,
(BinaryAssignCallback)shortint_server_key_unchecked_div_assign);
printf("scalar_div\n");
uint8_t forbidden_scalar_div_values[1] = {0};
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_div,
shortint_server_key_unchecked_scalar_div,
test_shortint_binary_scalar_op(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_div,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_div,
forbidden_scalar_div_values, 1);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_div,
shortint_server_key_unchecked_scalar_div_assign,
forbidden_scalar_div_values, 1);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_div,
shortint_server_key_unchecked_scalar_div_assign, forbidden_scalar_div_values, 1);
printf("scalar_mod\n");
uint8_t forbidden_scalar_mod_values[1] = {0};
test_shortint_binary_scalar_op(deser_cks, deser_sks, message_bits, carry_bits, scalar_mod,
shortint_server_key_unchecked_scalar_mod,
test_shortint_binary_scalar_op(deser_cks, deser_sks, cks_small, sks_small, message_bits,
carry_bits, scalar_mod,
(BinaryScalarCallback)shortint_server_key_unchecked_scalar_mod,
forbidden_scalar_mod_values, 1);
test_shortint_binary_scalar_op_assign(deser_cks, deser_sks, message_bits, carry_bits, scalar_mod,
shortint_server_key_unchecked_scalar_mod_assign,
forbidden_scalar_mod_values, 1);
test_shortint_binary_scalar_op_assign(
deser_cks, deser_sks, cks_small, sks_small, message_bits, carry_bits, scalar_mod,
shortint_server_key_unchecked_scalar_mod_assign, forbidden_scalar_mod_values, 1);
destroy_shortint_client_key(cks);
destroy_shortint_client_key(cks_small);
destroy_shortint_compressed_server_key(csks);
destroy_shortint_server_key(sks);
destroy_shortint_server_key(sks_small);
destroy_shortint_client_key(deser_cks);
destroy_shortint_compressed_server_key(deser_csks);
destroy_shortint_server_key(deser_sks);
destroy_shortint_parameters(params);
destroy_shortint_parameters(params_small);
destroy_buffer(&cks_ser_buffer);
destroy_buffer(&csks_ser_buffer);
destroy_buffer(&sks_ser_buffer);

View File

@@ -107,7 +107,6 @@ allow_static_const = true
allow_constexpr = false
sort_by = "Name"
[macro_expansion]
bitflags = false

View File

@@ -1,6 +1,6 @@
# Operations
In tfhe::boolean, the available operations are mainly related to their equivalent Boolean gates (i.e., AND, OR... etc). What follows is an example of a unary gate (NOT) and one about a binary gate (XOR). The last one is about the ternary MUX gate, which gives the possibility to homomorphically compute conditional statements of the form `If..Then..Else`.
In tfhe::boolean, the available operations are mainly related to their equivalent Boolean gates (i.e., AND, OR... etc). What follows are examples of a unary gate (NOT) and a binary gate (XOR). The last one is about the ternary MUX gate, which allows homomorphic computation of conditional statements of the form `If..Then..Else`.
## The NOT unary gate

View File

@@ -2,13 +2,13 @@
## Default parameters
The TFHE cryptographic scheme relies on a variant of [Regev cryptosystem](https://cims.nyu.edu/\~regev/papers/lwesurvey.pdf), and is based on a problem so hard to solve that it is even post-quantum resistant.
The TFHE cryptographic scheme relies on a variant of [Regev cryptosystem](https://cims.nyu.edu/\~regev/papers/lwesurvey.pdf) and is based on a problem so difficult that it is even post-quantum resistant.
In practice, you need to tune some cryptographic parameters in order to ensure both the correctness of the result and the security of the computation.
Some cryptographic parameters will require tuning to ensure both the correctness of the result and the security of the computation.
To make it simpler, **we provide two sets of parameters**, which ensure correct computations for a certain probability with the standard security of 128 bits. There exists an error probability due to the probabilistic nature of the encryption, which requires adding randomness (called noise) following a Gaussian distribution. If this noise is too large, the decryption will not give a correct result. There is a trade-off between efficiency and correctness: generally, using a less efficient parameter set (in terms of computation time) leads to a smaller risk of having an error during homomorphic evaluation.
To make it simpler, **we've provided two sets of parameters**, which ensure correct computations for a certain probability with the standard security of 128 bits. There exists an error probability due to the probabilistic nature of the encryption, which requires adding randomness (noise) following a Gaussian distribution. If this noise is too large, the decryption will not give a correct result. There is a trade-off between efficiency and correctness: generally, using a less efficient parameter set (in terms of computation time) leads to a smaller risk of having an error during homomorphic evaluation.
In the two proposed sets of parameters, the only difference lies in this probability error. The default parameter set ensures a probability error of at most $$2^{-40}$$ when computing a programmable bootstrapping (i.e., any gates but the `not`). The other one is closer to the error probability claimed into the original [TFHE paper](https://eprint.iacr.org/2018/421), namely $$2^{-165}$$, but it is up-to-date regarding security requirements.
In the two proposed sets of parameters, the only difference lies in this probability error. The default parameter set ensures a probability error of at most $$2^{-40}$$ when computing a programmable bootstrapping (i.e., any gates but the `not`). The other one is closer to the error probability claimed in the original [TFHE paper](https://eprint.iacr.org/2018/421), namely $$2^{-165}$$, but it is up-to-date regarding security requirements.
The following array summarizes this:
@@ -19,7 +19,7 @@ The following array summarizes this:
## User-defined parameters
Note that, if you desire, you can also create your own set of parameters. This is an `unsafe` operation as failing to properly fix the parameters will potentially result in an incorrect and/or insecure computation:
You can also create your own set of parameters. This is an `unsafe` operation as failing to properly fix the parameters will result in an incorrect and/or insecure computation:
```rust
use tfhe::boolean::prelude::*;

View File

@@ -1,19 +1,19 @@
# Tutorial
This library is meant to be used both on the **server side** and on the **client side**. The typical use case should follow the subsequent steps:
This library is meant to be used both on the **server side** and the **client side**. The typical use case should follow the subsequent steps:
1. On the **client side**, generate the `client` and `server keys`.
2. Send the `server key` to the **server**.
3. Then any number of times:
* On the **client side**, _encryption_ of the input data with the `client key`.
* On the **client side**, _encrypt_ the input data with the `client key`.
* Transmit the encrypted input to the **server**.
* On the **server side**, _homomorphic computation_ with the `server key`.
* On the **server side**, perform _homomorphic computation_ with the `server key`.
* Transmit the encrypted output to the **client**.
* On the **client side**, _decryption_ of the output data with the `client key`.
* On the **client side**, _decrypt_ the output data with the `client key`.
## Setup
In the first step, the client creates two keys: the `client key` and the `server key`, with the `concrete_boolean::gen_keys` function:
In the first step, the client creates two keys, the `client key` and the `server key`, with the `concrete_boolean::gen_keys` function:
```rust
use tfhe::boolean::prelude::*;
@@ -26,10 +26,10 @@ fn main() {
}
```
* The `client_key` is of type `ClientKey`. It is **secret**, and must **never** be transmitted. This key will only be used to encrypt and decrypt data.
* The `server_key` is of type `ServerKey`. It is a **public key**, and can be shared with any party. This key has to be sent to the server because it is required for homomorphic computation.
* The `client_key` is of type `ClientKey`. It is **secret** and must **never** be transmitted. This key will only be used to encrypt and decrypt data.
* The `server_key` is of type `ServerKey`. It is a **public key** and can be shared with any party. This key has to be sent to the server because it is required for homomorphic computation.
Note that both the `client_key` and `server_key` implement the `Serialize` and `Deserialize` traits. This way you can use any compatible serializer to store/send the data. For instance, to store the `server_key` in a binary file, you can use the `bincode` library:
Note that both the `client_key` and `server_key` implement the `Serialize` and `Deserialize` traits. This way you can use any compatible serializer to store/send the data. To store the `server_key` in a binary file, you can use the `bincode` library:
```rust
use std::fs::File;
@@ -72,9 +72,9 @@ fn main() {
}
```
## Encrypting Inputs
## Encrypting inputs
Once the server key is available on the **server side**, it is possible to perform some homomorphic computations. The client simply needs to encrypt some data and send it to the server. Again, the `Ciphertext` type implements the `Serialize` and the `Deserialize` traits, so that any serializer and communication tool suiting your use case can be employed:
Once the server key is available on the **server side**, it is possible to perform some homomorphic computations. The client needs to encrypt some data and send it to the server. Again, the `Ciphertext` type implements the `Serialize` and the `Deserialize` traits, so that any serializer and communication tool suiting your use case can be employed:
```rust
use tfhe::boolean::prelude::*;
@@ -99,7 +99,7 @@ fn main() {
}
```
## Encrypting Inputs using a public key
## Encrypting inputs using a public key
Once the server key is available on the **server side**, it is possible to perform some homomorphic computations. The client simply needs to encrypt some data and send it to the server. Again, the `Ciphertext` type implements the `Serialize` and the `Deserialize` traits, so that any serializer and communication tool suiting your use case can be utilized:

View File

@@ -1,12 +1,12 @@
# What is TFHE-rs?
<mark style="background-color:yellow;">⭐️</mark> [<mark style="background-color:yellow;">Star the repo on Github</mark>](https://github.com/zama-ai/tfhe-rs) <mark style="background-color:yellow;">| 🗣</mark> [<mark style="background-color:yellow;">Community support forum</mark> ](https://community.zama.ai)<mark style="background-color:yellow;">| 📁</mark> [<mark style="background-color:yellow;">Contribute to the project</mark>](https://docs.zama.ai/tfhe-rs/developers/contributing)
📁 [Github](https://github.com/zama-ai/tfhe-rs) | 💛 [Community support](https://zama.ai/community) | 🟨 [Zama Bounty Program](https://github.com/zama-ai/bounty-program)
![](\_static/tfhe-rs-doc-home.png)
TFHE-rs is a pure Rust implementation of TFHE for boolean and small integer arithmetics over encrypted data. It includes a Rust and C API, as well as a client-side WASM API.
TFHE-rs is a pure Rust implementation of TFHE for Boolean and integer arithmetics over encrypted data. It includes a Rust and C API, as well as a client-side WASM API.
TFHE-rs is meant for developers and researchers who want full control over what they can do with TFHE, while not having to worry about the low level implementation.
TFHE-rs is meant for developers and researchers who want full control over what they can do with TFHE, while not worrying about the low level implementation.
The goal is to have a stable, simple, high-performance, and production-ready library for all the advanced features of TFHE.

View File

@@ -10,6 +10,11 @@
* [Benchmarks](getting\_started/benchmarks.md)
* [Security and Cryptography](getting\_started/security\_and\_cryptography.md)
## High Level API
* [Tutorial](high_level_api/tutorial.md)
* [Operations](high_level_api/operations.md)
* [Serialization/Deserialization](high_level_api/serialization.md)
## Boolean
* [Tutorial](Boolean/tutorial.md)
* [Operations](Boolean/operations.md)
@@ -23,10 +28,14 @@
* [Serialization/Deserialization](shortint/serialization.md)
## Integer
* [Summary](integer/SUMMARY.md)
* [Tutorial](integer/tutorial.md)
* [Operations](integer/operations.md)
* [Cryptographic Parameters](integer/parameters.md)
* [Serialization/Deserialization](integer/serialization.md)
## C API
* [Tutorial](c_api/tutorial.md)
* [High-Level API](c_api/high-level-api.md)
* [Shortint API](c_api/shortint-api.md)
## JS on WASM API
* [Tutorial](js_on_wasm_api/tutorial.md)

BIN
tfhe/docs/_static/integer-ciphertext.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 45 KiB

View File

@@ -0,0 +1,143 @@
# High-Level API
\#Using the High-level C API
This library exposes a C binding to the high-level TFHE-rs primitives to implement _Fully Homomorphic Encryption_ (FHE) programs.
## First steps using TFHE-rs C API
### Setting-up TFHE-rs C API for use in a C program.
TFHE-rs C API can be built on a Unix x86\_64 machine using the following command:
```shell
RUSTFLAGS="-C target-cpu=native" cargo +nightly build --release --features=x86_64-unix,high-level-c-api -p tfhe
```
or on a Unix aarch64 machine using the following command:
```shell
RUSTFLAGS="-C target-cpu=native" cargo build +nightly --release --features=aarch64-unix,high-level-c-api -p tfhe
```
The `tfhe.h` header as well as the static (.a) and dynamic (.so) `libtfhe` binaries can then be found in "${REPO\_ROOT}/target/release/"
The build system needs to be set up so that the C or C++ program links against TFHE-rs C API binaries.
Here is a minimal CMakeLists.txt to do just that:
```cmake
project(my-project)
cmake_minimum_required(VERSION 3.16)
set(TFHE_C_API "/path/to/tfhe-rs/binaries/and/header")
include_directories(${TFHE_C_API})
add_library(tfhe STATIC IMPORTED)
set_target_properties(tfhe PROPERTIES IMPORTED_LOCATION ${TFHE_C_API}/libtfhe.a)
if(APPLE)
find_library(SECURITY_FRAMEWORK Security)
if (NOT SECURITY_FRAMEWORK)
message(FATAL_ERROR "Security framework not found")
endif()
endif()
set(EXECUTABLE_NAME my-executable)
add_executable(${EXECUTABLE_NAME} main.c)
target_include_directories(${EXECUTABLE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(${EXECUTABLE_NAME} LINK_PUBLIC tfhe m pthread dl)
if(APPLE)
target_link_libraries(${EXECUTABLE_NAME} LINK_PUBLIC ${SECURITY_FRAMEWORK})
endif()
target_compile_options(${EXECUTABLE_NAME} PRIVATE -Werror)
```
### Commented code of a uint128 subtraction using `TFHE-rs C API`.
{% hint style="warning" %}
WARNING: The following example does not have proper memory management in the error case to make it easier to fit the code on this page.
{% endhint %}
To run the example below, the above CMakeLists.txt and main.c files need to be in the same directory. The commands to run are:
```shell
# /!\ Be sure to update CMakeLists.txt to give the absolute path to the compiled tfhe library
$ ls
CMakeLists.txt main.c
$ mkdir build && cd build
$ cmake .. -DCMAKE_BUILD_TYPE=RELEASE
...
$ make
...
$ ./my-executable
Result: 2
$
```
```c
#include <tfhe.h>
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
int main(void)
{
int ok = 0;
// Prepare the config builder for the high level API and choose which types to enable
ConfigBuilder *builder;
Config *config;
// Put the builder in a default state without any types enabled
config_builder_all_disabled(&builder);
// Enable the uint128 type using the small LWE key for encryption
config_builder_enable_default_uint128_small(&builder);
// Populate the config
config_builder_build(builder, &config);
ClientKey *client_key = NULL;
ServerKey *server_key = NULL;
// Generate the keys using the config
generate_keys(config, &client_key, &server_key);
// Set the server key for the current thread
set_server_key(server_key);
FheUint128 *lhs = NULL;
FheUint128 *rhs = NULL;
FheUint128 *result = NULL;
// Encrypt a u128 using 64 bits words, we encrypt 20 << 64 | 10
ok = fhe_uint128_try_encrypt_with_client_key_u128(10, 20, client_key, &lhs);
assert(ok == 0);
// Encrypt a u128 using words, we encrypt 2 << 64 | 1
ok = fhe_uint128_try_encrypt_with_client_key_u128(1, 2, client_key, &rhs);
assert(ok == 0);
// Compute the subtraction
ok = fhe_uint128_sub(lhs, rhs, &result);
assert(ok == 0);
uint64_t w0, w1;
// Decrypt
ok = fhe_uint128_decrypt(result, client_key, &w0, &w1);
assert(ok == 0);
// Here the subtraction allows us to compare each word
assert(w0 == 9);
assert(w1 == 18);
// Destroy the ciphertexts
fhe_uint128_destroy(lhs);
fhe_uint128_destroy(rhs);
fhe_uint128_destroy(result);
// Destroy the keys
client_key_destroy(client_key);
server_key_destroy(server_key);
return EXIT_SUCCESS;
}
```

View File

@@ -1,34 +1,32 @@
# Tutorial
# Shortint API
## Using the C API
## Using the shortint C API
Welcome to this TFHE-rs C API tutorial!
This library exposes a C binding to the TFHE-rs primitives to implement _Fully Homomorphic Encryption_ (FHE) programs.
This library exposes a C binding to the TFHE-rs shortint API to implement _Fully Homomorphic Encryption_ (FHE) programs.
## First steps using TFHE-rs C API
### Setting-up TFHE-rs C API for use in a C program.
### Setting up TFHE-rs C API for use in a C program.
TFHE-rs C API can be built on a Unix x86\_64 machine using the following command:
```shell
RUSTFLAGS="-C target-cpu=native" cargo build --release --features=x86_64-unix,boolean-c-api,shortint-c-api -p tfhe
RUSTFLAGS="-C target-cpu=native" cargo +nightly build --release --features=x86_64-unix,boolean-c-api,shortint-c-api -p tfhe
```
or on a Unix aarch64 machine using the following command
or on a Unix aarch64 machine using the following command:
```shell
RUSTFLAGS="-C target-cpu=native" cargo build --release --features=aarch64-unix,boolean-c-api,shortint-c-api -p tfhe
RUSTFLAGS="-C target-cpu=native" cargo build +nightly --release --features=aarch64-unix,boolean-c-api,shortint-c-api -p tfhe
```
All features are opt-in, but for simplicity here, the C API is enabled for boolean and shortint.
All features are opt-in, but for simplicity here, the C API is enabled for Boolean and shortint.
The `tfhe.h` header as well as the static (.a) and dynamic (.so) `libtfhe` binaries can then be found in "${REPO\_ROOT}/target/release/"
The build system needs to be set up so that the C or C++ program links against TFHE-rs C API binaries.
Here is a minimal CMakeLists.txt allowing to do just that:
Here is a minimal CMakeLists.txt to do just that:
```cmake
project(my-project)
@@ -58,9 +56,9 @@ endif()
target_compile_options(${EXECUTABLE_NAME} PRIVATE -Werror)
```
### Commented code of a PBS doubling a 2 bits encrypted message using `TFHE-rs C API`.
### Commented code of a PBS doubling a 2-bits encrypted message using `TFHE-rs C API`.
The steps required to perform the multiplication by 2 of a 2 bits ciphertext using a PBS are detailed. This is NOT the most efficient way of doing this operation, but it can help to show the management required to run a PBS manually using the C API.
The steps required to perform the multiplication by 2 of a 2-bits ciphertext using a PBS are detailed. This is NOT the most efficient way of doing this operation, but it can help to show the management required to run a PBS manually using the C API.
WARNING: The following example does not have proper memory management in the error case to make it easier to fit the code on this page.
@@ -103,7 +101,7 @@ uint64_t get_max_value_of_accumulator_generator(uint64_t (*accumulator_func)(uin
int main(void)
{
ShortintPBSAccumulator *accumulator = NULL;
ShortintPBSLookupTable *accumulator = NULL;
ShortintClientKey *cks = NULL;
ShortintServerKey *sks = NULL;
ShortintParameters *params = NULL;
@@ -172,7 +170,3 @@ int main(void)
return EXIT_SUCCESS;
}
```
## Audience
Programmers wishing to use TFHE-rs but who are unable to use Rust (for various reasons) can use these bindings in their language of choice, as long as it can interface with C code to bring TFHE-rs functionalities to said language.

View File

@@ -1,15 +1,15 @@
# Overview of the `core_crypto` Module
# Quick Start
The `core_crypto` module from TFHE-rs is dedicated to the implementation of the cryptographic tools related to TFHE. To construct an FHE application, the [shortint](../shortint/tutorial.md) and/or [Boolean](../Boolean/tutorial.md) modules (based on this one) are recommended.
The `core_crypto` module offers an API to low-level cryptographic primitives and objects, like `lwe_encryption` or `rlwe_ciphertext`. Its goal is to propose an easy-to-use API for cryptographers.
The overall code architecture is split in two parts: one for the entity definitions, and another one focused on the algorithms. For instance, the entities contain the definition of useful types, like LWE ciphertext or bootstrapping keys. The algorithms are then naturally defined to work using these entities.
The API is convenient to easily add or modify existing algorithms or to have direct access to the raw data. For instance, even if the LWE ciphertext object is defined along with functions giving access to he body, this is also possible to bypass these to get directly the $$i^{th}$$ element of LWE mask.
The overall code architecture is split in two parts: one for entity definitions and another focused on algorithms. The entities contain the definition of useful types, like LWE ciphertext or bootstrapping keys. The algorithms are then naturally defined to work using these entities.
The API is convenient to easily add or modify existing algorithms or to have direct access to the raw data. Even if the LWE ciphertext object is defined along with functions giving access to the body, this is also possible to bypass these to get directly the $$i^{th}$$ element of LWE mask.
For instance, the code to encrypt and then decrypt a message looks like:
```rust
use tfhe::core_crypto::prelude::*;
@@ -18,6 +18,7 @@ use tfhe::core_crypto::prelude::*;
// Define parameters for LweCiphertext creation
let lwe_dimension = LweDimension(742);
let lwe_modular_std_dev = StandardDev(0.000007069849454709433);
let ciphertext_modulus = CiphertextModulus::new_native();
// Create the PRNG
let mut seeder = new_seeder();
@@ -36,7 +37,7 @@ let msg = 3u64;
let plaintext = Plaintext(msg << 60);
// Create a new LweCiphertext
let mut lwe = LweCiphertext::new(0u64, lwe_dimension.to_lwe_size());
let mut lwe = LweCiphertext::new(0u64, lwe_dimension.to_lwe_size(), ciphertext_modulus);
encrypt_lwe_ciphertext(
&lwe_secret_key,
@@ -59,4 +60,3 @@ let cleartext = rounded >> 60;
// Check we recovered the original message
assert_eq!(cleartext, msg);
```

View File

@@ -2,42 +2,41 @@
## Using the `core_crypto` primitives
Welcome to this tutorial about TFHE-rs `core_crypto` module!
Welcome to this tutorial about TFHE-rs `core_crypto` module.
### Setting-up TFHE-rs to use the `core_crypto` module
### Setting up TFHE-rs to use the `core_crypto` module
To use `TFHE-rs`, first it has to be added as a dependency in the `Cargo.toml`:
```toml
tfhe = { version = "0.2.0", features = [ "x86_64-unix" ] }
tfhe = { version = "0.2.4", features = [ "x86_64-unix" ] }
```
Here, this enables the `x86_64-unix` feature to have efficient implementations of various algorithms for `x86_64` CPUs on a Unix-like system. The 'unix' suffix indicates that the `UnixSeeder`, which uses `/dev/random` to generate random numbers, is actived as a fallback if no hardware number generator is available, like `rdseed` on `x86_64` or if the [`Randomization Services`](https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc) on Apple platforms are not available. To avoid having the `UnixSeeder` as a potential fallback or to run on non-Unix systems (e.g., Windows), the `x86_64` feature is sufficient.
This enables the `x86_64-unix` feature to have efficient implementations of various algorithms for `x86_64` CPUs on a Unix-like system. The 'unix' suffix indicates that the `UnixSeeder`, which uses `/dev/random` to generate random numbers, is activated as a fallback if no hardware number generator is available, like `rdseed` on `x86_64` or if the [`Randomization Services`](https://developer.apple.com/documentation/security/1399291-secrandomcopybytes?language=objc) on Apple platforms are not available. To avoid having the `UnixSeeder` as a potential fallback or to run on non-Unix systems (e.g., Windows), the `x86_64` feature is sufficient.
For Apple Silicon, the `aarch64-unix` or `aarch64` feature should be enabled. Note that `aarch64` is not supported on Windows as it's currently missing an entropy source required to seed the [CSPRNGs](https://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator) used in TFHE-rs.
For Apple Silicon, the `aarch64-unix` or `aarch64` feature should be enabled. `aarch64` is not supported on Windows as it's currently missing an entropy source required to seed the [CSPRNGs](https://en.wikipedia.org/wiki/Cryptographically\_secure\_pseudorandom\_number\_generator) used in TFHE-rs.
In short:
For x86_64-based machines running Unix-like OSes:
In short: For x86\_64-based machines running Unix-like OSes:
```toml
tfhe = { version = "0.2.0", features = ["x86_64-unix"] }
tfhe = { version = "0.2.4", features = ["x86_64-unix"] }
```
For Apple Silicon or aarch64-based machines running Unix-like OSes:
```toml
tfhe = { version = "0.2.0", features = ["aarch64-unix"] }
tfhe = { version = "0.2.4", features = ["aarch64-unix"] }
```
For x86_64-based machines with the [`rdseed instruction`](https://en.wikipedia.org/wiki/RDRAND) running Windows:
For x86\_64-based machines with the [`rdseed instruction`](https://en.wikipedia.org/wiki/RDRAND) running Windows:
```toml
tfhe = { version = "0.2.0", features = ["x86_64"] }
tfhe = { version = "0.2.4", features = ["x86_64"] }
```
### Commented code to double a 2 bits message in a leveled fashion and using a PBS with the `core_crypto` module.
### Commented code to double a 2-bits message in a leveled fashion and using a PBS with the `core_crypto` module.
As a complete example showing the usage of some common primitives of the `core_crypto` APIs, the following Rust code homomorphically computes 2 * 3 using two different methods. First using a cleartext multiplication and second using a PBS.
As a complete example showing the usage of some common primitives of the `core_crypto` APIs, the following Rust code homomorphically computes 2 \* 3 using two different methods. First using a cleartext multiplication and then using a PBS.
```rust
use tfhe::core_crypto::prelude::*;
@@ -53,6 +52,7 @@ pub fn main() {
let glwe_modular_std_dev = StandardDev(0.00000000000000029403601535432533);
let pbs_base_log = DecompositionBaseLog(23);
let pbs_level = DecompositionLevelCount(1);
let ciphertext_modulus = CiphertextModulus::new_native();
// Request the best seeder possible, starting with hardware entropy sources and falling back to
// /dev/random on Unix systems if enabled via cargo features
@@ -89,6 +89,7 @@ pub fn main() {
pbs_base_log,
pbs_level,
glwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
@@ -124,6 +125,7 @@ pub fn main() {
&small_lwe_sk,
plaintext,
lwe_modular_std_dev,
ciphertext_modulus,
&mut encryption_generator,
);
@@ -167,6 +169,7 @@ pub fn main() {
polynomial_size: PolynomialSize,
glwe_size: GlweSize,
message_modulus: usize,
ciphertext_modulus: CiphertextModulus<u64>,
delta: u64,
f: F,
) -> GlweCiphertextOwned<u64>
@@ -202,7 +205,11 @@ pub fn main() {
let accumulator_plaintext = PlaintextList::from_container(accumulator_u64);
let accumulator =
allocate_and_trivially_encrypt_new_glwe_ciphertext(glwe_size, &accumulator_plaintext);
allocate_and_trivially_encrypt_new_glwe_ciphertext(
glwe_size,
&accumulator_plaintext,
ciphertext_modulus,
);
accumulator
}
@@ -212,13 +219,17 @@ pub fn main() {
polynomial_size,
glwe_dimension.to_glwe_size(),
message_modulus as usize,
ciphertext_modulus,
delta,
|x: u64| 2 * x,
);
// Allocate the LweCiphertext to store the result of the PBS
let mut pbs_multiplication_ct =
LweCiphertext::new(0u64, big_lwe_sk.lwe_dimension().to_lwe_size());
let mut pbs_multiplication_ct = LweCiphertext::new(
0u64,
big_lwe_sk.lwe_dimension().to_lwe_size(),
ciphertext_modulus,
);
println!("Computing PBS...");
programmable_bootstrap_lwe_ciphertext(
&lwe_ciphertext_in,

View File

@@ -1,6 +1,6 @@
# Contributing
There are two ways to contribute to **TFHE-rs**:
There are two ways to contribute to **TFHE-rs**. You can:
* you can open issues to report bugs and typos and to suggest ideas
* you can ask to become an official contributor by emailing hello@zama.ai. Only approved contributors can end pull requests, so please make sure to get in touch before you do!
* open issues to report bugs and typos and to suggest ideas;
* ask to become an official contributor by emailing hello@zama.ai. Only approved contributors can send pull requests, so get in touch before you do.

View File

@@ -1,16 +1,16 @@
# Benchmarks
Due to their nature, homomorphic operations are obviously slower than their clear equivalent. In what follows, some timings are exposed for basic operations. For completeness, some benchmarks of other libraries are also given.
Due to their nature, homomorphic operations are naturally slower than their clear equivalent. Some timings are exposed for basic operations. For completeness, benchmarks for other libraries are also given.
All the benchmarks had been launched on an AWS m6i.metal with the following specifications: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz and 512GB of RAM.
All benchmarks were launched on an AWS m6i.metal with the following specifications: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz and 512GB of RAM.
## Boolean
This measures the execution time of a single binary boolean gate.
This measures the execution time of a single binary Boolean gate.
### tfhe.rs::boolean.
### tfhe-rs::boolean.
| Parameter set | concrete-fft | concrete-fft + avx512 |
| Parameter set | Concrete FFT | Concrete FFT + avx512 |
| --------------------- | ------------ | --------------------- |
| DEFAULT\_PARAMETERS | 8.8ms | 6.8ms |
| TFHE\_LIB\_PARAMETERS | 13.6ms | 10.9ms |
@@ -28,17 +28,41 @@ This measures the execution time of a single binary boolean gate.
| STD\_128 | 172ms | 78ms |
| MEDIUM | 113ms | 50.2ms |
## Shortint
This measures the execution time for some operations and some parameter sets of tfhe-rs::shortint.
This measures the execution time for some operations and some parameter sets of shortint.
### tfhe.rs::shortint.
This uses the concrete-fft + avx512 configuration.
This uses the Concrete FFT + avx512 configuration.
| Parameter set | unchecked\_add | unchecked\_mul\_lsb | keyswitch\_programmable\_bootstrap |
| --------------------------- | -------------- | ------------------- | ---------------------------------- |
| PARAM\_MESSAGE\_1\_CARRY\_1 | 338 ns | 8.3 ms | 8.1 ms |
| PARAM\_MESSAGE\_2\_CARRY\_2 | 406 ns | 18.4 ms | 18.4 ms |
| PARAM\_MESSAGE\_3\_CARRY\_3 | 3.06 µs | 134 ms | 134 ms |
| PARAM\_MESSAGE\_4\_CARRY\_4 | 11.7 µs | 854 ms | 945 ms |
| PARAM\_MESSAGE\_3\_CARRY\_3 | 3.06 µs | 134 ms | 129.4 ms |
| PARAM\_MESSAGE\_4\_CARRY\_4 | 11.7 µs | 854 ms | 828.1 ms |
Next, the timings for the operation flavor `default` are given. This flavor ensures predictable timings of an operation all along the circuit by clearing the carry space after each operation.
| Parameter set | add | mul\_lsb | keyswitch\_programmable\_bootstrap |
| --------------------------- | -------------- | ------------------- | ---------------------------------- |
| PARAM\_MESSAGE\_1\_CARRY\_1 | 7.90 ms | 8.00 ms | 8.10 ms |
| PARAM\_MESSAGE\_2\_CARRY\_2 | 18.4 ms | 18.1 ms | 18.4 ms |
| PARAM\_MESSAGE\_3\_CARRY\_3 | 131.5 ms | 129.5 ms | 129.4 ms |
| PARAM\_MESSAGE\_4\_CARRY\_4 | 852.5 ms | 839.7 ms | 828.1 ms |
## Integer
This measures the execution time for some operation sets of tfhe-rs::integer.
All timings are related to parallelized Radix-based integer operations, where each block is encrypted using PARAM\_MESSAGE\_2\_CARRY\_2.
To ensure predictable timings, the operation flavor is the `default` one: a carry propagation is computed after each operation. Operation cost could be reduced by using `unchecked`, `checked`, or `smart`.
| Plaintext size | add | mul | greater\_than (gt) | min |
| -------------------| -------------- | ------------------- | --------- | ------- |
| 8 bits | 129.0 ms | 227.2 ms | 111.9 ms | 186.8 ms |
| 16 bits | 256.3 ms | 756.0 ms | 145.3 ms | 233.1 ms |
| 32 bits | 469.4 ms | 2.10 s | 192.0 ms | 282.9 ms |
| 40 bits | 608.0 ms | 3.37 s | 228.4 ms | 318.6 ms |
| 64 bits | 959.9 ms | 5.53 s | 249.0 ms | 336.5 ms |
| 128 bits | 1.88 s | 14.1 s | 294.7 ms | 398.6 ms |
| 256 bits | 3.66 s | 29.2 s | 361.8 ms | 509.1 ms |

View File

@@ -5,9 +5,13 @@
To use `TFHE-rs` in your project, you first need to add it as a dependency in your `Cargo.toml`:
```toml
tfhe = { version = "0.2.0", features = [ "boolean", "shortint", "x86_64-unix" ] }
tfhe = { version = "0.2.4", features = [ "boolean", "shortint", "integer", "x86_64-unix" ] }
```
{% hint style="info" %}
When running code that uses `tfhe-rs`, it is highly recommended to run in release mode with cargo's `--release` flag to have the best performances possible, eg: `cargo run --release`.
{% endhint %}
## Choosing your features
`TFHE-rs` exposes different `cargo features` to customize the types and features used.
@@ -16,16 +20,17 @@ tfhe = { version = "0.2.0", features = [ "boolean", "shortint", "x86_64-unix" ]
This crate exposes two kinds of data types. Each kind is enabled by activating its corresponding feature in the TOML line. Each kind may have multiple types:
| Kind | Features | Type(s) |
| --------- | ---------- | ----------------------- |
| Booleans | `boolean` | Booleans |
| ShortInts | `shortint` | Short unsigned integers |
| Kind | Features | Type(s) |
| --------- | ---------- | --------------------------------- |
| Booleans | `boolean` | Booleans |
| ShortInts | `shortint` | Short unsigned integers |
| Integers | `integer` | Arbitrary-sized unsigned integers |
### Serialization.
The different data types and keys exposed by the crate can be serialized / deserialized.
More information can be found [here](../Boolean/serialization.md) for boolean and [here](../shortint/serialization.md) for shortint.
More information can be found [here](../Boolean/serialization.md) for Boolean and [here](../shortint/serialization.md) for shortint.
## Supported platforms
@@ -43,7 +48,7 @@ Users who have ARM devices can use `TFHE-rs` by compiling using the `nightly` to
### Using TFHE-rs with nightly toolchain.
First, install the needed Rust toolchain:
Install the needed Rust toolchain:
```shell
rustup toolchain install nightly
@@ -53,8 +58,6 @@ Then, you can either:
* Manually specify the toolchain to use in each of the cargo commands:
For example:
```shell
cargo +nightly build
cargo +nightly test

View File

@@ -16,7 +16,7 @@ The list of supported operations by the homomorphic Booleans is:
A walk-through using homomorphic Booleans can be found [here](../Boolean/tutorial.md).
## ShortInt
## Shortint
In TFHE-rs, shortint represents short unsigned integers encoded over a maximum of 8 bits. A complete homomorphic arithmetic is provided, along with the possibility to compute univariate and bi-variate functions. Some operations are only available for integers up to 4 bits. More technical details can be found [here](../shortint/operations.md).
@@ -38,7 +38,27 @@ The list of supported operations is:
| Exact Function Evaluation | Unary/Binary |
{% hint style="info" %}
\* The division operation implements a subtlety: since data is encrypted, it might be possible to compute a division by 0. In this case, the division is tweaked so that dividing by 0 returns 0.
The division operation implements a subtlety: since data is encrypted, it might be possible to compute a division by 0. The division is tweaked so that dividing by 0 returns 0.
{% endhint %}
A walk-through example can be found [here](../shortint/tutorial.md), and more examples and explanations can be found [here](../shortint/operations.md).[ ](../shortint/operations.md)
A walk-through example can be found [here](../shortint/tutorial.md), and more examples and explanations can be found [here](../shortint/operations.md).
## Integer
In TFHE-rs, integers represent unsigned integers up to 256 bits. They are encoded using Radix representations by default (more details [here](../integer/operations.md)).
The list of supported operations is:
| Operation name | Type |
| ------------------------------ | ------ |
| Negation | Unary |
| Addition | Binary |
| Subtraction | Binary |
| Multiplication | Binary |
| Bitwise OR, AND, XOR | Binary |
| Equality | Binary |
| Left/Right Shift | Binary |
| Comparisons `<`,`<=`,`>`, `>=` | Binary |
| Min, Max | Binary |
A walk-through example can be found [here](../integer/tutorial.md).

View File

@@ -1,58 +1,116 @@
# Quick Start
This library makes it possible to execute **homomorphic operations over encrypted data**, where the data are either Booleans or short integers (named shortint in the rest of this documentation). It allows one to execute a circuit on an **untrusted server** because both circuit inputs and outputs are kept **private**. Data are indeed encrypted on the client side, before being sent to the server. On the server side, every computation is performed on ciphertexts.
This library makes it possible to execute **homomorphic operations over encrypted data**, where the data are either Booleans, short integers (named shortint in the rest of this documentation), or integers up to 256 bits. It allows you to execute a circuit on an **untrusted server** because both circuit inputs and outputs are kept **private**. Data are indeed encrypted on the client side, before being sent to the server. On the server side, every computation is performed on ciphertexts.
The server, however, has to know the circuit to be evaluated. At the end of the computation, the server returns the encryption of the result to the user. She can then decrypt it with her `secret key`.
The server, however, has to know the circuit to be evaluated. At the end of the computation, the server returns the encryption of the result to the user. Then the user can decrypt it with the `secret key`.
## General method to write an homomorphic circuit program
The overall process to write an homomorphic program is the same for both Boolean and shortint types. In a nutshell, the basic steps for using the TFHE-rs library are the following:
The overall process to write an homomorphic program is the same for all types. The basic steps for using the TFHE-rs library are the following:
* Choose a data type (Boolean or shortint)
* Import the library
* Create client and server keys
* Encrypt data with the client key
* Compute over encrypted data using the server key
* Decrypt data with the client key
1. Choose a data type (Boolean, shortint, integer)
2. Import the library
3. Create client and server keys
4. Encrypt data with the client key
5. Compute over encrypted data using the server key
6. Decrypt data with the client key
### Boolean example.
### API levels.
Here is an example to illustrate how the library can be used to evaluate a Boolean circuit:
This library has different modules, with different levels of abstraction.
There is the **core\_crypto** module, which is the lowest level API with the primitive functions and types of the TFHE scheme.
Above the core\_crypto module, there are the B**oolean**, **shortint**, and **integer** modules, which simply allow evaluation of Boolean, short integer, and integer circuits.
Finally, there is the high-level module built on top of the Boolean, shortint, integer modules. This module is meant to abstract cryptographic complexities: no cryptographical knowledge is required to start developing an FHE application. Another benefit of the high-level module is the drastically simplified development process compared to lower level modules.
#### high-level API
TFHE-rs exposes a high-level API by default that includes datatypes that try to match Rust's native types by having overloaded operators (+, -, ...).
Here is an example of how the high-level API is used:
{% hint style="warning" %}
Use the `--release` flag to run this example (eg: `cargo run --release`)
{% endhint %}
```rust
use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8};
use tfhe::prelude::*;
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_uint8()
.build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
let clear_a = 27u8;
let clear_b = 128u8;
let a = FheUint8::encrypt(clear_a, &client_key);
let b = FheUint8::encrypt(clear_b, &client_key);
let result = a + b;
let decrypted_result: u8 = result.decrypt(&client_key);
let clear_result = clear_a + clear_b;
assert_eq!(decrypted_result, clear_result);
}
```
#### Boolean example
Here is an example of how the library can be used to evaluate a Boolean circuit:
{% hint style="warning" %}
Use the `--release` flag to run this example (eg: `cargo run --release`)
{% endhint %}
```rust
use tfhe::boolean::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys();
// We use the client secret key to encrypt two messages:
// We use the client secret key to encrypt two messages:
let ct_1 = client_key.encrypt(true);
let ct_2 = client_key.encrypt(false);
// We use the server public key to execute a boolean circuit:
// if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
// We use the server public key to execute a boolean circuit:
// if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
let ct_3 = server_key.not(&ct_2);
let ct_4 = server_key.and(&ct_1, &ct_2);
let ct_5 = server_key.nand(&ct_3, &ct_4);
let ct_6 = server_key.mux(&ct_5, &ct_3, &ct_4);
// We use the client key to decrypt the output of the circuit:
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_6);
assert_eq!(output, true);
}
```
### Shortint example.
#### shortint example
And here is a full example using shortint:
Here is a full example using shortint:
{% hint style="warning" %}
Use the `--release` flag to run this example (eg: `cargo run --release`)
{% endhint %}
```rust
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(Parameters::default());
// We generate a set of client/server keys
// using parameters with 2 bits of message and 2 bits of carry
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 1;
let msg2 = 0;
@@ -72,4 +130,32 @@ fn main() {
}
```
The library is pretty simple to use, and can evaluate **homomorphic circuits of arbitrary length**. The description of the algorithms can be found in the [TFHE](https://doi.org/10.1007/s00145-019-09319-x) paper (also available as [ePrint 2018/421](https://ia.cr/2018/421)).
#### integer example
{% hint style="warning" %}
Use the `--release` flag to run this example (eg: `cargo run --release`)
{% endhint %}
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We create keys for radix represention to create 16 bits integers
// using 8 blocks of 2 bits
let (cks, sks) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, 8);
let clear_a = 2382u16;
let clear_b = 29374u16;
let mut a = cks.encrypt(clear_a as u64);
let mut b = cks.encrypt(clear_b as u64);
let encrypted_max = sks.smart_max_parallelized(&mut a, &mut b);
let decrypted_max: u64 = cks.decrypt(&encrypted_max);
assert_eq!(decrypted_max as u16, clear_a.max(clear_b))
}
```
The library is simple to use and can evaluate **homomorphic circuits of arbitrary length**. The description of the algorithms can be found in the [TFHE](https://doi.org/10.1007/s00145-019-09319-x) paper (also available as [ePrint 2018/421](https://ia.cr/2018/421)).

View File

@@ -4,7 +4,7 @@
TFHE-rs is a cryptographic library dedicated to Fully Homomorphic Encryption. As its name suggests, it is based on the TFHE scheme.
It is interesting to understand some basics about TFHE in order to comprehend where the limitations are coming from, both in terms of precision (number of bits used to represent the plaintext values) and execution time (why TFHE operations are slower than native operations).
It is necessary to understand some basics about TFHE to comprehend where the limitations are coming from, both in terms of precision (number of bits used to represent plaintext values) and execution time (why TFHE operations are slower than native operations).
## LWE ciphertexts
@@ -24,7 +24,7 @@ To go from a **plaintext** to a **ciphertext,** one must encrypt the plaintext u
An LWE secret key is a list of `n` random integers: $$S = (s_0, ..., s_n)$$. $$n$$ is called the $$LweDimension$$
A LWE ciphertext, is composed of two parts:
A LWE ciphertext is composed of two parts:
* The mask $$(a_0, ..., a_{n-1})$$
* The body $$b$$
@@ -35,15 +35,15 @@ The body is computed as follows:
$$b = (\sum_{i = 0}^{n-1}{a_i * s_i}) + plaintext$$
Now that the encryption scheme is defined, to illustrate why it is slower to compute over encrypted data, let us show the example of the addition between ciphertexts.
Now that the encryption scheme is defined, let's review the example of the addition between ciphertexts to illustrate why it is slower to compute over encrypted data.
To add two ciphertexts, we must add their $mask$ and $body$, as is done below.
To add two ciphertexts, we must add their $mask$ and $body$:
$$
ct_0 = (a_{0}, ..., a_{n}, b) \\ ct_1 = (a_{1}^{'}, ..., a_{n}^{'}, b^{'}) \\ ct_{2} = ct_0 + ct_1 \\ ct_{2} = (a_{0} + a_{0}^{'}, ..., a_{n} + a_{n}^{'}, b + b^{'})\\ b + b^{'} = (\sum_{i = 0}^{n-1}{a_i * s_i}) + plaintext + (\sum_{i = 0}^{n-1}{a_i^{'} * s_i}) + plaintext^{'}\\ b + b^{'} = (\sum_{i = 0}^{n-1}{(a_i + a_i^{'})* s_i}) + \Delta m + \Delta m^{'} + e + e^{'}\\
$$
To add ciphertexts, it is sufficient to add their masks and bodies. Instead of just adding 2 integers, one needs to add $$n + 1$$ elements. The addition is an intuitive example to show the slowdown of FHE computation compared to plaintext computation, but other operations are far more expensive (e.g., the computation of a lookup table using the Programmable Bootstrapping).
To add ciphertexts, it is sufficient to add their masks and bodies. Instead of just adding two integers, one needs to add $$n + 1$$ elements. The addition is an intuitive example to show the slowdown of FHE computation compared to plaintext computation, but other operations are far more expensive (e.g., the computation of a lookup table using Programmable Bootstrapping).
## Understanding noise and padding
@@ -52,9 +52,9 @@ In FHE, there are two types of operations that can be applied to ciphertexts:
* **leveled operations**, which increase the noise in the ciphertext
* **bootstrapped operations**, which reduce the noise in the ciphertext
In FHE, the noise must be tracked and managed in order to guarantee the correctness of the computation.
In FHE, noise must be tracked and managed to guarantee the correctness of the computation.
Bootstrapping operations are used across the computation to decrease the noise in the ciphertexts, preventing it from tampering the message. The rest of the operations are called leveled because they do not need bootstrapping operations and, thus, are usually really fast.
Bootstrapping operations are used across the computation to decrease noise within the ciphertexts, preventing it from tampering the message. The rest of the operations are called leveled because they do not need bootstrapping operations and are usually really fast as a result.
The following sections explain the concept of noise and padding in ciphertexts.
@@ -62,19 +62,19 @@ The following sections explain the concept of noise and padding in ciphertexts.
For it to be secure, LWE requires random noise to be added to the message at encryption time.
In TFHE, this random noise is drawn from a Centered Normal Distribution parameterized by a standard deviation. This standard deviation is a security parameter. With all other security parameters set, the larger the standard deviation is, the more secure the encryption is.
In TFHE, this random noise is drawn from a Centered Normal Distribution, parameterized by a standard deviation. This standard deviation is a security parameter. With all other security parameters set, the more secure the encryption, the larger the standard deviation.
In `TFHE-rs`, the noise is encoded in the least significant bits of the plaintexts. Each leveled computation will increase the noise. Thus, if too many computations are performed, the noise will eventually overflow onto the significant data bits of the message and lead to an incorrect result.
In `TFHE-rs`, noise is encoded in the least significant bits of the plaintexts. Each leveled computation increases the noise. If too many computations are performed, the noise will eventually overflow onto the significant data bits of the message and lead to an incorrect result.
The figure below illustrates this problem in case of an addition, where an extra bit of noise is incurred as a result.
![Noise overtaking the plaintexts after homomorphic addition. Most significant bits are on the left.](../\_static/fig7.png)
TFHE-rs offers the ability to automatically manage noise by performing bootstrapping operations to reset the noise when needed.
TFHE-rs offers the ability to automatically manage noise by performing bootstrapping operations to reset the noise.
### Padding.
Since encoded values have a fixed precision, operating on them can sometimes produce results that are outside the original interval. To avoid losing precision or wrapping around the interval, TFHE-rs uses additional bits by defining bits of **padding** on the most significant bits.
Since encoded values have a fixed precision, operating on them can produce results that are outside the original interval. To avoid losing precision or wrapping around the interval, TFHE-rs uses additional bits by defining bits of **padding** on the most significant bits.
As an example, consider adding two ciphertexts. Adding two values could end up outside the range of either ciphertext, and thus necessitate a carry, which would then be carried onto the first padding bit. In the figure below, each plaintext over 32 bits has one bit of padding on its left (i.e., the most significant bit). After the addition, the padding bit is no longer available, as it has been used in order for the carry. This is referred to as **consuming** bits of padding. Since no padding is left, there is no guarantee that further additions would yield correct results.
@@ -86,8 +86,8 @@ If you would like to know more about TFHE, you can find more information in our
By default, the cryptographic parameters provided by `TFHE-rs` ensure at least 128 bits of security. The security has been evaluated using the latest versions of the Lattice Estimator ([repository](https://github.com/malb/lattice-estimator)) with `red_cost_model = reduction.RC.BDGL16`.
For all sets of parameters, the error probability when computing a univariate function over one ciphertext is $$2^{-40}$$. Note that univariate functions might be performed when arithmetic functions are computed (for instance, the multiplication of two ciphertexts).
For all sets of parameters, the error probability when computing a univariate function over one ciphertext is $$2^{-40}$$. Note that univariate functions might be performed when arithmetic functions are computed (i.e., the multiplication of two ciphertexts).
### Public key encryption.
In public key encryption, the public key contains a given number of ciphertexts all encrypting the value 0. By setting the number of encryptions of 0 in the public key at $$m = \lceil (n+1) \log(q) \rceil + \lambda$$, where $$n$$ is the LWE dimension, $$q$$ is the ciphertext modulus, and $$\lambda$$ is the number of security bits. In a nutshell, this construction is secure due to the leftover hash lemma, which is essentially related to the impossibility of breaking the underlying multiple subset sum problem. By using this formula, this guarantees both a high-density subset sum and an exponentially large number of possible associated random vectors per LWE sample (a,b).
In public key encryption, the public key contains a given number of ciphertexts all encrypting the value 0. By setting the number of encryptions to 0 in the public key at $$m = \lceil (n+1) \log(q) \rceil + \lambda$$, where $$n$$ is the LWE dimension, $$q$$ is the ciphertext modulus, and $$\lambda$$ is the number of security bits. This construction is secure due to the leftover hash lemma, which relates to the impossibility of breaking the underlying multiple subset sum problem. This guarantees both a high-density subset sum and an exponentially large number of possible associated random vectors per LWE sample (a,b).

View File

@@ -0,0 +1,405 @@
# Operations
The structure and operations related to all types (ì.e., Booleans, shortint and integer) are described in this section.
## Booleans
Native homomorphic Booleans support common Boolean operations.
The list of supported operations is:
| name | symbol | type |
| ------------------------------------------------------------- | ------ | ------ |
| [BitAnd](https://doc.rust-lang.org/std/ops/trait.BitAnd.html) | `&` | Binary |
| [BitOr](https://doc.rust-lang.org/std/ops/trait.BitOr.html) | `\|` | Binary |
| [BitXor](https://doc.rust-lang.org/std/ops/trait.BitXor.html) | `^` | Binary |
| [Neg](https://doc.rust-lang.org/std/ops/trait.Neg.html) | `!` | Unary |
## ShortInt
Native small homomorphic integer types (e.g., FheUint3 or FheUint4) easily compute various operations. In general, computing over encrypted data is as easy as computing over clear data, since the same operation symbol is used. The addition between two ciphertexts is done using the symbol `+` between two FheUint. Many operations can be computed between a clear value (i.e. a scalar) and a ciphertext.
In Rust native types, any operation is modular. In Rust, `u8`, computations are done modulus 2^8. The similar idea is applied for FheUintX, where operations are done modulus 2^X. In the type FheUint3, operations are done modulo 8.
### Arithmetic operations.
Small homomorphic integer types support all common arithmetic operations, meaning `+`, `-`, `x`, `/`, `mod`.
The division operation implements a subtlety: since data is encrypted, it might be possible to compute a division by 0. In this case, the division is tweaked so that dividing by 0 returns 0.
The list of supported operations is:
| name | symbol | type |
| ------------------------------------------------------- | ------ | ------ |
| [Add](https://doc.rust-lang.org/std/ops/trait.Add.html) | `+` | Binary |
| [Sub](https://doc.rust-lang.org/std/ops/trait.Sub.html) | `-` | Binary |
| [Mul](https://doc.rust-lang.org/std/ops/trait.Mul.html) | `*` | Binary |
| [Div](https://doc.rust-lang.org/std/ops/trait.Div.html) | `/` | Binary |
| [Rem](https://doc.rust-lang.org/std/ops/trait.Rem.html) | `%` | Binary |
| [Neg](https://doc.rust-lang.org/std/ops/trait.Neg.html) | `!` | Unary |
A simple example on how to use these operations:
```rust
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint3};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_uint3().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 7;
let clear_b = 3;
let clear_c = 2;
let mut a = FheUint3::try_encrypt(clear_a, &keys)?;
let mut b = FheUint3::try_encrypt(clear_b, &keys)?;
let mut c = FheUint3::try_encrypt(clear_c, &keys)?;
a = a * &b; // Clear equivalent computations: 7 * 3 mod 8 = 5
b = &b + &c; // Clear equivalent computations: 3 + 2 mod 8 = 5
b = b - 5; // Clear equivalent computations: 5 - 5 mod 8 = 0
let dec_a = a.decrypt(&keys);
let dec_b = b.decrypt(&keys);
// We homomorphically swapped values using bitwise operations
assert_eq!(dec_a, (clear_a * clear_b) % 8);
assert_eq!(dec_b, ((clear_b + clear_c) - 5) % 8);
Ok(())
}
```
### Bitwise operations.
Small homomorphic integer types support some bitwise operations.
The list of supported operations is:
| name | symbol | type |
| ------------------------------------------------------------- | ------ | ------ |
| [BitAnd](https://doc.rust-lang.org/std/ops/trait.BitAnd.html) | `&` | Binary |
| [BitOr](https://doc.rust-lang.org/std/ops/trait.BitOr.html) | `\|` | Binary |
| [BitXor](https://doc.rust-lang.org/std/ops/trait.BitXor.html) | `^` | Binary |
| [Shr](https://doc.rust-lang.org/std/ops/trait.Shr.html) | `>>` | Binary |
| [Shl](https://doc.rust-lang.org/std/ops/trait.Shl.html) | `<<` | Binary |
A simple example on how to use these operations:
```rust
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint3};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_uint3().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 7;
let clear_b = 3;
let mut a = FheUint3::try_encrypt(clear_a, &keys)?;
let mut b = FheUint3::try_encrypt(clear_b, &keys)?;
a = a ^ &b;
b = b ^ &a;
a = a ^ &b;
let dec_a = a.decrypt(&keys);
let dec_b = b.decrypt(&keys);
// We homomorphically swapped values using bitwise operations
assert_eq!(dec_a, clear_b);
assert_eq!(dec_b, clear_a);
Ok(())
}
```
### Comparisons.
Small homomorphic integer types support comparison operations.
Due to some Rust limitations, it is not possible to overload the comparison symbols because of the inner definition of the operations. Rust expects to have a Boolean as an output, whereas a ciphertext encrypted result is returned when using homomorphic types.
You will need to use the different methods instead of using symbols for the comparisons. These methods follow the same naming conventions as the two standard Rust traits:
* [PartialOrd](https://doc.rust-lang.org/std/cmp/trait.PartialOrd.html)
* [PartialEq](https://doc.rust-lang.org/std/cmp/trait.PartialEq.html)
A simple example on how to use these operations:
```rust
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint3};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_uint3().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 7;
let clear_b = 3;
let mut a = FheUint3::try_encrypt(clear_a, &keys)?;
let mut b = FheUint3::try_encrypt(clear_b, &keys)?;
assert_eq!(a.gt(&b).decrypt(&keys) != 0, true);
assert_eq!(b.le(&a).decrypt(&keys) != 0, true);
Ok(())
}
```
### Univariate function evaluations.
The shortint type also supports the computation of univariate functions, which deep down uses TFHE's _programmable bootstrapping_.
A simple example on how to use these operations:
```rust
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint4};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_uint4().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let pow_5 = |value: u64| {
value.pow(5) % FheUint4::MODULUS as u64
};
let clear_a = 12;
let a = FheUint4::try_encrypt(12, &keys)?;
let c = a.map(pow_5);
let decrypted = c.decrypt(&keys);
assert_eq!(decrypted, pow_5(clear_a) as u8);
Ok(())
}
```
### Bivariate function evaluations.
Using the shortint type allows you to evaluate bivariate functions (i.e., functions that takes two ciphertexts as input).
A simple code example:
```rust
use tfhe::prelude::*;
use tfhe::{generate_keys, set_server_key, ConfigBuilder, FheUint2};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let config = ConfigBuilder::all_disabled().enable_default_uint2().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 1;
let clear_b = 3;
let a = FheUint2::try_encrypt(clear_a, &keys)?;
let b = FheUint2::try_encrypt(clear_b, &keys)?;
let c = a.bivariate_function(&b, std::cmp::max);
let decrypted = c.decrypt(&keys);
assert_eq!(decrypted, std::cmp::max(clear_a, clear_b) as u8);
Ok(())
}
```
## Integer
In TFHE-rs, integers are used to encrypt any messages larger than 4 bits. All supported operations are listed below.
### Arithmetic operations.
Homomorphic integer types support arithmetic operations.
The list of supported operations is:
| name | symbol | type |
| ------------------------------------------------------- | ------ | ------ |
| [Add](https://doc.rust-lang.org/std/ops/trait.Add.html) | `+` | Binary |
| [Sub](https://doc.rust-lang.org/std/ops/trait.Sub.html) | `-` | Binary |
| [Mul](https://doc.rust-lang.org/std/ops/trait.Mul.html) | `*` | Binary |
| [Neg](https://doc.rust-lang.org/std/ops/trait.Neg.html) | `!` | Unary |
A simple example on how to use these operations:
```rust
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_uint8().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 15_u64;
let clear_b = 27_u64;
let clear_c = 43_u64;
let mut a = FheUint8::try_encrypt(clear_a, &keys)?;
let mut b = FheUint8::try_encrypt(clear_b, &keys)?;
let mut c = FheUint8::try_encrypt(clear_c, &keys)?;
a = a * &b; // Clear equivalent computations: 15 * 27 mod 256 = 149
b = &b + &c; // Clear equivalent computations: 27 + 43 mod 256 = 70
b = b - 76u8; // Clear equivalent computations: 70 - 76 mod 256 = 250
let dec_a: u8 = a.decrypt(&keys);
let dec_b: u8 = b.decrypt(&keys);
assert_eq!(dec_a, ((clear_a * clear_b) % 256_u64) as u8);
assert_eq!(dec_b, (((clear_b + clear_c).wrapping_sub(76_u64)) % 256_u64) as u8);
Ok(())
}
```
### Bitwise operations.
Homomorphic integer types support some bitwise operations.
The list of supported operations is:
| name | symbol | type |
| ------------------------------------------------------------- | ------ | ------ |
| [BitAnd](https://doc.rust-lang.org/std/ops/trait.BitAnd.html) | `&` | Binary |
| [BitOr](https://doc.rust-lang.org/std/ops/trait.BitOr.html) | `\|` | Binary |
| [BitXor](https://doc.rust-lang.org/std/ops/trait.BitXor.html) | `^` | Binary |
| [Shr](https://doc.rust-lang.org/std/ops/trait.Shr.html) | `>>` | Binary |
| [Shl](https://doc.rust-lang.org/std/ops/trait.Shl.html) | `<<` | Binary |
A simple example on how to use these operations:
```rust
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_uint8().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a = 164;
let clear_b = 212;
let mut a = FheUint8::try_encrypt(clear_a, &keys)?;
let mut b = FheUint8::try_encrypt(clear_b, &keys)?;
a = a ^ &b;
b = b ^ &a;
a = a ^ &b;
let dec_a: u8 = a.decrypt(&keys);
let dec_b: u8 = b.decrypt(&keys);
// We homomorphically swapped values using bitwise operations
assert_eq!(dec_a, clear_b);
assert_eq!(dec_b, clear_a);
Ok(())
}
```
### Comparisons.
Homomorphic integers support comparison operations. Since Rust does not allow the overloading of these operations, a simple function has been associated to each one.
The list of supported operations is:
| name | symbol | type |
| --------------------- | ------ | ------ |
| Greater than | `gt` | Binary |
| Greater or equal than | `ge` | Binary |
| Lower than | `lt` | Binary |
| Lower or equal than | `le` | Binary |
| Equal | `eq` | Binary |
A simple example on how to use these operations:
```rust
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_uint8().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a:u8 = 164;
let clear_b:u8 = 212;
let mut a = FheUint8::try_encrypt(clear_a, &keys)?;
let mut b = FheUint8::try_encrypt(clear_b, &keys)?;
let greater = a.gt(&b);
let greater_or_equal = a.ge(&b);
let lower = a.lt(&b);
let lower_or_equal = a.le(&b);
let equal = a.eq(&b);
let dec_gt : u8 = greater.decrypt(&keys);
let dec_ge : u8 = greater_or_equal.decrypt(&keys);
let dec_lt : u8 = lower.decrypt(&keys);
let dec_le : u8 = lower_or_equal.decrypt(&keys);
let dec_eq : u8 = equal.decrypt(&keys);
// We homomorphically swapped values using bitwise operations
assert_eq!(dec_gt, (clear_a > clear_b ) as u8);
assert_eq!(dec_ge, (clear_a >= clear_b) as u8);
assert_eq!(dec_lt, (clear_a < clear_b ) as u8);
assert_eq!(dec_le, (clear_a <= clear_b) as u8);
assert_eq!(dec_eq, (clear_a == clear_b) as u8);
Ok(())
}
```
### Min/Max.
Homomorphic integers support the min/max operations.
| name | symbol | type |
| ---- | ------ | ------ |
| Min | `min` | Binary |
| Max | `max` | Binary |
A simple example on how to use these operations:
```rust
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_uint8().build();
let (keys, server_keys) = generate_keys(config);
set_server_key(server_keys);
let clear_a:u8 = 164;
let clear_b:u8 = 212;
let mut a = FheUint8::try_encrypt(clear_a, &keys)?;
let mut b = FheUint8::try_encrypt(clear_b, &keys)?;
let min = a.min(&b);
let max = a.max(&b);
let dec_min : u8 = min.decrypt(&keys);
let dec_max : u8 = max.decrypt(&keys);
// We homomorphically swapped values using bitwise operations
assert_eq!(dec_min, u8::min(clear_a, clear_b));
assert_eq!(dec_max, u8::max(clear_a, clear_b));
Ok(())
}
```

View File

@@ -0,0 +1,73 @@
# Serialization/Deserialization
As explained in the Introduction, most types are meant to be shared with the server that performs the computations.
The easiest way to send these data to a server is to use the `serialization` and `deserialization` features. `tfhe` uses the [serde](https://crates.io/crates/serde) framework. Serde's `Serialize` and `Deserialize` functions are implemented on TFHE's types.
To serialize our data, a [data format](https://serde.rs/#data-formats) should be picked. Here, [bincode](https://crates.io/crates/bincode) is a good choice, mainly because it is a binary format.
```toml
# Cargo.toml
[dependencies]
# ...
tfhe = { version = "0.2.4", features = ["integer","x86_64-unix"]}
bincode = "1.3.3"
```
```rust
// main.rs
use bincode;
use std::io::Cursor;
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_uint8()
.build();
let ( client_key, server_key) = generate_keys(config);
let msg1 = 1;
let msg2 = 0;
let value_1 = FheUint8::encrypt(msg1, &client_key);
let value_2 = FheUint8::encrypt(msg2, &client_key);
// Prepare to send data to the server
// The ClientKey is _not_ sent
let mut serialized_data = Vec::new();
bincode::serialize_into(&mut serialized_data, &server_key)?;
bincode::serialize_into(&mut serialized_data, &value_1)?;
bincode::serialize_into(&mut serialized_data, &value_2)?;
// Simulate sending serialized data to a server and getting
// back the serialized result
let serialized_result = server_function(&serialized_data)?;
let result: FheUint8 = bincode::deserialize(&serialized_result)?;
let output: u8 = result.decrypt(&client_key);
assert_eq!(output, msg1 + msg2);
Ok(())
}
fn server_function(serialized_data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut serialized_data = Cursor::new(serialized_data);
let server_key: ServerKey = bincode::deserialize_from(&mut serialized_data)?;
let ct_1: FheUint8 = bincode::deserialize_from(&mut serialized_data)?;
let ct_2: FheUint8 = bincode::deserialize_from(&mut serialized_data)?;
set_server_key(server_key);
let result = ct_1 + ct_2;
let serialized_result = bincode::serialize(&result)?;
Ok(serialized_result)
}
```

View File

@@ -0,0 +1,679 @@
# Tutorial
## Quick Start
The basic steps for using the high-level API of TFHE-rs are:
1. Importing TFHE-rs prelude;
2. Client-side: Configuring and creating keys;
3. Client-side: Encrypting data;
4. Server-side: Setting the server key;
5. Server-side: Computing over encrypted data;
6. Client-side: Decrypting data.
Here is the full example (mixing client and server parts):
```rust
use tfhe::{ConfigBuilder, generate_keys, set_server_key, FheUint8};
use tfhe::prelude::*;
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_uint8()
.build();
// Client-side
let (client_key, server_key) = generate_keys(config);
let clear_a = 27u8;
let clear_b = 128u8;
let a = FheUint8::encrypt(clear_a, &client_key);
let b = FheUint8::encrypt(clear_b, &client_key);
//Server-side
set_server_key(server_key);
let result = a + b;
//Client-side
let decrypted_result: u8 = result.decrypt(&client_key);
let clear_result = clear_a + clear_b;
assert_eq!(decrypted_result, clear_result);
}
```
Default configuration for x86 Unix machines:
```toml
tfhe = { version = "0.2.4", features = ["integer", "x86_64-unix"]}
```
Other configurations can be found [here](../getting_started/installation.md).
### Imports.
`tfhe` uses `traits` to have a consistent API for creating FHE types and enable users to write generic functions. To be able to use associated functions and methods of a trait, the trait has to be in scope.
To make it easier, the `prelude` 'pattern' is used. All `tfhe` important traits are in a `prelude` module that you **glob import**. With this, there is no need to remember or know the traits to import.
```rust
use tfhe::prelude::*;
```
### 1. Configuring and creating keys.
The first step is the creation of the configuration. The configuration is used to declare which type you will use or not use, as well as enabling you to use custom crypto-parameters for these types for more advanced usage / testing.
Creating a configuration is done using the ConfigBuilder type.
In this example, 8-bit unsigned integers with default parameters are used. The `integers`
feature must also be enabled, as per the table on the [Getting Started page](../getting_started/installation.md).
The config is done by first creating a builder with all types deactivated. Then, the `uint8` type with default parameters is activated.
```rust
use tfhe::{ConfigBuilder, generate_keys};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_uint8()
.build();
let (client_key, server_key) = generate_keys(config);
}
```
The `generate_keys` command returns a client key and a server key.
The `client_key` is meant to stay private and not leave the client whereas the `server_key` can be made public and sent to a server for it to enable FHE computations.
### 2. Setting the server key.
The next step is to call `set_server_key`
This function will **move** the server key to an internal state of the crate and manage the details to give a simpler interface.
```rust
use tfhe::{ConfigBuilder, generate_keys, set_server_key};
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_uint8()
.build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
}
```
### 3. Encrypting data.
Encrypting data is done via the `encrypt` associated function of the \[FheEncrypt] trait.
Types exposed by this crate implement at least one of \[FheEncrypt] or \[FheTryEncrypt] to allow enryption.
```Rust
let clear_a = 27u8;
let clear_b = 128u8;
let a = FheUint8::encrypt(clear_a, &client_key);
let b = FheUint8::encrypt(clear_b, &client_key);
```
### 4. Computation and decryption.
Computations should be as easy as normal Rust to write, thanks to operator overloading.
```Rust
let result = a + b;
```
The decryption is done by using the `decrypt` method, which comes from the \[FheDecrypt] trait.
```Rust
let decrypted_result: u8 = result.decrypt(&client_key);
let clear_result = clear_a + clear_b;
assert_eq!(decrypted_result, clear_result);
```
## A first complete example: FheLatinString (Integer)
The goal of this tutorial is to build a data type that represents a Latin string in FHE while implementing the `to_lower` and `to_upper` functions.
The allowed characters in a Latin string are:
* Uppercase letters: `A B C D E F G H I J K L M N O P Q R S T U V W X Y Z`
* Lowercase letters: `a b c d e f g h i j k l m n o p q r s t u v w x y z`
For the code point of the letters,`ascii` codes are used:
* The uppercase letters are in the range \[65, 90]
* The lowercase letters are in the range \[97, 122]
`lower_case` = `upper_case` + 32 <=> `upper_case` = `lower_case` - 32
For this type, the `FheUint8` type is used.
### Types and methods.
This type will hold the encrypted characters as a `Vec<FheUint8>`, as well as the encrypted constant `32` to implement the functions that change the case.
In the `FheLatinString::encrypt` function, some data validation is done:
* The input string can only contain ascii letters (no digit, no special characters).
* The input string cannot mix lower and upper case letters.
These two points are to work around a limitation of FHE. It is not possible to create branches, meaning the function cannot use conditional statements. Checking if the 'char' is an uppercase letter to modify it to a lowercase one cannot be done, like in the example below.
```rust
fn to_lower(string: &String) -> String {
let mut result = String::with_capacity(string.len());
for char in string.chars() {
if char.is_uppercase() {
result.extend(char.to_lowercase().to_string().chars())
}
}
result
}
```
With these preconditions checked, implementing `to_lower` and `to_upper` is rather simple.
To use the `FheUint8` type, the `integer` feature must be activated:
```toml
# Cargo.toml
[dependencies]
# Default configuration for x86 Unix machines:
tfhe = { version = "0.2.4", features = ["integer", "x86_64-unix"]}
```
Other configurations can be found [here](../getting_started/installation.md).
```rust
use tfhe::{FheUint8, ConfigBuilder, generate_keys, set_server_key, ClientKey};
use tfhe::prelude::*;
struct FheLatinString{
bytes: Vec<FheUint8>,
// Constant used to switch lower case <=> upper case
cst: FheUint8,
}
impl FheLatinString {
fn encrypt(string: &str, client_key: &ClientKey) -> Self {
assert!(
string.chars().all(|char| char.is_ascii_alphabetic()),
"The input string must only contain ascii letters"
);
let has_mixed_case = string.as_bytes().windows(2).any(|window| {
let first = char::from(*window.first().unwrap());
let second = char::from(*window.last().unwrap());
(first.is_ascii_lowercase() && second.is_ascii_uppercase())
|| (first.is_ascii_uppercase() && second.is_ascii_lowercase())
});
assert!(
!has_mixed_case,
"The input string cannot mix lower case and upper case letters"
);
let fhe_bytes = string
.bytes()
.map(|b| FheUint8::encrypt(b, client_key))
.collect::<Vec<FheUint8>>();
let cst = FheUint8::encrypt(32, client_key);
Self {
bytes: fhe_bytes,
cst,
}
}
fn decrypt(&self, client_key: &ClientKey) -> String {
let ascii_bytes = self
.bytes
.iter()
.map(|fhe_b| fhe_b.decrypt(client_key))
.collect::<Vec<u8>>();
String::from_utf8(ascii_bytes).unwrap()
}
fn to_upper(&self) -> Self {
Self {
bytes: self
.bytes
.iter()
.map(|b| b - &self.cst)
.collect::<Vec<FheUint8>>(),
cst: self.cst.clone(),
}
}
fn to_lower(&self) -> Self {
Self {
bytes: self
.bytes
.iter()
.map(|b| b + &self.cst)
.collect::<Vec<FheUint8>>(),
cst: self.cst.clone(),
}
}
}
fn main() {
let config = ConfigBuilder::all_disabled()
.enable_default_uint8()
.build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
let my_string = FheLatinString::encrypt("zama", &client_key);
let verif_string = my_string.decrypt(&client_key);
println!("{}", verif_string);
let my_string_upper = my_string.to_upper();
let verif_string = my_string_upper.decrypt(&client_key);
println!("{}", verif_string);
assert_eq!(verif_string, "ZAMA");
let my_string_lower = my_string_upper.to_lower();
let verif_string = my_string_lower.decrypt(&client_key);
println!("{}", verif_string);
assert_eq!(verif_string, "zama");
}
```
## A more complex example: Parity Bit (Boolean)
This example is dedicated to the building of a small function that homomorphically computes a parity bit.
First, a non-generic function is written. Then, generics are used to handle the case where the function inputs are both `FheBool`s and clear `bool`s.
The parity bit function takes as input two parameters:
* A slice of Boolean
* A mode (`Odd` or `Even`)
This function returns a Boolean that will be either `true` or `false` so that the sum of Booleans (in the input and the returned one) is either an `Odd` or `Even` number, depending on the requested mode.
***
### 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.2.4", features = ["boolean", "x86_64-unix"]}
```
Other configurations can be found [here](../getting_started/installation.md).
#### function definition
First, the verification function is defined.
The way to find the parity bit is to initialize it to `false, then` `XOR` it with all the bits, one after the other, adding negation depending on the requested mode.
A validation function is also defined to sum together the number of the bit set within the input with the computed parity bit and check that the sum is an even or odd number, depending on the mode.
```rust
use tfhe::FheBool;
use tfhe::prelude::*;
#[derive(Copy, Clone, Debug)]
enum ParityMode {
// The sum bits of message + parity bit must an odd number
Odd,
// The sum bits of message + parity bit must an even number
Even,
}
fn compute_parity_bit(fhe_bits: &[FheBool], mode: ParityMode) -> FheBool {
let mut parity_bit = fhe_bits[0].clone();
for fhe_bit in &fhe_bits[1..] {
parity_bit = fhe_bit ^ parity_bit
}
match mode {
ParityMode::Odd => !parity_bit,
ParityMode::Even => parity_bit,
}
}
fn is_even(n: u8) -> bool {
(n & 1) == 0
}
fn is_odd(n: u8) -> bool {
!is_even(n)
}
fn check_parity_bit_validity(bits: &[bool], mode: ParityMode, parity_bit: bool) -> bool {
let num_bit_set = bits
.iter()
.map(|bit| *bit as u8)
.fold(parity_bit as u8, |acc, bit| acc + bit);
match mode {
ParityMode::Even => is_even(num_bit_set),
ParityMode::Odd => is_odd(num_bit_set),
}
}
```
#### final code
After the mandatory configuration steps, the function is called:
```rust
use tfhe::{FheBool, ConfigBuilder, generate_keys, set_server_key};
use tfhe::prelude::*;
#[derive(Copy, Clone, Debug)]
enum ParityMode {
// The sum bits of message + parity bit must an odd number
Odd,
// The sum bits of message + parity bit must an even number
Even,
}
fn compute_parity_bit(fhe_bits: &[FheBool], mode: ParityMode) -> FheBool {
let mut parity_bit = fhe_bits[0].clone();
for fhe_bit in &fhe_bits[1..] {
parity_bit = fhe_bit ^ parity_bit
}
match mode {
ParityMode::Odd => !parity_bit,
ParityMode::Even => parity_bit,
}
}
fn is_even(n: u8) -> bool {
(n & 1) == 0
}
fn is_odd(n: u8) -> bool {
!is_even(n)
}
fn check_parity_bit_validity(bits: &[bool], mode: ParityMode, parity_bit: bool) -> bool {
let num_bit_set = bits
.iter()
.map(|bit| *bit as u8)
.fold(parity_bit as u8, |acc, bit| acc + bit);
match mode {
ParityMode::Even => is_even(num_bit_set),
ParityMode::Odd => is_odd(num_bit_set),
}
}
fn main() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let (client_key, server_key) = generate_keys(config);
set_server_key(server_key);
let clear_bits = [0, 1, 0, 0, 0, 1, 1].map(|b| (b != 0) as bool);
let fhe_bits = clear_bits
.iter()
.map(|bit| FheBool::encrypt(*bit, &client_key))
.collect::<Vec<FheBool>>();
let mode = ParityMode::Odd;
let fhe_parity_bit = compute_parity_bit(&fhe_bits, mode);
let decrypted_parity_bit = fhe_parity_bit.decrypt(&client_key);
let is_parity_bit_valid = check_parity_bit_validity(&clear_bits, mode, decrypted_parity_bit);
println!("Parity bit is set: {} for mode: {:?}", decrypted_parity_bit, mode);
assert!(is_parity_bit_valid);
let mode = ParityMode::Even;
let fhe_parity_bit = compute_parity_bit(&fhe_bits, mode);
let decrypted_parity_bit = fhe_parity_bit.decrypt(&client_key);
let is_parity_bit_valid = check_parity_bit_validity(&clear_bits, mode, decrypted_parity_bit);
println!("Parity bit is set: {} for mode: {:?}", decrypted_parity_bit, mode);
assert!(is_parity_bit_valid);
}
```
***
### Generic version.
To make the `compute_parity_bit` function compatible with both `FheBool` and `bool`, generics have to be used.
Writing a generic function that accepts `FHE` types as well as clear types can help test the function to see if it is correct. If the function is generic, it can run with clear data, allowing the use of print-debugging or a debugger to spot errors.
Writing generic functions that use operator overloading for our FHE types can be trickier than normal, since `FHE` types are not copy. So using the reference `&` is mandatory, even though this is not the case when using native types, which are all `Copy`.
This will make the generic bounds trickier at first.
#### writing the correct trait bounds
The function has the following signature:
```Rust
fn check_parity_bit_validity(
fhe_bits: &[FheBool],
mode: ParityMode,
) -> bool
```
To make it generic, the first step is:
```Rust
fn compute_parity_bit<BoolType>(
fhe_bits: &[BoolType],
mode: ParityMode,
) -> BoolType
```
Next, the generic bounds have to be defined with the `where` clause.
In the function, the following operators are used:
* `!` (trait: `Not`)
* `^` (trait: `BitXor`)
By adding them to `where`, this gives:
```Rust
where
BoolType: Clone + Not<Output = BoolType>,
BoolType: BitXor<BoolType, Output=BoolType>,
```
However, the compiler will complain:
```text
---- src/user_doc_tests.rs - user_doc_tests (line 199) stdout ----
error[E0369]: no implementation for `&BoolType ^ BoolType`
--> src/user_doc_tests.rs:218:30
|
21 | parity_bit = fhe_bit ^ parity_bit
| ------- ^ ---------- BoolType
| |
| &BoolType
|
help: consider extending the `where` bound, but there might be an alternative better way to express this requirement
|
17 | BoolType: BitXor<BoolType, Output=BoolType>, &BoolType: BitXor<BoolType>
| ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
error: aborting due to previous error
```
`fhe_bit` is a reference to a `BoolType` (`&BoolType`) since it is borrowed from the `fhe_bits` slice when iterating over its elements. The first try is to change the `BitXor` bounds to what the Compiler suggests by requiring `&BoolType` to implement `BitXor` and not `BoolType`.
```Rust
where
BoolType: Clone + Not<Output = BoolType>,
&BoolType: BitXor<BoolType, Output=BoolType>,
```
The Compiler is still not happy:
```text
---- src/user_doc_tests.rs - user_doc_tests (line 236) stdout ----
error[E0637]: `&` without an explicit lifetime name cannot be used here
--> src/user_doc_tests.rs:251:5
|
17 | &BoolType: BitXor<BoolType, Output=BoolType>,
| ^ explicit lifetime name needed here
error[E0310]: the parameter type `BoolType` may not live long enough
--> src/user_doc_tests.rs:251:16
|
17 | &BoolType: BitXor<BoolType, Output=BoolType>,
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ...so that the reference type `&'static BoolType` does not outlive the data it points at
|
help: consider adding an explicit lifetime bound...
|
15 | BoolType: Clone + Not<Output = BoolType> + 'static,
|
```
The way to fix this is to use `Higher-Rank Trait Bounds`:
```Rust
where
BoolType: Clone + Not<Output = BoolType>,
for<'a> &'a BoolType: BitXor<BoolType, Output = BoolType>,
```
The final code will look like this:
```rust
use std::ops::{Not, BitXor};
#[derive(Copy, Clone, Debug)]
enum ParityMode {
// The sum bits of message + parity bit must an odd number
Odd,
// The sum bits of message + parity bit must an even number
Even,
}
fn compute_parity_bit<BoolType>(fhe_bits: &[BoolType], mode: ParityMode) -> BoolType
where
BoolType: Clone + Not<Output = BoolType>,
for<'a> &'a BoolType: BitXor<BoolType, Output = BoolType>,
{
let mut parity_bit = fhe_bits[0].clone();
for fhe_bit in &fhe_bits[1..] {
parity_bit = fhe_bit ^ parity_bit
}
match mode {
ParityMode::Odd => !parity_bit,
ParityMode::Even => parity_bit,
}
}
```
#### final code
Here is a complete example that uses this function for both clear and FHE values:
```rust
use tfhe::{FheBool, ConfigBuilder, generate_keys, set_server_key};
use tfhe::prelude::*;
use std::ops::{Not, BitXor};
#[derive(Copy, Clone, Debug)]
enum ParityMode {
// The sum bits of message + parity bit must an odd number
Odd,
// The sum bits of message + parity bit must an even number
Even,
}
fn compute_parity_bit<BoolType>(fhe_bits: &[BoolType], mode: ParityMode) -> BoolType
where
BoolType: Clone + Not<Output=BoolType>,
for<'a> &'a BoolType: BitXor<BoolType, Output=BoolType>,
{
let mut parity_bit = fhe_bits[0].clone();
for fhe_bit in &fhe_bits[1..] {
parity_bit = fhe_bit ^ parity_bit
}
match mode {
ParityMode::Odd => !parity_bit,
ParityMode::Even => parity_bit,
}
}
fn is_even(n: u8) -> bool {
(n & 1) == 0
}
fn is_odd(n: u8) -> bool {
!is_even(n)
}
fn check_parity_bit_validity(bits: &[bool], mode: ParityMode, parity_bit: bool) -> bool {
let num_bit_set = bits
.iter()
.map(|bit| *bit as u8)
.fold(parity_bit as u8, |acc, bit| acc + bit);
match mode {
ParityMode::Even => is_even(num_bit_set),
ParityMode::Odd => is_odd(num_bit_set),
}
}
fn main() {
let config = ConfigBuilder::all_disabled().enable_default_bool().build();
let ( client_key, server_key) = generate_keys(config);
set_server_key(server_key);
let clear_bits = [0, 1, 0, 0, 0, 1, 1].map(|b| (b != 0) as bool);
let fhe_bits = clear_bits
.iter()
.map(|bit| FheBool::encrypt(*bit, &client_key))
.collect::<Vec<FheBool>>();
let mode = ParityMode::Odd;
let clear_parity_bit = compute_parity_bit(&clear_bits, mode);
let fhe_parity_bit = compute_parity_bit(&fhe_bits, mode);
let decrypted_parity_bit = fhe_parity_bit.decrypt(&client_key);
let is_parity_bit_valid = check_parity_bit_validity(&clear_bits, mode, decrypted_parity_bit);
println!("Parity bit is set: {} for mode: {:?}", decrypted_parity_bit, mode);
assert!(is_parity_bit_valid);
assert_eq!(decrypted_parity_bit, clear_parity_bit);
let mode = ParityMode::Even;
let clear_parity_bit = compute_parity_bit(&clear_bits, mode);
let fhe_parity_bit = compute_parity_bit(&fhe_bits, mode);
let decrypted_parity_bit = fhe_parity_bit.decrypt(&client_key);
let is_parity_bit_valid = check_parity_bit_validity(&clear_bits, mode, decrypted_parity_bit);
println!("Parity bit is set: {} for mode: {:?}", decrypted_parity_bit, mode);
assert!(is_parity_bit_valid);
assert_eq!(decrypted_parity_bit, clear_parity_bit);
}
```

View File

@@ -1,20 +0,0 @@
# TFHE-rs Integer User Guide
[Introduction](introduction.md)
# Getting Started
[Installation](getting_started/installation.md)
[Writing Your First Circuit](getting_started/first_circuit.md)
[Types Of Operations](getting_started/operation_types.md)
[List of Operations](getting_started/operation_list.md)
[Cryptographic Parameters](getting_started/parameters.md)
# How to
[Serialization / Deserialization](tutorials/serialization.md)

View File

@@ -1,105 +0,0 @@
# Writing Your First Circuit
## Key Types
`integer` provides 2 basic key types:
- `ClientKey`
- `ServerKey`
The `ClientKey` is the key that encrypts and decrypts messages,
thus this key is meant to be kept private and should never be shared.
This key is created from parameter values that will dictate both the security and efficiency
of computations. The parameters also set the maximum number of bits of message encrypted
in a ciphertext.
The `ServerKey` is the key that is used to actually do the FHE computations. It contains (among other things)
a bootstrapping key and a keyswitching key.
This key is created from a `ClientKey` that needs to be shared to the server, therefore it is not
meant to be kept private.
A user with a `ServerKey` can compute on the encrypted data sent by the owner of the associated
`ClientKey`.
To reflect that, computation/operation methods are tied to the `ServerKey` type.
## 1. Key Generation
To generate the keys, a user needs two parameters:
- A set of `shortint` cryptographic parameters.
- The number of ciphertexts used to encrypt an integer (we call them "shortint blocks").
For this example we are going to build a pair of keys that can encrypt an **8-bit** integer
by using **4** shortint blocks that store **2** bits of message each.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
}
```
## 2. Encrypting values
Once we have our keys we can encrypt values:
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 128;
let msg2 = 13;
// We use the client key to encrypt two messages:
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
}
```
## 3. Computing and decrypting
With our `server_key`, and encrypted values, we can now do an addition
and then decrypt the result.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 128;
let msg2 = 13;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
// We use the server public key to execute an integer circuit:
let ct_3 = server_key.unchecked_add(&ct_1, &ct_2);
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_3);
assert_eq!(output, (msg1 + msg2) % modulus);
}
```

View File

@@ -1,11 +0,0 @@
# Installation
## Cargo.toml
To use `integer`, you will need to add TFHE-rs to the list of dependencies your project, by updating your `Cargo.toml` file.
```toml
tfhe = { version = "0.2.0", features = ["integer", "x86_64-unix"] }
```
TODO doc

View File

@@ -1,15 +0,0 @@
# List of available operations
`integer` comes with a set of already implemented functions:
- addition between two ciphertexts
- addition between a ciphertext and an unencrypted scalar
- multiplication of a ciphertext by an unencrypted scalar
- bitwise shift `<<`, `>>`
- bitwise and, or and xor
- multiplication between two ciphertexts
- subtraction of a ciphertext by another ciphertext
- subtraction of a ciphertext by an unencrypted scalar
- negation of a ciphertext

View File

@@ -1,86 +0,0 @@
# How Integers are represented
In `integer`, the encrypted data is split amongst many ciphertexts
encrypted using the `shortint` library.
This crate implements two ways to represent an integer:
- the Radix representation
- the CRT (Chinese Reminder Theorem) representation
## Radix based Integers
The first possibility to represent a large integer is to use a radix-based decomposition on the
plaintexts. Let $$B \in \mathbb{N}$$ be a basis such that the size of $$B$$ is smaller (or equal)
to four bits.
Then, an integer $$m \in \mathbb{N}$$ can be written as $$m = m_0 + m_1*B + m_2*B^2 + ... $$, where
each $$m_i$$ is strictly smaller than $$B$$. Each $$m_i$$ is then independently encrypted. In
the end, an Integer ciphertext is defined as a set of Shortint ciphertexts.
In practice, the definition of an Integer requires the basis and the number of blocks. This is
done at the key creation step.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
}
```
In this example, the keys are dedicated to Integers decomposed as four blocks using the basis
$$B=2^2$$. Otherwise said, they allow to work on Integers modulus $$(2^2)^4 = 2^8$$.
In this representation, the correctness of operations requires to propagate the carries
between the ciphertext. This operation is costly since it relies on the computation of many
programmable bootstrapping over Shortints.
## CRT based Integers
The second approach to represent large integers is based on the Chinese Remainder Theorem.
In this cases, the basis $$B$$ is composed of several integers $$b_i$$, such that there are
pairwise coprime, and each b_i has a size smaller than four bits. Then, the Integer will be
defined modulus $$\prod b_i$$. For an integer $$m$$, its CRT decomposition is simply defined as
$$m % b_0, m % b_1, ...$$. Each part is then encrypted as a Shortint ciphertext. In
the end, an Integer ciphertext is defined as a set of Shortint ciphertexts.
An example of such a basis
could be $$B = [2, 3, 5]$$. This means that the Integer is defined modulus $$2*3*5 = 30$$.
This representation has many advantages: no carry propagation is required, so that only cleaning
the carry buffer of each ciphertexts is enough. This implies that operations can easily be
parallelized. Moreover, it allows to efficiently compute PBS in the case where the function is
CRT compliant.
A variant of the CRT is proposed, where each block might be associated to a different key couple.
In the end, a keychain is required to the computations, but performance might be improved.
# Types of operations
Much like `shortint`, the operations available via a `ServerKey` may come in different variants:
- operations that take their inputs as encrypted values.
- scalar operations take at least one non-encrypted value as input.
For example, the addition has both variants:
- `ServerKey::unchecked_add` which takes two encrypted values and adds them.
- `ServerKey::unchecked_scalar_add` which takes an encrypted value and a clear value (the
so-called scalar) and adds them.
Each operation may come in different 'flavors':
- `unchecked`: Always does the operation, without checking if the result may exceed the capacity of
the plaintext space.
- `checked`: Checks are done before computing the operation, returning an error if operation
cannot be done safely.
- `smart`: Always does the operation, if the operation cannot be computed safely, the smart operation
will propagate the carry buffer to make the operation possible.
Not all operations have these 3 flavors, as some of them are implemented in a way that the operation
is always possible without ever exceeding the plaintext space capacity.

View File

@@ -1,6 +0,0 @@
# Use of parameters
`integer` does not come with its own set of parameters, instead it uses
parameters from the `shortint` crate. Currently, only the parameters
`PARAM_MESSAGE_{X}_CARRY_{X}` with `X` in [1,4] can be used in `integer`.

View File

@@ -1,51 +0,0 @@
# The tree programmable bootstrapping
In `integer`, the user can evaluate any function on an encrypted ciphertext. To do so the user must first
create a `treepbs key`, choose a function to evaluate and give them as parameters to the `tree programmable bootstrapping`.
Two versions of the tree pbs are implemented: the `standard` version that computes a result according to every encrypted
bit (message and carry), and the `base` version that only takes into account the message bits of each block.
{% hint style="warning" %}
The `tree pbs` is quite slow, therefore its use is currently restricted to two and three blocks integer ciphertexts.
{% endhint %}
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::integer::wopbs::WopbsKey;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
use tfhe::shortint::parameters::parameters_wopbs_message_carry::WOPBS_PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 2;
// Generate the client key and the server key:
let (cks, sks) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg: u64 = 27;
let ct = cks.encrypt(msg);
// message_modulus^vec_length
let modulus = cks.parameters().message_modulus.0.pow(num_block as u32) as u64;
let wopbs_key = WopbsKey::new_wopbs_key(&cks.as_ref(), &sks, &WOPBS_PARAM_MESSAGE_2_CARRY_2);
let f = |x: u64| x * x;
// evaluate f
let ct = wopbs_key.keyswitch_to_wopbs_params(&sks, &ct);
let lut = wopbs_key.generate_lut_radix(&ct, f);
let ct_res = wopbs_key.wopbs(&ct, &lut);
let ct_res = wopbs_key.keyswitch_to_pbs_params(&ct_res);
// decryption
let res = cks.decrypt(&ct_res);
let clear = f(msg) % modulus;
assert_eq!(res, clear);
}
```
# The WOP programmable bootstrapping

View File

@@ -1,8 +0,0 @@
# TFHE-rs Integer
## Introduction
`integer` is a module of TFHE-rs based on its `shortint` module, this crate provides
large precision integers by using multiple `shortint` ciphertexts.
The intended target audience for this library is people who are somewhat familiar with cryptography.

View File

@@ -0,0 +1,248 @@
# Operations
The structure and operations related to the integers are described in this section.
## How an integer is represented
In `integer`, the encrypted data is split amongst many ciphertexts encrypted with the `shortint` library. Below is a scheme representing an integer composed by k shortint ciphertexts.
![](../\_static/integer-ciphertext.png)
This crate implements two ways to represent an integer:
* the Radix representation
* the CRT (Chinese Reminder Theorem) representation
### Radix-based integers.
The first possibility to represent a large integer is to use a Radix-based decomposition on the plaintexts. Let $$B \in \mathbb{N}$$ be a basis such that the size of $$B$$ is smaller than (or equal to) 4 bits. Then, an integer $$m \in \mathbb{N}$$ can be written as $$m = m_0 + m_1*B + m_2*B^2 + ...$$, where each $$m_i$$ is strictly smaller than $$B$$. Each $$m_i$$ is then independently encrypted. In the end, an Integer ciphertext is defined as a set of shortint ciphertexts.
The definition of an integer requires a basis and a number of blocks. This is done at key generation. Below, the keys are dedicated to unsigned integers encrypting messages over 8 bits, using a basis over 2 bits (i.e., $$B=2^2$$) and 4 blocks.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
}
```
In this representation, the correctness of operations requires to propagate the carries between the ciphertext. This operation is costly since it relies on the computation of many programmable bootstrapping operations over shortints.
### CRT-based integers.
The second approach to represent large integers is based on the Chinese Remainder Theorem. In this case, the basis $$B$$ is composed of several integers $$b_i$$, such that there are pairwise coprime, and each $$b\_i$$ has a size smaller than 4 bits. The CRT-based integer are defined modulus $$\prod b_i$$. For an integer $$m$$, its CRT decomposition is simply defined as $$m % b_0, m % b_1, ...$$. Each part is then encrypted as a shortint ciphertext. In the end, an Integer ciphertext is defined as a set of shortint ciphertexts.
In the following example, the chosen basis is $$B = [2, 3, 5]$$. The integer is defined modulus $$2*3*5 = 30$$. There is no need to pre-size the number of blocks since it is determined from the number of values composing the basis. Here, the integer is split over three blocks.
```rust
use tfhe::integer::CrtClientKey;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let basis = vec![2, 3, 5];
let cks = CrtClientKey::new(PARAM_MESSAGE_2_CARRY_2, basis);
}
```
This representation has many advantages: no carry propagation is required, cleaning the carry buffer of each ciphertext block is enough. This implies that operations can easily be
parallelized. It also allows the efficient computation of PBS in the case where the function is CRT-compliant.
A variant of the CRT is proposed, where each block might be associated to a different key couple. In the end, a keychain to the computations is required, but performance might be improved.
## List of available operations
The list of operations available in `integer` depends on the type of representation:
| Operation name | Radix-based | CRT-based |
| ------------------------------ | -------------------- | -------------------------- |
| Negation | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Addition | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Scalar Addition | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Subtraction | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Scalar Subtraction | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Multiplication | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Scalar Multiplication | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Bitwise OR, AND, XOR | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Equality | :heavy\_check\_mark: | :heavy\_check\_mark: |
| Left/Right Shift | :heavy\_check\_mark: | :heavy\_multiplication\_x: |
| Comparisons `<`,`<=`,`>`, `>=` | :heavy\_check\_mark: | :heavy\_multiplication\_x: |
| Min, Max | :heavy\_check\_mark: | :heavy\_multiplication\_x: |
## Types of operations
Much like `shortint`, the operations available via a `ServerKey` may come in different variants:
* operations that take their inputs as encrypted values.
* scalar operations take at least one non-encrypted value as input.
For example, the addition has both variants:
* `ServerKey::unchecked_add`, which takes two encrypted values and adds them.
* `ServerKey::unchecked_scalar_add`, which takes an encrypted value and a clear value (the so-called scalar) and adds them.
Each operation may come in different 'flavors':
* `unchecked`: Always does the operation, without checking if the result may exceed the capacity of the plaintext space.
* `checked`: Checks are done before computing the operation, returning an error if operation cannot be done safely.
* `smart`: Always does the operation, if the operation cannot be computed safely, the smart operation will propagate the carry buffer to make the operation possible.
* `default`: Always compute the operation and always clear the carry. Could be **slower** than smart, but ensure that the timings are consistent from one call to another.
Not all operations have these 4 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.
## How to use each operation type
Let's try to do a circuit evaluation using the different flavors of already introduced operations. For a very small circuit, the `unchecked` flavor may be enough to do the computation correctly. Otherwise, `checked` and `smart` are the best options.
As an example, let's do a scalar multiplication, a subtraction, and an addition.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12u64;
let msg2 = 11u64;
let msg3 = 9u64;
let scalar = 3u64;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let ct_3 = client_key.encrypt(msg2);
server_key.unchecked_small_scalar_mul_assign(&mut ct_1, scalar);
server_key.unchecked_sub_assign(&mut ct_1, &ct_2);
server_key.unchecked_add_assign(&mut ct_1, &ct_3);
// We use the client key to decrypt the output of the circuit:
let output: u64 = client_key.decrypt(&ct_1);
// The carry buffer has been overflowed, the result is not correct
assert_ne!(output, ((msg1 * scalar as u64 - msg2) + msg3) % modulus as u64);
}
```
During this computation the carry buffer has been overflowed, and the output may be incorrect as all the operations were `unchecked`.
If the same circuit is done but using the `checked` flavor, a panic will occur:
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 2;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12u64;
let msg2 = 11u64;
let msg3 = 9u64;
let scalar = 3u64;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let ct_3 = client_key.encrypt(msg3);
let result = server_key.checked_small_scalar_mul_assign(&mut ct_1, scalar);
assert!(result.is_ok());
let result = server_key.checked_sub_assign(&mut ct_1, &ct_2);
assert!(result.is_err());
// We use the client key to decrypt the output of the circuit:
// Only the scalar multiplication could be done
let output: u64 = client_key.decrypt(&ct_1);
assert_eq!(output, (msg1 * scalar) % modulus as u64);
}
```
The `checked` flavor permits the manual management of the overflow of the carry buffer by raising an error if correctness is not guaranteed.
Using the `smart` flavor will output the correct result all the time. However, the computation may be slower as the carry buffer may be propagated during the computations.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12;
let msg2 = 11;
let msg3 = 9;
let scalar = 3;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let mut ct_2 = client_key.encrypt(msg2);
let mut ct_3 = client_key.encrypt(msg3);
server_key.smart_scalar_mul_assign(&mut ct_1, scalar);
server_key.smart_sub_assign(&mut ct_1, &mut ct_2);
server_key.smart_add_assign(&mut ct_1, &mut ct_3);
// We use the client key to decrypt the output of the circuit:
let output: u64 = client_key.decrypt(&ct_1);
assert_eq!(output, ((msg1 * scalar as u64 - msg2) + msg3) % modulus as u64);
}
```
The main advantage of the default flavor is to ensure predictable timings, as long as only this kind of operation is used. Only the parallelized version of the operations is provided.
{% hint style="warning" %}
Using `default` could **slow down** computations.
{% endhint %}
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12;
let msg2 = 11;
let msg3 = 9;
let scalar = 3;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let mut ct_2 = client_key.encrypt(msg2);
let mut ct_3 = client_key.encrypt(msg3);
server_key.scalar_mul_assign_parallelized(&mut ct_1, scalar);
server_key.sub_assign_parallelized(&mut ct_1, &mut ct_2);
server_key.add_assign_parallelized(&mut ct_1, &mut ct_3);
// We use the client key to decrypt the output of the circuit:
let output: u64 = client_key.decrypt(&ct_1);
assert_eq!(output, ((msg1 * scalar as u64 - msg2) + msg3) % modulus as u64);
}
```

View File

@@ -0,0 +1,3 @@
# Cryptographic Parameters
`integer` does not come with its own set of parameters. Instead, it relies on parameters from `shortint`. Currently, parameter sets having the same space dedicated to the message and the carry (i.e. `PARAM_MESSAGE_{X}_CARRY_{X}` with `X` in \[1,4]) are recommended. See [here](../shortint/parameters.md) for more details about cryptographic parameters, and [here](operations.md) to see how to properly instantiate integers depending on the chosen representation.

View File

@@ -1,14 +1,10 @@
# Serialization / Deserialization
# Serialization/Deserialization
As explained in the introduction, some types (`Serverkey`, `Ciphertext`) are meant to be shared
with the server that does the computations.
As explained in the introduction, some types (`Serverkey`, `Ciphertext`) are meant to be shared with the server that does the computations.
The easiest way to send these data to a server is to use the serialization and deserialization features.
concrete-integer uses the serde framework, serde's Serialize and Deserialize are implemented.
To be able to serialize our data, we need to pick a [data format], for our use case,
[bincode] is a good choice, mainly because it is binary format.
The easiest way to send these data to a server is to use the serialization and deserialization features. TFHE-rs uses the serde framework, so serde's Serialize and Deserialize are implemented.
To be able to serialize our data, a [data format](https://serde.rs/#data-formats) needs to be picked. Here, [bincode](https://crates.io/crates/bincode) is a good choice, mainly because it is binary format.
```toml
# Cargo.toml
@@ -18,14 +14,13 @@ To be able to serialize our data, we need to pick a [data format], for our use c
bincode = "1.3.3"
```
```rust
// main.rs
use bincode;
use std::io::Cursor;
use tfhe::integer::{gen_keys_radix, ServerKey, RadixCiphertext};
use tfhe::integer::{gen_keys_radix, ServerKey, RadixCiphertextBig};
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
@@ -51,9 +46,9 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Simulate sending serialized data to a server and getting
// back the serialized result
let serialized_result = server_function(&serialized_data)?;
let result: RadixCiphertext = bincode::deserialize(&serialized_result)?;
let result: RadixCiphertextBig = bincode::deserialize(&serialized_result)?;
let output = client_key.decrypt(&result);
let output: u64 = client_key.decrypt(&result);
assert_eq!(output, (msg1 + msg2) % modulus);
Ok(())
}
@@ -62,8 +57,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
fn server_function(serialized_data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut serialized_data = Cursor::new(serialized_data);
let server_key: ServerKey = bincode::deserialize_from(&mut serialized_data)?;
let ct_1: RadixCiphertext = bincode::deserialize_from(&mut serialized_data)?;
let ct_2: RadixCiphertext = bincode::deserialize_from(&mut serialized_data)?;
let ct_1: RadixCiphertextBig = bincode::deserialize_from(&mut serialized_data)?;
let ct_2: RadixCiphertextBig = bincode::deserialize_from(&mut serialized_data)?;
let result = server_key.unchecked_add(&ct_1, &ct_2);
@@ -72,7 +67,3 @@ fn server_function(serialized_data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error
Ok(serialized_result)
}
```
[serde]: https://crates.io/crates/serde
[data format]: https://serde.rs/#data-formats
[bincode]: https://crates.io/crates/bincode

View File

@@ -0,0 +1,121 @@
# Tutorial
The steps to homomorphically evaluate an integer circuit are described here.
## Key Types
`integer` provides 3 basic key types:
* `ClientKey`
* `ServerKey`
* `PublicKey`
The `ClientKey` is the key that encrypts and decrypts messages, thus this key is meant to be kept private and should never be shared. This key is created from parameter values that will dictate both the security and efficiency of computations. The parameters also set the maximum number of bits of message encrypted in a ciphertext.
The `ServerKey` is the key that is used to actually do the FHE computations. It contains a bootstrapping key and a keyswitching key. This key is created from a `ClientKey` that needs to be shared to the server, so it is not meant to be kept private. A user with a `ServerKey` can compute on the encrypted data sent by the owner of the associated `ClientKey`.
To reflect that, computation/operation methods are tied to the `ServerKey` type.
The `PublicKey` is a key used to encrypt messages. It can be publicly shared to allow users to encrypt data such that only the `ClientKey` holder will be able to decrypt. Encrypting with the `PublicKey` does not alter the homomorphic capabilities associated to the `ServerKey`.
## 1. Key Generation
To generate the keys, a user needs two parameters:
* A set of `shortint` cryptographic parameters.
* The number of ciphertexts used to encrypt an integer (we call them "shortint blocks").
We are now going to build a pair of keys that can encrypt an **8-bit** integer by using **4** shortint blocks that store **2** bits of message each.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
}
```
## 2. Encrypting values
Once we have our keys, we can encrypt values:
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 128u64;
let msg2 = 13u64;
// We use the client key to encrypt two messages:
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
}
```
## 3. Encrypting values with the public key
Once the client key is generated, the public key can be derived and used to encrypt data.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::integer::PublicKeyBig;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, _) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
//We generate the public key from the secret client key:
let public_key = PublicKeyBig::new(&client_key);
//encryption
let msg1 = 128u64;
let msg2 = 13u64;
// We use the public key to encrypt two messages:
let ct_1 = public_key.encrypt_radix(msg1, num_block);
let ct_2 = public_key.encrypt_radix(msg2, num_block);
}
```
## 4. Computing and decrypting
With our `server_key`, and encrypted values, we can now do an addition and then decrypt the result.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 128;
let msg2 = 13;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
// We use the server public key to execute an integer circuit:
let ct_3 = server_key.unchecked_add(&ct_1, &ct_2);
// We use the client key to decrypt the output of the circuit:
let output: u64 = client_key.decrypt(&ct_3);
assert_eq!(output, (msg1 + msg2) % modulus);
}
```

View File

@@ -1,120 +0,0 @@
# Circuit evaluation
Let's try to do a circuit evaluation using the different flavours of operations we already introduced.
For a very small circuit, the `unchecked` flavour may be enough to do the computation correctly.
Otherwise, the `checked` and `smart` are the best options.
As an example, let's do a scalar multiplication, a subtraction and an addition.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12;
let msg2 = 11;
let msg3 = 9;
let scalar = 3;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let ct_3 = client_key.encrypt(msg2);
server_key.unchecked_small_scalar_mul_assign(&mut ct_1, scalar);
server_key.unchecked_sub_assign(&mut ct_1, &ct_2);
server_key.unchecked_add_assign(&mut ct_1, &ct_3);
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_1);
// The carry buffer has been overflowed, the result is not correct
assert_ne!(output, ((msg1 * scalar as u64 - msg2) + msg3) % modulus as u64);
}
```
During this computation the carry buffer has been overflowed and as all the operations were `unchecked` the output
may be incorrect.
If we redo this same circuit but using the `checked` flavour, a panic will occur.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 2;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12;
let msg2 = 11;
let msg3 = 9;
let scalar = 3;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let ct_3 = client_key.encrypt(msg3);
let result = server_key.checked_small_scalar_mul_assign(&mut ct_1, scalar);
assert!(result.is_ok());
let result = server_key.checked_sub_assign(&mut ct_1, &ct_2);
assert!(result.is_err());
// We use the client key to decrypt the output of the circuit:
// Only the scalar multiplication could be done
let output = client_key.decrypt(&ct_1);
assert_eq!(output, (msg1 * scalar) % modulus as u64);
}
```
Therefore the `checked` flavour permits to manually manage the overflow of the carry buffer
by raising an error if the correctness is not guaranteed.
Lastly, using the `smart` flavour will output the correct result all the time. However, the computation may be slower
as the carry buffer may be propagated during the computations.
```rust
use tfhe::integer::gen_keys_radix;
use tfhe::shortint::parameters::PARAM_MESSAGE_2_CARRY_2;
fn main() {
let num_block = 4;
let (client_key, server_key) = gen_keys_radix(&PARAM_MESSAGE_2_CARRY_2, num_block);
let msg1 = 12;
let msg2 = 11;
let msg3 = 9;
let scalar = 3;
// message_modulus^vec_length
let modulus = client_key.parameters().message_modulus.0.pow(num_block as u32) as u64;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let mut ct_2 = client_key.encrypt(msg2);
let mut ct_3 = client_key.encrypt(msg3);
server_key.smart_scalar_mul_assign(&mut ct_1, scalar);
server_key.smart_sub_assign(&mut ct_1, &mut ct_2);
server_key.smart_add_assign(&mut ct_1, &mut ct_3);
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_1);
assert_eq!(output, ((msg1 * scalar as u64 - msg2) + msg3) % modulus as u64);
}
```

View File

@@ -2,24 +2,21 @@
## Using the JS on WASM API
Welcome to this TFHE-rs JS on WASM API tutorial!
Welcome to this TFHE-rs JS on WASM API tutorial.
TFHE-rs uses WASM to expose a JS binding to the client-side primitives, like key generation and encryption, of the Boolean and shortint modules.
There are several limitations at this time. Due to a lack of threading support in WASM, key
generation can be too slow to be practical for bigger parameter sets.
There are several limitations at this time. Due to a lack of threading support in WASM, key generation can be too slow to be practical for bigger parameter sets.
Some parameter sets lead to FHE keys that are too big to fit in the 2GB memory space of WASM.
This means that some parameters sets are virtually unusable.
Some parameter sets lead to FHE keys that are too big to fit in the 2GB memory space of WASM. This means that some parameter sets are virtually unusable.
## First steps using TFHE-rs JS on WASM API
### Setting-up TFHE-rs JS on WASM API for use in nodejs programs.
To build the JS on WASM bindings for TFHE-rs, you will first need to install [`wasm-pack`](https://rustwasm.github.io/wasm-pack/) in addition to a compatible (>= 1.65) [`rust toolchain`](https://rustup.rs/).
To build the JS on WASM bindings for TFHE-rs, you need to install [`wasm-pack`](https://rustwasm.github.io/wasm-pack/) in addition to a compatible (>= 1.65) [`rust toolchain`](https://rustup.rs/).
Then, in a shell run the following to clone the TFHE-rs repo (one may want to checkout a
specific tag, here the default branch is used for the build):
In a shell, then run the following to clone the TFHE-rs repo (one may want to checkout a specific tag, here the default branch is used for the build):
```shell
$ git clone https://github.com/zama-ai/tfhe-rs.git
@@ -34,12 +31,11 @@ $ rustup run wasm-pack build --release --target=nodejs --features=boolean-client
[INFO]: :-) Your wasm pkg is ready to publish at ...
```
The command above targets nodejs. A binding for a web browser can be generated as well using
`--target=web`. This use case will not be discussed in this tutorial.
The command above targets nodejs. A binding for a web browser can be generated as well using `--target=web`. This use case will not be discussed in this tutorial.
Both Boolean and shortint features are enabled here but it's possible to use one without the other.
Both Boolean and shortint features are enabled here, but it's possible to use one without the other.
After the build, a new directory ***pkg*** is present in the `tfhe` directory.
After the build, a new directory _**pkg**_ is present in the `tfhe` directory.
```shell
$ ls pkg
@@ -49,9 +45,8 @@ $
### Commented code to generate keys for shortint and encrypt a ciphertext
{% hint style=“warning” %}
Be sure to update the path of the required clause in the example below for the TFHE
package that was just built.
{% hint style="info" %}
Be sure to update the path of the required clause in the example below for the TFHE package that was just built.
{% endhint %}
```javascript
@@ -101,7 +96,7 @@ function shortint_example() {
shortint_example();
```
The `example.js` script can then be run using [`node`](https://nodejs.org/) like so:
The `example.js` script can then be run using [`node`](https://nodejs.org/), like so:
```shell
$ node example.js

View File

@@ -1,6 +1,8 @@
# Operations
## How shortint is represented
The structure and the operations related to the short integers are described in this section.
## How a shortint is represented
In `shortint`, the encrypted data is stored in an LWE ciphertext.
@@ -8,37 +10,38 @@ Conceptually, the message stored in an LWE ciphertext is divided into a **carry
![](../\_static/ciphertext-representation.png)
The message buffer is the space where the actual message is stored. This represents the modulus of the input messages (denoted by `MessageModulus` in the code). When doing computations on a ciphertext, the encrypted message can overflow the message modulus: the exceeding information is stored in the carry buffer. The size of the carry buffer is defined by another modulus, called `CarryModulus`.
The message buffer is the space where the actual message is stored. This represents the modulus of the input messages (denoted by `MessageModulus` in the code). When doing computations on a ciphertext, the encrypted message can overflow the message modulus. The exceeding information is stored in the carry buffer. The size of the carry buffer is defined by another modulus, called `CarryModulus`.
Together, the message modulus and the carry modulus form the plaintext space that is available in a ciphertext. This space cannot be overflowed, otherwise the computation may result in incorrect outputs.
In order to ensure the correctness of the computation, we keep track of the maximum value encrypted in a ciphertext via an associated attribute called the **degree**. When the degree reaches a defined threshold, the carry buffer may be emptied to safely resume the computations. Therefore, in `shortint` the carry modulus is mainly considered as a means to do more computations.
In order to ensure the correctness of the computation, we track the maximum value encrypted in a ciphertext via an associated attribute called the **degree**. When the degree reaches a defined threshold, the carry buffer may be emptied to safely resume the computations. In `shortint` the carry modulus is considered useful as a means to do more computations.
## Types of operations
The operations available via a `ServerKey` may come in different variants:
* operations that take their inputs as encrypted values.
* scalar operations that take at least one non-encrypted value as input.
* operations that take their inputs as encrypted values
* scalar operations that take at least one non-encrypted value as input
For example, the addition has both variants:
* `ServerKey::unchecked_add` which takes two encrypted values and adds them.
* `ServerKey::unchecked_scalar_add` which takes an encrypted value and a clear value (the so-called scalar) and adds them.
* `ServerKey::unchecked_add`, which takes two encrypted values and adds them.
* `ServerKey::unchecked_scalar_add`, which takes an encrypted value and a clear value (the so-called scalar) and adds them.
Each operation may come in different 'flavors':
* `unchecked`: Always does the operation, without checking if the result may exceed the capacity of the plaintext space. Using this operation might have an impact on the correctness of the following operations;
* `checked`: Checks are done before computing the operation, returning an error if operation cannot be done safely;
* `smart`: Always does the operation - if the operation cannot be computed safely, the smart operation will clear the carry modulus to make the operation possible.
* `smart`: Always does the operation. If the operation cannot be computed safely, the smart operation will clear the carry modulus to make the operation possible;
* `default`: Always does the operation and always clears the carry. Could be **slower** than smart, but it ensures that the timings are consistent from one call to another.
Not all operations have these 3 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.
Not all operations have these 4 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.
## How to use operation types
Let's try to do a circuit evaluation using the different flavours of operations we already introduced. For a very small circuit, the `unchecked` flavour may be enough to do the computation correctly. Otherwise, the `checked` and `smart` are the best options.
Let's try to do a circuit evaluation using the different flavors of operations we already introduced. For a very small circuit, the `unchecked` flavour may be enough to do the computation correctly. Otherwise,`checked` and `smart` are the best options.
As an example, let's do a scalar multiplication, a subtraction, and a multiplication.
Let's do a scalar multiplication, a subtraction, and a multiplication.
```rust
use tfhe::shortint::prelude::*;
@@ -70,7 +73,7 @@ fn main() {
During this computation, the carry buffer has been overflowed and, as all the operations were `unchecked`, the output may be incorrect.
If we redo this same circuit with the `checked` flavour, a panic will occur.
If we redo this same circuit with the `checked` flavor, a panic will occur:
```rust
use tfhe::shortint::prelude::*;
@@ -112,9 +115,9 @@ fn main() {
}
```
Therefore, the `checked` flavour permits manual management of the overflow of the carry buffer by raising an error if the correctness is not guaranteed.
The `checked` flavor permits manual management of the overflow of the carry buffer by raising an error if correctness is not guaranteed.
Lastly, using the `smart` flavour will output the correct result all the time. However, the computation may be slower as the carry buffer may be cleaned during the computations.
Using the `smart` flavor will output the correct result all the time. However, the computation may be slower as the carry buffer may be cleaned during the computations.
```rust
use tfhe::shortint::prelude::*;
@@ -144,17 +147,51 @@ fn main() {
}
```
The main advantage of the default flavor is to ensure predictable timings as long as only this kind of operation is used.
{% hint style="warning" %}
Using `default` could **slow-down** computations.
{% endhint %}
```rust
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 3;
let msg2 = 3;
let scalar = 4;
let modulus = client_key.parameters.message_modulus.0;
// We use the client key to encrypt two messages:
let mut ct_1 = client_key.encrypt(msg1);
let mut ct_2 = client_key.encrypt(msg2);
server_key.scalar_mul_assign(&mut ct_1, scalar);
server_key.sub_assign(&mut ct_1, &mut ct_2);
server_key.mul_lsb_assign(&mut ct_1, &mut ct_2);
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_1);
assert_eq!(output, ((msg1 * scalar as u64 - msg2) * msg2) % modulus as u64);
}
```
\#List of available operations
{% hint style="warning" %}
Currently, certain operations can only be used if the parameter set chosen is compatible with the bivariate programmable bootstrapping, meaning the carry buffer is larger than or equal to the message buffer. These operations are marked with a star (\*).
Certain operations can only be used if the parameter set chosen is compatible with the bivariate programmable bootstrapping, meaning the carry buffer is larger than or equal to the message buffer. These operations are marked with a star (\*).
{% endhint %}
The list of implemented operations for shortint is:
* addition between two ciphertexts
* addition between a ciphertext and an unencrypted scalar
* comparisons `<`, `<=`, `>`, `>=`, `==` between a ciphertext and an unencrypted scalar
* comparisons `<`, `<=`, `>`, `>=`, `==`, `!=` between a ciphertext and an unencrypted scalar
* division of a ciphertext by an unencrypted scalar
* LSB multiplication between two ciphertexts returning the result truncated to fit in the `message buffer`
* multiplication of a ciphertext by an unencrypted scalar
@@ -163,15 +200,13 @@ The list of implemented operations for shortint is:
* subtraction of a ciphertext by an unencrypted scalar
* negation of a ciphertext
* bitwise and, or and xor (\*)
* comparisons `<`, `<=`, `>`, `>=`, `==` between two ciphertexts (\*)
* comparisons `<`, `<=`, `>`, `>=`, `==`, `!=` between two ciphertexts (\*)
* division between two ciphertexts (\*)
* MSB multiplication between two ciphertexts returning the part overflowing the `message buffer` (\*)
In what follows, some simple code examples are given.
### Public key encryption.
TFHE-rs supports both private and public key encryption methods. Note that the only difference between both lies into the encryption step: in this case, the encryption method is called using `public_key` instead of `client_key`.
TFHE-rs supports both private and public key encryption methods. The only difference between both lies in the encryption step: in this case, the encryption method is called using `public_key` instead of `client_key`.
Here is a small example on how to use public encryption:
@@ -181,7 +216,7 @@ use tfhe::shortint::prelude::*;
fn main() {
// Generate the client key and the server key:
let (cks, _) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let pks = PublicKey::new(&cks);
let pks = PublicKeyBig::new(&cks);
let msg = 2;
// Encryption of one message:
@@ -192,8 +227,6 @@ fn main() {
}
```
In what follows, all examples are related to private key encryption.
### Arithmetic operations.
Classical arithmetic operations are supported by shortint:
@@ -307,7 +340,7 @@ fn main() {
let acc = server_key.generate_accumulator(|n| n.count_ones().into());
// add the two ciphertexts
let ct_res = server_key.keyswitch_programmable_bootstrap(&ct_1, &acc);
let ct_res = server_key.apply_lookup_table(&ct_1, &acc);
// We use the client key to decrypt the output of the circuit:
@@ -318,7 +351,7 @@ fn main() {
#### bi-variate function evaluations
Using the shortint types offers the possibility to evaluate bi-variate functions, i.e., functions that takes two ciphertexts as input. This requires choosing a parameter set such that the carry buffer size is at least as large as the message one i.e., PARAM\_MESSAGE\_X\_CARRY\_Y with X <= Y.
Using the shortint types offers the possibility to evaluate bi-variate functions, or functions that take two ciphertexts as input. This requires choosing a parameter set such that the carry buffer size is at least as large as the message (i.e., PARAM\_MESSAGE\_X\_CARRY\_Y with X <= Y).
Here is a simple code example:
@@ -336,13 +369,13 @@ fn main() {
// We use the private client key to encrypt two messages:
let ct_1 = client_key.encrypt(msg1);
let ct_2 = client_key.encrypt(msg2);
let mut ct_2 = client_key.encrypt(msg2);
// Compute the accumulator for the bivariate functions
let acc = server_key.generate_accumulator_bivariate(|x,y| (x.count_ones()
+ y.count_ones()) as u64 % modulus );
let ct_res = server_key.keyswitch_programmable_bootstrap_bivariate(&ct_1, &ct_2, &acc);
let ct_res = server_key.smart_apply_lookup_table_bivariate(&ct_1, &mut ct_2, &acc);
// We use the client key to decrypt the output of the circuit:
let output = client_key.decrypt(&ct_res);

View File

@@ -1,6 +1,6 @@
# Cryptographic Parameters
All parameter sets provide at least 128-bits of security according to the [Lattice-Estimator](https://github.com/malb/lattice-estimator), with an error probability equal to $$2^{-40}$$ when computing a programmable bootstrapping. This error probability is due to the randomness added at each encryption (see [here](../getting\_started/security\_and\_cryptography.md) for more details about the encryption process).
All parameter sets provide at least 128-bits of security according to the [Lattice-Estimator](https://github.com/malb/lattice-estimator), with an error probability equal to $$2^{-40}$$ when computing using programmable bootstrapping. This error probability is due to the randomness added at each encryption (see [here](../getting\_started/security\_and\_cryptography.md) for more details about the encryption process).
## Parameters and message precision
@@ -10,9 +10,9 @@ The user is allowed to choose which set of parameters to use when creating the p
The difference between the parameter sets is the total amount of space dedicated to the plaintext and how it is split between the message buffer and the carry buffer. The syntax chosen for the name of a parameter is: `PARAM_MESSAGE_{number of message bits}_CARRY_{number of carry bits}`. For example, the set of parameters for a message buffer of 5 bits and a carry buffer of 2 bits is `PARAM_MESSAGE_5_CARRY_2`.
In what follows, there is an example where keys are generated to have messages encoded over 2 bits i.e., computations are done modulus $$2^2 = 4$$), with 2 bits of carry.
This example contains keys that are generated to have messages encoded over 2 bits (i.e., computations are done modulus $$2^2 = 4$$) with 2 bits of carry.
Note that the `PARAM_MESSAGE_2_CARRY_2` parameter set is the default `shortint` parameter set that you can also use through the `tfhe::shortint::prelude::DEFAULT_PARAMETERS` constant.
The `PARAM_MESSAGE_2_CARRY_2` parameter set is the default `shortint` parameter set that you can also use through the `tfhe::shortint::prelude::DEFAULT_PARAMETERS` constant.
```rust
use tfhe::shortint::prelude::*;
@@ -36,15 +36,15 @@ As shown [here](../getting\_started/benchmarks.md), the choice of the parameter
### Generic bi-variate functions.
The computations of bi-variate functions is based on a trick, _concatenating_ two ciphertexts into one. In the case where the carry buffer is not at least as large as the message one, this trick no longer works. Then, many bi-variate operations, such as comparisons cannot be correctly computed. The only exception concerns the multiplication.
The computations of bi-variate functions is based on a trick: _concatenating_ two ciphertexts into one. Where the carry buffer is not at least as large as the message one, this trick no longer works. Many bi-variate operations, such as comparisons, then cannot be correctly computed. The only exception concerns multiplication.
### Multiplication.
In the case of the multiplication, two algorithms are implemented: the first one relies on the bi-variate function trick, where the other one is based on the [quarter square method](https://en.wikipedia.org/wiki/Multiplication\_algorithm#Quarter\_square\_multiplication). In order to correctly compute a multiplication, the only requirement is to have at least one bit of carry (i.e., using parameter sets PARAM\_MESSAGE\_X\_CARRY\_Y with Y>=1). This method is, in general, slower than using the other one. Note that using the `smart` version of the multiplication automatically chooses which algorithm is used depending on the chosen parameters.
In the case of multiplication, two algorithms are implemented: the first one relies on the bi-variate function trick, where the other one is based on the [quarter square method](https://en.wikipedia.org/wiki/Multiplication\_algorithm#Quarter\_square\_multiplication). To correctly compute a multiplication, the only requirement is to have at least one bit of carry (i.e., using parameter sets PARAM\_MESSAGE\_X\_CARRY\_Y with Y>=1). This method is slower than using the other one. Using the `smart` version of the multiplication automatically chooses which algorithm is used depending on the chosen parameters.
## User-defined parameter sets
Beyond the predefined parameter sets, it is possible to define new parameter sets. To do so, it is sufficient to use the function `unsecure_parameters()` or to manually fill the `Parameter` structure fields.
It is possible to define new parameter sets. To do so, it is sufficient to use the function `unsecure_parameters()` or to manually fill the `Parameter` structure fields.
For instance:
@@ -70,6 +70,7 @@ fn main() {
DecompositionBaseLog(0),
MessageModulus(4),
CarryModulus(1),
CiphertextModulus::new_native(),
)
};
}

View File

@@ -4,7 +4,7 @@ As explained in the introduction, some types (`Serverkey`, `Ciphertext`) are mea
The easiest way to send these data to a server is to use the serialization and deserialization features. tfhe::shortint uses the [serde](https://crates.io/crates/serde) framework. Serde's Serialize and Deserialize are then implemented on tfhe::shortint's types.
To be able to serialize our data, we need to pick a [data format](https://serde.rs/#data-formats). For our use case, [bincode](https://crates.io/crates/bincode) is a good choice, mainly because it is binary format.
To serialize the data, we need to pick a [data format](https://serde.rs/#data-formats). For our use case, [bincode](https://crates.io/crates/bincode) is a good choice, mainly because it is binary format.
```toml
# Cargo.toml
@@ -23,7 +23,7 @@ use tfhe::shortint::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let (client_key, server_key) = gen_keys(Parameters::default());
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 1;
let msg2 = 0;
@@ -39,7 +39,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
// Simulate sending serialized data to a server and getting
// back the serialized result
let serialized_result = server_function(&serialized_data)?;
let result: Ciphertext = bincode::deserialize(&serialized_result)?;
let result: CiphertextBig = bincode::deserialize(&serialized_result)?;
let output = client_key.decrypt(&result);
assert_eq!(output, msg1 + msg2);
@@ -50,8 +50,8 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {
fn server_function(serialized_data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
let mut serialized_data = Cursor::new(serialized_data);
let server_key: ServerKey = bincode::deserialize_from(&mut serialized_data)?;
let ct_1: Ciphertext = bincode::deserialize_from(&mut serialized_data)?;
let ct_2: Ciphertext = bincode::deserialize_from(&mut serialized_data)?;
let ct_1: CiphertextBig = bincode::deserialize_from(&mut serialized_data)?;
let ct_2: CiphertextBig = bincode::deserialize_from(&mut serialized_data)?;
let result = server_key.unchecked_add(&ct_1, &ct_2);

View File

@@ -1,26 +1,29 @@
# Tutorial
## Writing an homomorphic circuit using shortint
The steps to homomorphically evaluate a circuit are described below.
## Key Generation
## Key generation
`tfhe::shortint` provides 2 key types:
`tfhe::shortint` provides 3 key types:
* `ClientKey`
* `ServerKey`
* `PublicKey`
The `ClientKey` is the key that encrypts and decrypts messages (integer values up to 8 bits here), thus this key is meant to be kept private and should never be shared. This key is created from parameter values that will dictate both the security and efficiency of computations. The parameters also set the maximum number of bits of message encrypted in a ciphertext.
The `ClientKey` is the key that encrypts and decrypts messages (integer values up to 8 bits here). It is meant to be kept private and should never be shared. This key is created from parameter values that will dictate both the security and efficiency of computations. The parameters also set the maximum number of bits of message encrypted in a ciphertext.
The `ServerKey` is the key that is used to actually do the FHE computations. It contains (among other things) a bootstrapping key and a keyswitching key. This key is created from a `ClientKey` that needs to be shared to the server, therefore it is not meant to be kept private. A user with a `ServerKey` can compute on the encrypted data sent by the owner of the associated `ClientKey`.
The `ServerKey` is the key that is used to actually do the FHE computations. Most importantly, it contains a bootstrapping key and a keyswitching key. This key is created from a `ClientKey` that needs to be shared to the server, therefore it is not meant to be kept private. A user with a `ServerKey` can compute on the encrypted data sent by the owner of the associated `ClientKey`.
To reflect that, computation/operation methods are tied to the `ServerKey` type.
Computation/operation methods are tied to the `ServerKey` type.
The `PublicKey` is the key used to encrypt messages. It can be publicly shared to allow users to encrypt data such that only the `ClientKey` holder will be able to decrypt. Encrypting with the `PublicKey` does not alter the homomorphic capabilities associated to the `ServerKey`.
```rust
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(Parameters::default());
// We generate a set of client/server keys
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
}
```
@@ -32,8 +35,8 @@ Once the keys have been generated, the client key is used to encrypt data:
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(Parameters::default());
// We generate a set of client/server keys
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 1;
let msg2 = 0;
@@ -52,9 +55,9 @@ Once the keys have been generated, the client key is used to encrypt data:
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, _) = gen_keys(Parameters::default());
let public_key = PublicKey::new(&client_key);
// We generate a set of client/server keys
let (client_key, _) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let public_key = PublicKeyBig::new(&client_key);
let msg1 = 1;
let msg2 = 0;
@@ -67,14 +70,14 @@ fn main() {
## Computing and decrypting
With our `server_key` and encrypted values, we can now do an addition and then decrypt the result.
With the `server_key`, addition is now possible over encrypted values. The resulting plaintext is recovered after the decryption with the secret client key.
```rust
use tfhe::shortint::prelude::*;
fn main() {
// We generate a set of client/server keys, using the default parameters:
let (client_key, server_key) = gen_keys(Parameters::default());
// We generate a set of client/server keys
let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
let msg1 = 1;
let msg2 = 0;

View File

@@ -1,3 +1,7 @@
#[path = "../benches/utilities.rs"]
mod utilities;
use crate::utilities::{write_to_json, OperatorType};
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::Path;
@@ -12,8 +16,8 @@ fn write_result(file: &mut File, name: &str, value: usize) {
fn client_server_key_sizes(results_file: &Path) {
let boolean_params_vec = vec![
(DEFAULT_PARAMETERS, "default"),
(TFHE_LIB_PARAMETERS, "tfhe_lib"),
(DEFAULT_PARAMETERS, "DEFAULT_PARAMETERS"),
(TFHE_LIB_PARAMETERS, "TFHE_LIB_PARAMETERS"),
];
File::create(results_file).expect("create results file failed");
let mut file = OpenOptions::new()
@@ -21,19 +25,25 @@ fn client_server_key_sizes(results_file: &Path) {
.open(results_file)
.expect("cannot open results file");
let operator = OperatorType::Atomic;
println!("Generating boolean (ClientKey, ServerKey)");
for (i, (params, name)) in boolean_params_vec.iter().enumerate() {
for (i, (params, params_name)) in boolean_params_vec.iter().enumerate() {
println!(
"Generating [{} / {}] : {}",
i + 1,
boolean_params_vec.len(),
name
params_name.to_lowercase()
);
let cks = client_key::ClientKey::new(params);
let sks = server_key::ServerKey::new(&cks);
let ksk_size = sks.key_switching_key_size_bytes();
write_result(&mut file, &format!("boolean_{}_{}", name, "ksk"), ksk_size);
let test_name = format!("boolean_key_sizes_{params_name}_ksk");
write_result(&mut file, &test_name, ksk_size);
write_to_json(&test_name, *params, *params_name, "KSK", &operator);
println!(
"Element in KSK: {}, size in bytes: {}",
sks.key_switching_key_size_elements(),
@@ -41,7 +51,11 @@ fn client_server_key_sizes(results_file: &Path) {
);
let bsk_size = sks.bootstrapping_key_size_bytes();
write_result(&mut file, &format!("boolean_{}_{}", name, "bsk"), bsk_size);
let test_name = format!("boolean_key_sizes_{params_name}_bsk");
write_result(&mut file, &test_name, bsk_size);
write_to_json(&test_name, *params, *params_name, "BSK", &operator);
println!(
"Element in BSK: {}, size in bytes: {}",
sks.bootstrapping_key_size_elements(),

View File

@@ -1,3 +1,7 @@
#[path = "../benches/utilities.rs"]
mod utilities;
use crate::utilities::{write_to_json, OperatorType};
use std::fs::{File, OpenOptions};
use std::io::Write;
use std::path::Path;
@@ -26,13 +30,15 @@ fn client_server_key_sizes(results_file: &Path) {
.open(results_file)
.expect("cannot open results file");
let operator = OperatorType::Atomic;
println!("Generating shortint (ClientKey, ServerKey)");
for (i, params) in shortint_params_vec.iter().enumerate() {
println!(
"Generating [{} / {}] : {}",
i + 1,
shortint_params_vec.len(),
params.name()
params.name().to_lowercase()
);
let keys = KEY_CACHE.get_from_param(*params);
@@ -41,11 +47,11 @@ fn client_server_key_sizes(results_file: &Path) {
// let cks = keys.client_key();
let sks = keys.server_key();
let ksk_size = sks.key_switching_key_size_bytes();
write_result(
&mut file,
&format!("shortint_{}_ksk", params.name().to_lowercase()),
ksk_size,
);
let test_name = format!("shortint_key_sizes_{}_ksk", params.name());
write_result(&mut file, &test_name, ksk_size);
write_to_json(&test_name, *params, params.name(), "KSK", &operator);
println!(
"Element in KSK: {}, size in bytes: {}",
sks.key_switching_key_size_elements(),
@@ -53,11 +59,11 @@ fn client_server_key_sizes(results_file: &Path) {
);
let bsk_size = sks.bootstrapping_key_size_bytes();
write_result(
&mut file,
&format!("shortint_{}_bsk", params.name().to_lowercase()),
bsk_size,
);
let test_name = format!("shortint_key_sizes_{}_bsk", params.name());
write_result(&mut file, &test_name, bsk_size);
write_to_json(&test_name, *params, params.name(), "BSK", &operator);
println!(
"Element in BSK: {}, size in bytes: {}",
sks.bootstrapping_key_size_elements(),

View File

@@ -107,6 +107,18 @@ test('shortint_encrypt_decrypt', (t) => {
let deserialized_sks = Shortint.deserialize_compressed_server_key(serialized_sks);
// No equality tests here, as wasm stores pointers which will always differ
// Encryption using small keys
let params_small = Shortint.get_parameters_small(2, 2);
let cks_small = Shortint.new_client_key(params_small);
let ct_small = Shortint.encrypt_small(cks_small, BigInt(3));
let serialized_ct_small = Shortint.serialize_ciphertext(ct_small);
let deserialized_ct_small = Shortint.deserialize_ciphertext(serialized_ct_small);
let decrypted_small = Shortint.decrypt(cks_small, deserialized_ct_small);
assert.deepStrictEqual(decrypted_small, BigInt(3));
});
test('shortint_compressed_encrypt_decrypt', (t) => {
@@ -124,6 +136,20 @@ test('shortint_compressed_encrypt_decrypt', (t) => {
let decrypted = Shortint.decrypt(deserialized_cks, decompressed_ct);
assert.deepStrictEqual(decrypted, BigInt(3));
// Encryption using small keys
let params_small = Shortint.get_parameters_small(2, 2);
let cks_small = Shortint.new_client_key(params_small);
let ct_small = Shortint.encrypt_compressed_small(cks_small, BigInt(3));
let serialized_ct_small = Shortint.serialize_compressed_ciphertext(ct_small);
let deserialized_ct_small = Shortint.deserialize_compressed_ciphertext(serialized_ct_small);
let decompressed_ct_small = Shortint.decompress_ciphertext(deserialized_ct_small);
let decrypted_small = Shortint.decrypt(cks_small, decompressed_ct_small);
assert.deepStrictEqual(decrypted_small, BigInt(3));
});
test('shortint_public_encrypt_decrypt', (t) => {
@@ -138,6 +164,20 @@ test('shortint_public_encrypt_decrypt', (t) => {
let decrypted = Shortint.decrypt(cks, deserialized_ct);
assert.deepStrictEqual(decrypted, BigInt(3));
// Small
let params_small = Shortint.get_parameters_small(2, 2);
let cks_small = Shortint.new_client_key(params_small);
let pk_small = Shortint.new_public_key_small(cks_small);
let ct_small = Shortint.encrypt_with_public_key(pk_small, BigInt(3));
let serialized_ct_small = Shortint.serialize_ciphertext(ct_small);
let deserialized_ct_small = Shortint.deserialize_ciphertext(serialized_ct_small);
let decrypted_small = Shortint.decrypt(cks_small, deserialized_ct_small);
assert.deepStrictEqual(decrypted_small, BigInt(3));
});
test('shortint_compressed_public_encrypt_decrypt', (t) => {
@@ -155,6 +195,23 @@ test('shortint_compressed_public_encrypt_decrypt', (t) => {
let decrypted = Shortint.decrypt(cks, deserialized_ct);
assert.deepStrictEqual(decrypted, BigInt(1));
// Small
let params_small = Shortint.get_parameters_small(2, 2);
let cks_small = Shortint.new_client_key(params_small);
let pk_small = Shortint.new_compressed_public_key_small(cks_small);
let serialized_pk_small = Shortint.serialize_compressed_public_key(pk_small);
let deserialized_pk_small = Shortint.deserialize_compressed_public_key(serialized_pk_small);
let ct_small = Shortint.encrypt_with_compressed_public_key(deserialized_pk_small, BigInt(1));
let serialized_ct_small = Shortint.serialize_ciphertext(ct_small);
let deserialized_ct_small = Shortint.deserialize_ciphertext(serialized_ct_small);
let decrypted_small = Shortint.decrypt(cks_small, deserialized_ct_small);
assert.deepStrictEqual(decrypted_small, BigInt(1));
});
test('shortint_deterministic_keygen', (t) => {

View File

@@ -55,7 +55,7 @@ impl ClientKey {
/// use tfhe::boolean::prelude::*;
///
/// // Generate the client key and the server key:
/// let (cks, mut sks) = gen_keys();
/// let (cks, sks) = gen_keys();
///
/// // Encryption of one message:
/// let ct = cks.encrypt(true);
@@ -78,7 +78,7 @@ impl ClientKey {
/// use tfhe::boolean::prelude::*;
///
/// // Generate the client key and the server key:
/// let (cks, mut sks) = gen_keys();
/// let (cks, sks) = gen_keys();
///
/// // Encryption of one message:
/// let ct = cks.encrypt_compressed(true);
@@ -103,7 +103,7 @@ impl ClientKey {
/// use tfhe::boolean::prelude::*;
///
/// // Generate the client key and the server key:
/// let (cks, mut sks) = gen_keys();
/// let (cks, sks) = gen_keys();
///
/// // Encryption of one message:
/// let ct = cks.encrypt(true);

View File

@@ -4,8 +4,9 @@ use crate::core_crypto::algorithms::*;
use crate::core_crypto::commons::computation_buffers::ComputationBuffers;
use crate::core_crypto::commons::generators::{DeterministicSeeder, EncryptionRandomGenerator};
use crate::core_crypto::commons::math::random::{ActivatedRandomGenerator, Seeder};
use crate::core_crypto::commons::parameters::CiphertextModulus;
use crate::core_crypto::entities::*;
use crate::core_crypto::fft_impl::math::fft::Fft;
use crate::core_crypto::fft_impl::fft64::math::fft::Fft;
use serde::{Deserialize, Serialize};
use std::error::Error;
@@ -51,6 +52,7 @@ impl Memory {
let mut accumulator = GlweCiphertextMutView::from_container(
accumulator_elements,
server_key.bootstrapping_key.polynomial_size(),
CiphertextModulus::new_native(),
);
accumulator.get_mut_mask().as_mut().fill(0u32);
@@ -60,9 +62,11 @@ impl Memory {
let accumulator = GlweCiphertextView::from_container(
accumulator_elements,
server_key.bootstrapping_key.polynomial_size(),
CiphertextModulus::new_native(),
);
let lwe = LweCiphertextMutView::from_container(lwe_elements);
let lwe =
LweCiphertextMutView::from_container(lwe_elements, CiphertextModulus::new_native());
(accumulator, lwe)
}
@@ -153,6 +157,7 @@ impl Bootstrapper {
cks.parameters.pbs_base_log,
cks.parameters.pbs_level,
cks.parameters.glwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.encryption_generator,
);
@@ -192,6 +197,7 @@ impl Bootstrapper {
cks.parameters.ks_base_log,
cks.parameters.ks_level,
cks.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.encryption_generator,
);
@@ -212,6 +218,7 @@ impl Bootstrapper {
cks.parameters.pbs_base_log,
cks.parameters.pbs_level,
cks.parameters.glwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.seeder,
);
@@ -222,6 +229,7 @@ impl Bootstrapper {
cks.parameters.pbs_base_log,
cks.parameters.pbs_level,
cks.parameters.glwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.seeder,
);
@@ -234,6 +242,7 @@ impl Bootstrapper {
cks.parameters.ks_base_log,
cks.parameters.ks_level,
cks.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.seeder,
);
@@ -277,6 +286,7 @@ impl Bootstrapper {
Ok(LweCiphertext::from_container(
buffer_after_pbs.as_ref().to_owned(),
input.ciphertext_modulus(),
))
}
@@ -292,6 +302,7 @@ impl Bootstrapper {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
input.ciphertext_modulus(),
);
keyswitch_lwe_ciphertext(&server_key.key_switching_key, input, &mut output);

View File

@@ -18,6 +18,9 @@ use crate::core_crypto::commons::math::random::{ActivatedRandomGenerator, Seeder
use crate::core_crypto::commons::parameters::*;
use crate::core_crypto::seeders::new_seeder;
#[cfg(test)]
mod tests;
pub(crate) trait BinaryGatesEngine<L, R, K> {
fn and(&mut self, ct_left: L, ct_right: R, server_key: &K) -> Ciphertext;
fn nand(&mut self, ct_left: L, ct_right: R, server_key: &K) -> Ciphertext;
@@ -122,6 +125,7 @@ impl BooleanEngine {
&client_key.lwe_secret_key,
zero_encryption_count,
client_key.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.encryption_generator,
);
@@ -130,6 +134,7 @@ impl BooleanEngine {
&client_key.lwe_secret_key,
zero_encryption_count,
client_key.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.encryption_generator,
);
@@ -156,6 +161,7 @@ impl BooleanEngine {
&cks.lwe_secret_key,
plain,
cks.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.encryption_generator,
);
@@ -175,6 +181,7 @@ impl BooleanEngine {
&cks.lwe_secret_key,
plain,
cks.parameters.lwe_modular_std_dev,
CiphertextModulus::new_native(),
&mut self.bootstrapper.seeder,
);
@@ -189,7 +196,11 @@ impl BooleanEngine {
Plaintext(PLAINTEXT_FALSE)
};
let mut output = LweCiphertext::new(0u32, pks.parameters.lwe_dimension.to_lwe_size());
let mut output = LweCiphertext::new(
0u32,
pks.parameters.lwe_dimension.to_lwe_size(),
CiphertextModulus::new_native(),
);
// encryption
encrypt_lwe_ciphertext_with_public_key(
@@ -249,6 +260,37 @@ impl Default for BooleanEngine {
}
impl BooleanEngine {
/// Replace the thread_local BooleanEngine
///
/// `new_engine` will replace the already_existing
/// `thread_local` engine.
///
/// # Example
///
/// ```rust
/// use tfhe::boolean::engine::BooleanEngine;
/// use tfhe::core_crypto::commons::generators::DeterministicSeeder;
/// use tfhe::core_crypto::commons::math::random::Seed;
/// use tfhe::core_crypto::prelude::ActivatedRandomGenerator;
///
/// // WARNING: Using a deterministic seed is not recommended
/// // as it renders the random generation insecure
///
/// let deterministic_seed = Seed(0);
///
/// let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(deterministic_seed);
/// let boolean_engine = BooleanEngine::new_from_seeder(&mut seeder);
/// BooleanEngine::replace_thread_local(boolean_engine);
///
/// // This uses the engine create earlier
/// let (cks, sks) = tfhe::boolean::gen_keys();
/// ```
pub fn replace_thread_local(new_engine: Self) {
Self::with_thread_local_mut(|local_engine| {
let _ = std::mem::replace(local_engine, new_engine);
})
}
pub fn new() -> Self {
let mut root_seeder = new_seeder();
@@ -292,6 +334,7 @@ impl BooleanEngine {
.input_lwe_dimension()
.to_lwe_size(),
plain,
CiphertextModulus::new_native(),
)
}
}
@@ -338,7 +381,7 @@ impl BooleanEngine {
};
}
// convert inputs into LweCiphertext32
// convert inputs into LweCiphertextOwned<u32>
let ct_then_ct = self.convert_into_lwe_ciphertext_32(ct_then, server_key);
let ct_else_ct = self.convert_into_lwe_ciphertext_32(ct_else, server_key);
@@ -348,6 +391,7 @@ impl BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_condition_ct.ciphertext_modulus(),
);
let buffer_lwe_before_pbs = &mut buffer_lwe_before_pbs_o;
@@ -413,6 +457,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;
@@ -455,6 +500,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;
@@ -497,6 +543,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;
@@ -540,6 +587,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;
@@ -581,6 +629,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;
@@ -625,6 +674,7 @@ impl BinaryGatesEngine<&Ciphertext, &Ciphertext, ServerKey> for BooleanEngine {
.bootstrapping_key
.input_lwe_dimension()
.to_lwe_size(),
ct_left_ct.ciphertext_modulus(),
);
let bootstrapper = &mut self.bootstrapper;

View File

@@ -0,0 +1,54 @@
#[test]
fn test_replacing_thread_local_engine() {
use crate::boolean::engine::BooleanEngine;
use crate::core_crypto::commons::generators::DeterministicSeeder;
use crate::core_crypto::commons::math::random::Seed;
use crate::core_crypto::prelude::ActivatedRandomGenerator;
let deterministic_seed = Seed(0);
// We change the engine in the main thread
// then generate a client key, and then encrypt
// a boolean value and serialize it to compare
// it with other ciphertext
let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(deterministic_seed);
let boolean_engine = BooleanEngine::new_from_seeder(&mut seeder);
BooleanEngine::replace_thread_local(boolean_engine);
let (cks, _) = crate::boolean::gen_keys();
let ct = cks.encrypt(false);
let main_thread_data = bincode::serialize(&ct).unwrap();
// In this thread, we don't change the engine
// and so we expect the encrypted value to be
// different compared with the one from the main thread
//
// This also "proves" that a thread is not affected
// by engine changes from other thread as engines are
// thread_local
let second_thread_data = std::thread::spawn(|| {
let (cks, _) = crate::boolean::gen_keys();
let ct = cks.encrypt(false);
bincode::serialize(&ct).unwrap()
})
.join()
.unwrap();
assert_ne!(second_thread_data, main_thread_data);
// In this thread, we change the engine,
// with a new engine that has the same seed
// as the one in the main thread
// So we expect the encrypted value to be the same
// compared with the one from the main thread
let third_thread_data = std::thread::spawn(move || {
let mut seeder = DeterministicSeeder::<ActivatedRandomGenerator>::new(deterministic_seed);
let boolean_engine = BooleanEngine::new_from_seeder(&mut seeder);
BooleanEngine::replace_thread_local(boolean_engine);
let (cks, _) = crate::boolean::gen_keys();
let ct = cks.encrypt(false);
bincode::serialize(&ct).unwrap()
})
.join()
.unwrap();
assert_eq!(third_thread_data, main_thread_data);
}

View File

@@ -8,7 +8,7 @@ use crate::core_crypto::entities::*;
use serde::{Deserialize, Serialize};
/// A structure containing a public key.
#[derive(Clone, Serialize, Deserialize)]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PublicKey {
pub(crate) lwe_public_key: LwePublicKeyOwned<u32>,
pub(crate) parameters: BooleanParameters,
@@ -51,7 +51,7 @@ impl PublicKey {
/// use tfhe::boolean::prelude::*;
///
/// // Generate the client key and the server key:
/// let (cks, mut sks) = gen_keys();
/// let (cks, sks) = gen_keys();
///
/// let pks = PublicKey::new(&cks);
/// # }

View File

@@ -0,0 +1,35 @@
use crate::high_level_api::prelude::*;
use std::ops::{BitAnd, BitOr, BitXor, Not};
pub struct FheBool(crate::high_level_api::FheBool);
impl_destroy_on_type!(FheBool);
impl_clone_on_type!(FheBool);
impl_binary_fn_on_type!(FheBool => bitand, bitor, bitxor);
impl_unary_fn_on_type!(FheBool => not);
impl_decrypt_on_type!(FheBool, bool);
impl_try_encrypt_trivial_on_type!(FheBool{crate::high_level_api::FheBool}, bool);
impl_try_encrypt_with_client_key_on_type!(FheBool{crate::high_level_api::FheBool}, bool);
impl_try_encrypt_with_public_key_on_type!(FheBool{crate::high_level_api::FheBool}, bool);
pub struct CompressedFheBool(crate::high_level_api::CompressedFheBool);
impl_destroy_on_type!(CompressedFheBool);
impl_clone_on_type!(CompressedFheBool);
impl_serialize_deserialize_on_type!(CompressedFheBool);
#[no_mangle]
pub unsafe extern "C" fn compressed_fhe_bool_decompress(
sself: *const CompressedFheBool,
result: *mut *mut FheBool,
) -> ::std::os::raw::c_int {
crate::c_api::utils::catch_panic(|| {
let compressed = crate::c_api::utils::get_ref_checked(sself).unwrap();
let decompressed_inner = compressed.0.clone().into();
*result = Box::into_raw(Box::new(FheBool(decompressed_inner)));
})
}

View File

@@ -0,0 +1,120 @@
use crate::c_api::utils::*;
use std::os::raw::c_int;
pub struct ConfigBuilder(pub(in crate::c_api) crate::high_level_api::ConfigBuilder);
pub struct Config(pub(in crate::c_api) crate::high_level_api::Config);
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 {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let inner_builder = crate::high_level_api::ConfigBuilder::all_disabled();
*result = Box::into_raw(Box::new(ConfigBuilder(inner_builder)));
})
}
#[no_mangle]
pub unsafe extern "C" fn config_builder_clone(
input: *const ConfigBuilder,
result: *mut *mut ConfigBuilder,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let cloned = get_ref_checked(input).unwrap().0.clone();
*result = Box::into_raw(Box::new(ConfigBuilder(cloned)));
})
}
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!(uint8);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint8 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint10);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint10 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint12);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint12 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint14);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint14 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint16);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint16 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint32);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint32 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint64);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint64 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint128);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint128 @small);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint256);
#[cfg(feature = "integer")]
define_enable_default_fn!(uint256 @small);
/// Takes ownership of the builder
#[no_mangle]
pub unsafe extern "C" fn config_builder_build(
builder: *mut ConfigBuilder,
result: *mut *mut Config,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let config = Box::from_raw(builder).0.build();
*result = Box::into_raw(Box::new(Config(config)));
})
}

View File

@@ -0,0 +1,288 @@
use crate::c_api::high_level_api::keys::{ClientKey, PublicKey};
use crate::high_level_api::prelude::*;
use std::ops::{
Add, AddAssign, BitAnd, BitAndAssign, BitOr, BitOrAssign, BitXor, BitXorAssign, Mul, MulAssign,
Neg, Shl, ShlAssign, Shr, ShrAssign, Sub, SubAssign,
};
use crate::c_api::high_level_api::u256::U256;
use crate::c_api::utils::*;
use std::os::raw::c_int;
/// Implement C functions for all the operations supported by a integer type,
/// which should also be accessible from C API
macro_rules! impl_operations_for_integer_type {
(
name: $name:ident,
clear_scalar_type: $clear_scalar_type:ty
) => {
impl_binary_fn_on_type_mut!($name => add, sub, mul, bitand, bitor, bitxor, eq, ge, gt, le, lt, min, max);
impl_binary_assign_fn_on_type_mut!($name => add_assign, sub_assign, mul_assign, bitand_assign, bitor_assign, bitxor_assign);
impl_scalar_binary_fn_on_type_mut!($name, $clear_scalar_type => add, sub, mul, shl, shr);
impl_scalar_binary_assign_fn_on_type_mut!($name, $clear_scalar_type => add_assign, sub_assign, mul_assign, shl_assign, shr_assign);
impl_unary_fn_on_type_mut!($name => neg);
};
}
/// Creates a type that will act as an opaque wrapper
/// aroung a tfhe integer.
///
/// It also implements binary operations for this wrapper type
macro_rules! create_integer_wrapper_type {
(
name: $name:ident,
clear_scalar_type: $clear_scalar_type:ty
) => {
pub struct $name($crate::high_level_api::$name);
impl_destroy_on_type!($name);
impl_operations_for_integer_type!(name: $name, clear_scalar_type: $clear_scalar_type);
impl_serialize_deserialize_on_type!($name);
impl_clone_on_type!($name);
// The compressed version of the ciphertext type
::paste::paste! {
pub struct [<Compressed $name>]($crate::high_level_api::[<Compressed $name>]);
impl_destroy_on_type!([<Compressed $name>]);
impl_clone_on_type!([<Compressed $name>]);
impl_serialize_deserialize_on_type!([<Compressed $name>]);
#[no_mangle]
pub unsafe extern "C" fn [<compressed_ $name:snake _decompress>](
sself: *const [<Compressed $name>],
result: *mut *mut $name,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let compressed = $crate::c_api::utils::get_ref_checked(sself).unwrap();
let decompressed_inner = compressed.0.clone().into();
*result = Box::into_raw(Box::new($name(decompressed_inner)));
})
}
}
};
}
create_integer_wrapper_type!(name: FheUint8, clear_scalar_type: u8);
create_integer_wrapper_type!(name: FheUint10, clear_scalar_type: u16);
create_integer_wrapper_type!(name: FheUint12, clear_scalar_type: u16);
create_integer_wrapper_type!(name: FheUint14, clear_scalar_type: u16);
create_integer_wrapper_type!(name: FheUint16, clear_scalar_type: u16);
create_integer_wrapper_type!(name: FheUint32, clear_scalar_type: u32);
create_integer_wrapper_type!(name: FheUint64, clear_scalar_type: u64);
create_integer_wrapper_type!(name: FheUint128, clear_scalar_type: u64);
create_integer_wrapper_type!(name: FheUint256, clear_scalar_type: u64);
impl_decrypt_on_type!(FheUint8, u8);
impl_try_encrypt_trivial_on_type!(FheUint8{crate::high_level_api::FheUint8}, u8);
impl_try_encrypt_with_client_key_on_type!(FheUint8{crate::high_level_api::FheUint8}, u8);
impl_try_encrypt_with_public_key_on_type!(FheUint8{crate::high_level_api::FheUint8}, u8);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint8{crate::high_level_api::CompressedFheUint8}, u8);
impl_decrypt_on_type!(FheUint10, u16);
impl_try_encrypt_trivial_on_type!(FheUint10{crate::high_level_api::FheUint10}, u16);
impl_try_encrypt_with_client_key_on_type!(FheUint10{crate::high_level_api::FheUint10}, u16);
impl_try_encrypt_with_public_key_on_type!(FheUint10{crate::high_level_api::FheUint10}, u16);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint10{crate::high_level_api::CompressedFheUint10}, u16);
impl_decrypt_on_type!(FheUint12, u16);
impl_try_encrypt_trivial_on_type!(FheUint12{crate::high_level_api::FheUint12}, u16);
impl_try_encrypt_with_client_key_on_type!(FheUint12{crate::high_level_api::FheUint12}, u16);
impl_try_encrypt_with_public_key_on_type!(FheUint12{crate::high_level_api::FheUint12}, u16);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint12{crate::high_level_api::CompressedFheUint12}, u16);
impl_decrypt_on_type!(FheUint14, u16);
impl_try_encrypt_trivial_on_type!(FheUint14{crate::high_level_api::FheUint14}, u16);
impl_try_encrypt_with_client_key_on_type!(FheUint14{crate::high_level_api::FheUint14}, u16);
impl_try_encrypt_with_public_key_on_type!(FheUint14{crate::high_level_api::FheUint14}, u16);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint14{crate::high_level_api::CompressedFheUint14}, u16);
impl_decrypt_on_type!(FheUint16, u16);
impl_try_encrypt_trivial_on_type!(FheUint16{crate::high_level_api::FheUint16}, u16);
impl_try_encrypt_with_client_key_on_type!(FheUint16{crate::high_level_api::FheUint16}, u16);
impl_try_encrypt_with_public_key_on_type!(FheUint16{crate::high_level_api::FheUint16}, u16);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint16{crate::high_level_api::CompressedFheUint16}, u16);
impl_decrypt_on_type!(FheUint32, u32);
impl_try_encrypt_trivial_on_type!(FheUint32{crate::high_level_api::FheUint32}, u32);
impl_try_encrypt_with_client_key_on_type!(FheUint32{crate::high_level_api::FheUint32}, u32);
impl_try_encrypt_with_public_key_on_type!(FheUint32{crate::high_level_api::FheUint32}, u32);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint32{crate::high_level_api::CompressedFheUint32}, u32);
impl_decrypt_on_type!(FheUint64, u64);
impl_try_encrypt_trivial_on_type!(FheUint64{crate::high_level_api::FheUint64}, u64);
impl_try_encrypt_with_client_key_on_type!(FheUint64{crate::high_level_api::FheUint64}, u64);
impl_try_encrypt_with_public_key_on_type!(FheUint64{crate::high_level_api::FheUint64}, u64);
impl_try_encrypt_with_client_key_on_type!(CompressedFheUint64{crate::high_level_api::CompressedFheUint64}, u64);
#[no_mangle]
pub unsafe extern "C" fn fhe_uint128_try_encrypt_trivial_u128(
low_word: u64,
high_word: u64,
result: *mut *mut FheUint128,
) -> c_int {
catch_panic(|| {
let value = ((high_word as u128) << 64u128) | low_word as u128;
let inner = <crate::high_level_api::FheUint128>::try_encrypt_trivial(value).unwrap();
*result = Box::into_raw(Box::new(FheUint128(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint128_try_encrypt_with_client_key_u128(
low_word: u64,
high_word: u64,
client_key: *const ClientKey,
result: *mut *mut FheUint128,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let value = ((high_word as u128) << 64u128) | low_word as u128;
let inner = <crate::high_level_api::FheUint128>::try_encrypt(value, &client_key.0).unwrap();
*result = Box::into_raw(Box::new(FheUint128(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn compressed_fhe_uint128_try_encrypt_with_client_key_u128(
low_word: u64,
high_word: u64,
client_key: *const ClientKey,
result: *mut *mut CompressedFheUint128,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let value = ((high_word as u128) << 64u128) | low_word as u128;
let inner =
<crate::high_level_api::CompressedFheUint128>::try_encrypt(value, &client_key.0)
.unwrap();
*result = Box::into_raw(Box::new(CompressedFheUint128(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint128_try_encrypt_with_public_key_u128(
low_word: u64,
high_word: u64,
public_key: *const PublicKey,
result: *mut *mut FheUint128,
) -> c_int {
catch_panic(|| {
let public_key = get_ref_checked(public_key).unwrap();
let value = ((high_word as u128) << 64u128) | low_word as u128;
let inner = <crate::high_level_api::FheUint128>::try_encrypt(value, &public_key.0).unwrap();
*result = Box::into_raw(Box::new(FheUint128(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint128_decrypt(
encrypted_value: *const FheUint128,
client_key: *const ClientKey,
low_word: *mut u64,
high_word: *mut u64,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let encrypted_value = get_ref_checked(encrypted_value).unwrap();
let inner: u128 = encrypted_value.0.decrypt(&client_key.0);
*low_word = (inner & (u64::MAX as u128)) as u64;
*high_word = (inner >> 64) as u64;
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint256_try_encrypt_trivial_u256(
value: *const U256,
result: *mut *mut FheUint256,
) -> c_int {
catch_panic(|| {
let inner = <crate::high_level_api::FheUint256>::try_encrypt_trivial((*value).0).unwrap();
*result = Box::into_raw(Box::new(FheUint256(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint256_try_encrypt_with_client_key_u256(
value: *const U256,
client_key: *const ClientKey,
result: *mut *mut FheUint256,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let inner =
<crate::high_level_api::FheUint256>::try_encrypt((*value).0, &client_key.0).unwrap();
*result = Box::into_raw(Box::new(FheUint256(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn compressed_fhe_uint256_try_encrypt_with_client_key_u256(
value: *const U256,
client_key: *const ClientKey,
result: *mut *mut CompressedFheUint256,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let inner =
<crate::high_level_api::CompressedFheUint256>::try_encrypt((*value).0, &client_key.0)
.unwrap();
*result = Box::into_raw(Box::new(CompressedFheUint256(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint256_try_encrypt_with_public_key_u256(
value: *const U256,
public_key: *const PublicKey,
result: *mut *mut FheUint256,
) -> c_int {
catch_panic(|| {
let public_key = get_ref_checked(public_key).unwrap();
let inner =
<crate::high_level_api::FheUint256>::try_encrypt((*value).0, &public_key.0).unwrap();
*result = Box::into_raw(Box::new(FheUint256(inner)));
})
}
#[no_mangle]
pub unsafe extern "C" fn fhe_uint256_decrypt(
encrypted_value: *const FheUint256,
client_key: *const ClientKey,
result: *mut *mut U256,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let encrypted_value = get_ref_checked(encrypted_value).unwrap();
let inner: crate::integer::U256 = encrypted_value.0.decrypt(&client_key.0);
*result = Box::into_raw(Box::new(U256(inner)));
})
}

View File

@@ -0,0 +1,71 @@
use crate::c_api::utils::*;
use std::os::raw::c_int;
pub struct ClientKey(pub(crate) crate::high_level_api::ClientKey);
pub struct PublicKey(pub(crate) crate::high_level_api::PublicKey);
pub struct ServerKey(pub(crate) crate::high_level_api::ServerKey);
impl_destroy_on_type!(ClientKey);
impl_destroy_on_type!(PublicKey);
impl_destroy_on_type!(ServerKey);
impl_serialize_deserialize_on_type!(ClientKey);
impl_serialize_deserialize_on_type!(PublicKey);
impl_serialize_deserialize_on_type!(ServerKey);
#[no_mangle]
pub unsafe extern "C" fn generate_keys(
config: *mut super::config::Config,
result_client_key: *mut *mut ClientKey,
result_server_key: *mut *mut ServerKey,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result_client_key).unwrap();
check_ptr_is_non_null_and_aligned(result_server_key).unwrap();
*result_client_key = std::ptr::null_mut();
*result_server_key = std::ptr::null_mut();
let config = Box::from_raw(config);
let (cks, sks) = crate::high_level_api::generate_keys(config.0);
*result_client_key = Box::into_raw(Box::new(ClientKey(cks)));
*result_server_key = Box::into_raw(Box::new(ServerKey(sks)));
})
}
#[no_mangle]
pub unsafe extern "C" fn set_server_key(server_key: *const ServerKey) -> c_int {
catch_panic(|| {
let server_key = get_ref_checked(server_key).unwrap();
let cloned = server_key.0.clone();
crate::high_level_api::set_server_key(cloned);
})
}
/// result can be null
#[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)))
}
})
}
#[no_mangle]
pub unsafe extern "C" fn public_key_new(
client_key: *const ClientKey,
result_public_key: *mut *mut PublicKey,
) -> c_int {
catch_panic(|| {
let client_key = get_ref_checked(client_key).unwrap();
let inner = crate::high_level_api::PublicKey::new(&client_key.0);
*result_public_key = Box::into_raw(Box::new(PublicKey(inner)));
})
}

View File

@@ -0,0 +1,10 @@
#[macro_use]
mod utils;
#[cfg(feature = "boolean")]
pub mod booleans;
pub mod config;
#[cfg(feature = "integer")]
pub mod integers;
pub mod keys;
#[cfg(feature = "integer")]
pub mod u256;

View File

@@ -0,0 +1,115 @@
use crate::c_api::utils::*;
use std::os::raw::c_int;
pub struct U256(pub(in crate::c_api) crate::integer::U256);
impl_destroy_on_type!(U256);
/// w0 is the least significant, w4 is the most significant
#[no_mangle]
pub unsafe extern "C" fn u256_from_u64_words(
w0: u64,
w1: u64,
w2: u64,
w3: u64,
result: *mut *mut U256,
) -> c_int {
catch_panic(|| {
let inner = crate::integer::U256::from((w0, w1, w2, w3));
*result = Box::into_raw(Box::new(U256(inner)));
})
}
/// w0 is the least significant, w4 is the most significant
#[no_mangle]
pub unsafe extern "C" fn u256_to_u64_words(
input: *const U256,
w0: *mut u64,
w1: *mut u64,
w2: *mut u64,
w3: *mut u64,
) -> c_int {
catch_panic(|| {
let input = get_ref_checked(input).unwrap();
check_ptr_is_non_null_and_aligned(w0).unwrap();
check_ptr_is_non_null_and_aligned(w1).unwrap();
check_ptr_is_non_null_and_aligned(w2).unwrap();
check_ptr_is_non_null_and_aligned(w3).unwrap();
*w0 = input.0 .0[0];
*w1 = input.0 .0[1];
*w2 = input.0 .0[2];
*w3 = input.0 .0[3];
})
}
/// Creates a U256 from little endian bytes
///
/// len must be 32
#[no_mangle]
pub unsafe extern "C" fn u256_from_little_endian_bytes(
input: *const u8,
len: usize,
result: *mut *mut U256,
) -> c_int {
catch_panic(|| {
let mut inner = crate::integer::U256::default();
let input = std::slice::from_raw_parts(input, len);
inner.copy_from_le_byte_slice(input);
*result = Box::into_raw(Box::new(U256(inner)));
})
}
/// Creates a U256 from big endian bytes
///
/// len must be 32
#[no_mangle]
pub unsafe extern "C" fn u256_from_big_endian_bytes(
input: *const u8,
len: usize,
result: *mut *mut U256,
) -> c_int {
catch_panic(|| {
let mut inner = crate::integer::U256::default();
let input = std::slice::from_raw_parts(input, len);
inner.copy_from_be_byte_slice(input);
*result = Box::into_raw(Box::new(U256(inner)));
})
}
/// len must be 32
#[no_mangle]
pub unsafe extern "C" fn u256_little_endian_bytes(
input: *const U256,
result: *mut u8,
len: usize,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let input = get_ref_checked(input).unwrap();
let bytes = std::slice::from_raw_parts_mut(result, len);
input.0.copy_to_le_byte_slice(bytes);
})
}
/// len must be 32
#[no_mangle]
pub unsafe extern "C" fn u256_big_endian_bytes(
input: *const U256,
result: *mut u8,
len: usize,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let input = get_ref_checked(input).unwrap();
let bytes = std::slice::from_raw_parts_mut(result, len);
input.0.copy_to_be_byte_slice(bytes);
})
}

View File

@@ -0,0 +1,329 @@
macro_rules! impl_destroy_on_type {
($wrapper_type:ty) => {
::paste::paste! {
#[no_mangle]
#[doc = "ptr can be null (no-op in that case)"]
pub unsafe extern "C" fn [<$wrapper_type:snake _destroy>](
ptr: *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
if (!ptr.is_null()) {
$crate::c_api::utils::check_ptr_is_non_null_and_aligned(ptr).unwrap();
drop(Box::from_raw(ptr));
}
})
}
}
};
}
macro_rules! impl_try_encrypt_with_client_key_on_type {
($wrapper_type:ty{$wrapped_type:ty}, $input_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _try_encrypt_with_client_key_ $input_type:snake>](
value: $input_type,
client_key: *const $crate::c_api::high_level_api::keys::ClientKey,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let client_key = $crate::c_api::utils::get_ref_checked(client_key).unwrap();
let inner = <$wrapped_type>::try_encrypt(value, &client_key.0).unwrap();
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
};
}
macro_rules! impl_try_encrypt_with_public_key_on_type {
($wrapper_type:ty{$wrapped_type:ty}, $input_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _try_encrypt_with_public_key_ $input_type:snake>](
value: $input_type,
public_key: *const $crate::c_api::high_level_api::keys::PublicKey,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let public_key = $crate::c_api::utils::get_ref_checked(public_key).unwrap();
let inner = <$wrapped_type>::try_encrypt(value, &public_key.0).unwrap();
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
};
}
macro_rules! impl_try_encrypt_trivial_on_type {
($wrapper_type:ty{$wrapped_type:ty}, $input_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _try_encrypt_trivial_ $input_type:snake>](
value: $input_type,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let inner = <$wrapped_type>::try_encrypt_trivial(value).unwrap();
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
};
}
macro_rules! impl_decrypt_on_type {
($wrapper_type:ty, $output_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _decrypt>](
encrypted_value: *const $wrapper_type,
client_key: *const $crate::c_api::high_level_api::keys::ClientKey,
result: *mut $output_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let client_key = $crate::c_api::utils::get_ref_checked(client_key).unwrap();
let encrypted_value = $crate::c_api::utils::get_ref_checked(encrypted_value).unwrap();
*result = encrypted_value.0.decrypt(&client_key.0);
})
}
}
};
}
macro_rules! impl_clone_on_type {
($wrapper_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _clone>](
sself: *const $wrapper_type,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
$crate::c_api::utils::check_ptr_is_non_null_and_aligned(result).unwrap();
let wrapper = $crate::c_api::utils::get_ref_checked(sself).unwrap();
let heap_allocated_object = Box::new($wrapper_type(wrapper.0.clone()));
*result = Box::into_raw(heap_allocated_object);
})
}
}
};
}
macro_rules! impl_serialize_deserialize_on_type {
($wrapper_type:ty) => {
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _serialize>](
sself: *const $wrapper_type,
result: *mut $crate::c_api::buffer::Buffer,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
$crate::c_api::utils::check_ptr_is_non_null_and_aligned(result).unwrap();
let wrapper = $crate::c_api::utils::get_ref_checked(sself).unwrap();
let buffer: $crate::c_api::buffer::Buffer = bincode::serialize(&wrapper.0)
.unwrap()
.into();
*result = buffer;
})
}
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _deserialize>](
buffer_view: $crate::c_api::buffer::BufferView,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
$crate::c_api::utils::check_ptr_is_non_null_and_aligned(result).unwrap();
// First fill the result with a null ptr so that if we fail and the return code is not
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let object = bincode::deserialize(buffer_view.into()).unwrap();
let heap_allocated_object = Box::new($wrapper_type(object));
*result = Box::into_raw(heap_allocated_object);
})
}
}
};
}
macro_rules! impl_binary_fn_on_type {
($wrapper_type:ty => $($binary_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _ $binary_fn_name>](
lhs: *const $wrapper_type,
rhs: *const $wrapper_type,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_ref_checked(lhs).unwrap();
let rhs = $crate::c_api::utils::get_ref_checked(rhs).unwrap();
let inner = (&lhs.0).$binary_fn_name(&rhs.0);
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
)*
};
}
macro_rules! impl_unary_fn_on_type {
($wrapper_type:ty => $($unary_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _ $unary_fn_name>](
lhs: *const $wrapper_type,
result: *mut *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_ref_checked(lhs).unwrap();
let inner = (&lhs.0).$unary_fn_name();
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
)*
};
}
// Meant for types on which makes use of interior mutability
#[cfg(feature = "integer")]
macro_rules! impl_unary_fn_on_type_mut {
($wrapper_type:ty => $($unary_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _ $unary_fn_name>](
lhs: *mut $wrapper_type,
result: *mut *mut $wrapper_type,
) -> c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_mut_checked(lhs).unwrap();
let inner = (&lhs.0).$unary_fn_name();
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
)*
};
}
// Meant for types on which makes use of interior mutability
#[cfg(feature = "integer")]
macro_rules! impl_binary_fn_on_type_mut {
($wrapper_type:ty => $($binary_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _ $binary_fn_name>](
lhs: *mut $wrapper_type,
rhs: *mut $wrapper_type,
result: *mut *mut $wrapper_type,
) -> c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_mut_checked(lhs).unwrap();
let rhs = $crate::c_api::utils::get_mut_checked(rhs).unwrap();
let inner = (&lhs.0).$binary_fn_name(&rhs.0);
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
)*
};
}
// Meant for types on which makes use of interior mutability
#[cfg(feature = "integer")]
macro_rules! impl_binary_assign_fn_on_type_mut {
($wrapper_type:ty => $($binary_assign_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _ $binary_assign_fn_name>](
lhs: *mut $wrapper_type,
rhs: *mut $wrapper_type,
) -> ::std::os::raw::c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_mut_checked(lhs).unwrap();
let rhs = $crate::c_api::utils::get_mut_checked(rhs).unwrap();
lhs.0.$binary_assign_fn_name(&rhs.0);
})
}
}
)*
};
}
// Meant for types on which makes use of interior mutability
#[cfg(feature = "integer")]
macro_rules! impl_scalar_binary_fn_on_type_mut {
($wrapper_type:ty, $scalar_type:ty => $($binary_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _scalar_ $binary_fn_name>](
lhs: *mut $wrapper_type,
rhs: $scalar_type,
result: *mut *mut $wrapper_type,
) -> c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_mut_checked(lhs).unwrap();
let inner = (&lhs.0).$binary_fn_name(rhs);
*result = Box::into_raw(Box::new($wrapper_type(inner)));
})
}
}
)*
};
}
// Meant for types on which makes use of interior mutability
#[cfg(feature = "integer")]
macro_rules! impl_scalar_binary_assign_fn_on_type_mut {
($wrapper_type:ty, $scalar_type:ty => $($binary_assign_fn_name:ident),* $(,)?) => {
$(
::paste::paste! {
#[no_mangle]
pub unsafe extern "C" fn [<$wrapper_type:snake _scalar_ $binary_assign_fn_name>](
lhs: *mut $wrapper_type,
rhs: $scalar_type,
) -> c_int {
$crate::c_api::utils::catch_panic(|| {
let lhs = $crate::c_api::utils::get_mut_checked(lhs).unwrap();
lhs.0.$binary_assign_fn_name(rhs);
})
}
}
)*
};
}

View File

@@ -2,6 +2,8 @@
#[cfg(feature = "boolean-c-api")]
pub mod boolean;
pub mod buffer;
#[cfg(feature = "high-level-c-api")]
pub mod high_level_api;
#[cfg(feature = "shortint-c-api")]
pub mod shortint;
pub(crate) mod utils;

View File

@@ -4,10 +4,50 @@ use std::os::raw::c_int;
use crate::shortint;
pub struct ShortintCiphertext(pub(in crate::c_api) shortint::ciphertext::Ciphertext);
pub struct ShortintCompressedCiphertext(
pub(in crate::c_api) shortint::ciphertext::CompressedCiphertext,
);
#[derive(serde::Serialize, serde::Deserialize)]
pub(in crate::c_api) enum ShortintCiphertextInner {
Big(shortint::ciphertext::CiphertextBig),
Small(shortint::ciphertext::CiphertextSmall),
}
impl From<shortint::ciphertext::CiphertextBig> for ShortintCiphertextInner {
fn from(value: shortint::ciphertext::CiphertextBig) -> Self {
ShortintCiphertextInner::Big(value)
}
}
impl From<shortint::ciphertext::CiphertextSmall> for ShortintCiphertextInner {
fn from(value: shortint::ciphertext::CiphertextSmall) -> Self {
ShortintCiphertextInner::Small(value)
}
}
pub struct ShortintCiphertext(pub(in crate::c_api) ShortintCiphertextInner);
#[derive(serde::Serialize, serde::Deserialize)]
pub(in crate::c_api) enum ShortintCompressedCiphertextInner {
Big(shortint::ciphertext::CompressedCiphertextBig),
Small(shortint::ciphertext::CompressedCiphertextSmall),
}
impl From<shortint::ciphertext::CompressedCiphertextBig> for ShortintCompressedCiphertextInner {
fn from(value: shortint::ciphertext::CompressedCiphertextBig) -> Self {
ShortintCompressedCiphertextInner::Big(value)
}
}
impl From<shortint::ciphertext::CompressedCiphertextSmall> for ShortintCompressedCiphertextInner {
fn from(value: shortint::ciphertext::CompressedCiphertextSmall) -> Self {
ShortintCompressedCiphertextInner::Small(value)
}
}
pub struct ShortintCompressedCiphertext(pub(in crate::c_api) ShortintCompressedCiphertextInner);
#[repr(C)]
pub enum ShortintCiphertextKind {
ShortintCiphertextBig,
ShortintCiphertextSmall,
}
#[no_mangle]
pub unsafe extern "C" fn shortint_ciphertext_set_degree(
@@ -17,7 +57,12 @@ pub unsafe extern "C" fn shortint_ciphertext_set_degree(
catch_panic(|| {
let ciphertext = get_mut_checked(ciphertext).unwrap();
ciphertext.0.degree.0 = degree;
let inner = &mut ciphertext.0;
match inner {
ShortintCiphertextInner::Big(inner_ct) => inner_ct.degree.0 = degree,
ShortintCiphertextInner::Small(inner_ct) => inner_ct.degree.0 = degree,
}
})
}
@@ -31,7 +76,12 @@ pub unsafe extern "C" fn shortint_ciphertext_get_degree(
let ciphertext = get_ref_checked(ciphertext).unwrap();
*result = ciphertext.0.degree.0;
let inner = &ciphertext.0;
*result = match inner {
ShortintCiphertextInner::Big(inner_ct) => inner_ct.degree.0,
ShortintCiphertextInner::Small(inner_ct) => inner_ct.degree.0,
};
})
}
@@ -63,8 +113,7 @@ pub unsafe extern "C" fn shortint_deserialize_ciphertext(
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let ciphertext: shortint::ciphertext::Ciphertext =
bincode::deserialize(buffer_view.into()).unwrap();
let ciphertext = bincode::deserialize(buffer_view.into()).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCiphertext(ciphertext));
@@ -74,7 +123,7 @@ pub unsafe extern "C" fn shortint_deserialize_ciphertext(
#[no_mangle]
pub unsafe extern "C" fn shortint_decompress_ciphertext(
compressed_ciphertext: *mut ShortintCompressedCiphertext,
compressed_ciphertext: *const ShortintCompressedCiphertext,
result: *mut *mut ShortintCiphertext,
) -> c_int {
catch_panic(|| {
@@ -84,9 +133,16 @@ pub unsafe extern "C" fn shortint_decompress_ciphertext(
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let compressed_ciphertext = get_mut_checked(compressed_ciphertext).unwrap();
let compressed_ciphertext = get_ref_checked(compressed_ciphertext).unwrap();
let ciphertext = compressed_ciphertext.0.clone().into();
let ciphertext = match &compressed_ciphertext.0 {
ShortintCompressedCiphertextInner::Big(inner) => {
ShortintCiphertextInner::Big(inner.clone().into())
}
ShortintCompressedCiphertextInner::Small(inner) => {
ShortintCiphertextInner::Small(inner.clone().into())
}
};
let heap_allocated_ciphertext = Box::new(ShortintCiphertext(ciphertext));
@@ -122,7 +178,7 @@ pub unsafe extern "C" fn shortint_deserialize_compressed_ciphertext(
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let ciphertext: shortint::ciphertext::CompressedCiphertext =
let ciphertext: ShortintCompressedCiphertextInner =
bincode::deserialize(buffer_view.into()).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCompressedCiphertext(ciphertext));

View File

@@ -45,8 +45,9 @@ pub unsafe extern "C" fn shortint_client_key_encrypt(
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_ciphertext =
Box::new(ShortintCiphertext(client_key.0.encrypt(value_to_encrypt)));
let heap_allocated_ciphertext = Box::new(ShortintCiphertext(
client_key.0.encrypt(value_to_encrypt).into(),
));
*result = Box::into_raw(heap_allocated_ciphertext);
})
@@ -68,7 +69,56 @@ pub unsafe extern "C" fn shortint_client_key_encrypt_compressed(
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCompressedCiphertext(
client_key.0.encrypt_compressed(value_to_encrypt),
client_key.0.encrypt_compressed(value_to_encrypt).into(),
));
*result = Box::into_raw(heap_allocated_ciphertext);
})
}
#[no_mangle]
pub unsafe extern "C" fn shortint_client_key_encrypt_small(
client_key: *const ShortintClientKey,
value_to_encrypt: u64,
result: *mut *mut ShortintCiphertext,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
// First fill the result with a null ptr so that if we fail and the return code is not
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCiphertext(
client_key.0.encrypt_small(value_to_encrypt).into(),
));
*result = Box::into_raw(heap_allocated_ciphertext);
})
}
#[no_mangle]
pub unsafe extern "C" fn shortint_client_key_encrypt_compressed_small(
client_key: *const ShortintClientKey,
value_to_encrypt: u64,
result: *mut *mut ShortintCompressedCiphertext,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
// First fill the result with a null ptr so that if we fail and the return code is not
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCompressedCiphertext(
client_key
.0
.encrypt_compressed_small(value_to_encrypt)
.into(),
));
*result = Box::into_raw(heap_allocated_ciphertext);
@@ -86,8 +136,16 @@ pub unsafe extern "C" fn shortint_client_key_decrypt(
let client_key = get_ref_checked(client_key).unwrap();
let ciphertext_to_decrypt = get_ref_checked(ciphertext_to_decrypt).unwrap();
let inner = &ciphertext_to_decrypt.0;
*result = client_key.0.decrypt(&ciphertext_to_decrypt.0);
*result = match inner {
super::ciphertext::ShortintCiphertextInner::Big(inner_ct) => {
client_key.0.decrypt(inner_ct)
}
super::ciphertext::ShortintCiphertextInner::Small(inner_ct) => {
client_key.0.decrypt(inner_ct)
}
};
})
}

View File

@@ -3,9 +3,9 @@ use std::os::raw::c_int;
use super::parameters::ShortintParameters;
use super::{
ShortintBivariatePBSAccumulator, ShortintCiphertext, ShortintClientKey,
ShortintBivariatePBSLookupTable, ShortintCiphertext, ShortintClientKey,
ShortintCompressedCiphertext, ShortintCompressedPublicKey, ShortintCompressedServerKey,
ShortintPBSAccumulator, ShortintPublicKey, ShortintServerKey,
ShortintPBSLookupTable, ShortintPublicKey, ShortintServerKey,
};
#[no_mangle]
@@ -92,7 +92,7 @@ pub unsafe extern "C" fn destroy_shortint_compressed_ciphertext(
#[no_mangle]
pub unsafe extern "C" fn destroy_shortint_pbs_accumulator(
pbs_accumulator: *mut ShortintPBSAccumulator,
pbs_accumulator: *mut ShortintPBSLookupTable,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(pbs_accumulator).unwrap();
@@ -103,7 +103,7 @@ pub unsafe extern "C" fn destroy_shortint_pbs_accumulator(
#[no_mangle]
pub unsafe extern "C" fn destroy_shortint_bivariate_pbs_accumulator(
pbs_accumulator: *mut ShortintBivariatePBSAccumulator,
pbs_accumulator: *mut ShortintBivariatePBSLookupTable,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(pbs_accumulator).unwrap();

View File

@@ -10,10 +10,11 @@ use std::os::raw::c_int;
use crate::shortint;
pub use ciphertext::{ShortintCiphertext, ShortintCompressedCiphertext};
pub(in crate::c_api) use ciphertext::ShortintCiphertextInner;
pub use ciphertext::{ShortintCiphertext, ShortintCiphertextKind, ShortintCompressedCiphertext};
pub use client_key::ShortintClientKey;
pub use public_key::{ShortintCompressedPublicKey, ShortintPublicKey};
pub use server_key::pbs::{ShortintBivariatePBSAccumulator, ShortintPBSAccumulator};
pub use server_key::pbs::{ShortintBivariatePBSLookupTable, ShortintPBSLookupTable};
pub use server_key::{ShortintCompressedServerKey, ShortintServerKey};
#[no_mangle]

View File

@@ -7,6 +7,8 @@ use std::os::raw::c_int;
use crate::shortint;
pub const SHORTINT_NATIVE_MODULUS: u64 = 0;
pub struct ShortintParameters(pub(in crate::c_api) shortint::parameters::Parameters);
#[no_mangle]
@@ -67,6 +69,32 @@ pub unsafe extern "C" fn shortint_get_parameters(
})
}
#[no_mangle]
pub unsafe extern "C" fn shortint_get_parameters_small(
message_bits: u32,
carry_bits: u32,
result: *mut *mut ShortintParameters,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let params: Option<_> = match (message_bits, carry_bits) {
(1, 1) => Some(crate::shortint::parameters::PARAM_SMALL_MESSAGE_1_CARRY_1),
(2, 2) => Some(crate::shortint::parameters::PARAM_SMALL_MESSAGE_2_CARRY_2),
(3, 3) => Some(crate::shortint::parameters::PARAM_SMALL_MESSAGE_3_CARRY_3),
(4, 4) => Some(crate::shortint::parameters::PARAM_SMALL_MESSAGE_4_CARRY_4),
_ => None,
};
match params {
Some(params) => {
let params = Box::new(ShortintParameters(params));
*result = Box::into_raw(params);
}
None => *result = std::ptr::null_mut(),
}
})
}
#[no_mangle]
pub unsafe extern "C" fn shortint_create_parameters(
lwe_dimension: usize,
@@ -85,6 +113,7 @@ pub unsafe extern "C" fn shortint_create_parameters(
cbs_base_log: usize,
message_modulus: usize,
carry_modulus: usize,
modulus_power_of_2_exponent: usize,
result: *mut *mut ShortintParameters,
) -> c_int {
catch_panic(|| {
@@ -112,6 +141,11 @@ pub unsafe extern "C" fn shortint_create_parameters(
cbs_base_log: DecompositionBaseLog(cbs_base_log),
message_modulus: crate::shortint::parameters::MessageModulus(message_modulus),
carry_modulus: crate::shortint::parameters::CarryModulus(carry_modulus),
ciphertext_modulus:
crate::shortint::parameters::CiphertextModulus::try_new_power_of_2(
modulus_power_of_2_exponent,
)
.unwrap(),
}));
*result = Box::into_raw(heap_allocated_parameters);

View File

@@ -7,14 +7,32 @@ use crate::shortint;
use super::{ShortintCiphertext, ShortintClientKey};
pub struct ShortintPublicKey(pub(in crate::c_api) shortint::public_key::PublicKey);
pub struct ShortintCompressedPublicKey(
pub(in crate::c_api) shortint::public_key::CompressedPublicKey,
);
#[repr(C)]
pub enum ShortintPublicKeyKind {
ShortintPublicKeyBig,
ShortintPublicKeySmall,
}
#[derive(serde::Serialize, serde::Deserialize)]
pub(in crate::c_api) enum ShortintPublicKeyInner {
Big(shortint::public_key::PublicKeyBig),
Small(shortint::public_key::PublicKeySmall),
}
pub struct ShortintPublicKey(pub(in crate::c_api) ShortintPublicKeyInner);
#[derive(serde::Serialize, serde::Deserialize)]
pub(in crate::c_api) enum ShortintCompressedPublicKeyInner {
Big(shortint::public_key::CompressedPublicKeyBig),
Small(shortint::public_key::CompressedPublicKeySmall),
}
pub struct ShortintCompressedPublicKey(pub(in crate::c_api) ShortintCompressedPublicKeyInner);
#[no_mangle]
pub unsafe extern "C" fn shortint_gen_public_key(
client_key: *const ShortintClientKey,
public_key_kind: ShortintPublicKeyKind,
result: *mut *mut ShortintPublicKey,
) -> c_int {
catch_panic(|| {
@@ -26,9 +44,16 @@ pub unsafe extern "C" fn shortint_gen_public_key(
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_public_key = Box::new(ShortintPublicKey(
shortint::public_key::PublicKey::new(&client_key.0),
));
let heap_allocated_public_key = match public_key_kind {
ShortintPublicKeyKind::ShortintPublicKeyBig => Box::new(ShortintPublicKey(
ShortintPublicKeyInner::Big(shortint::public_key::PublicKeyBig::new(&client_key.0)),
)),
ShortintPublicKeyKind::ShortintPublicKeySmall => {
Box::new(ShortintPublicKey(ShortintPublicKeyInner::Small(
shortint::public_key::PublicKeySmall::new(&client_key.0),
)))
}
};
*result = Box::into_raw(heap_allocated_public_key);
})
@@ -49,8 +74,14 @@ pub unsafe extern "C" fn shortint_public_key_encrypt(
let public_key = get_ref_checked(public_key).unwrap();
let heap_allocated_ciphertext =
Box::new(ShortintCiphertext(public_key.0.encrypt(value_to_encrypt)));
let heap_allocated_ciphertext = match &public_key.0 {
ShortintPublicKeyInner::Big(inner) => {
Box::new(ShortintCiphertext(inner.encrypt(value_to_encrypt).into()))
}
ShortintPublicKeyInner::Small(inner) => {
Box::new(ShortintCiphertext(inner.encrypt(value_to_encrypt).into()))
}
};
*result = Box::into_raw(heap_allocated_ciphertext);
})
@@ -84,8 +115,7 @@ pub unsafe extern "C" fn shortint_deserialize_public_key(
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let public_key: shortint::public_key::PublicKey =
bincode::deserialize(buffer_view.into()).unwrap();
let public_key: ShortintPublicKeyInner = bincode::deserialize(buffer_view.into()).unwrap();
let heap_allocated_public_key = Box::new(ShortintPublicKey(public_key));
@@ -96,6 +126,7 @@ pub unsafe extern "C" fn shortint_deserialize_public_key(
#[no_mangle]
pub unsafe extern "C" fn shortint_gen_compressed_public_key(
client_key: *const ShortintClientKey,
public_key_kind: ShortintPublicKeyKind,
result: *mut *mut ShortintCompressedPublicKey,
) -> c_int {
catch_panic(|| {
@@ -107,9 +138,18 @@ pub unsafe extern "C" fn shortint_gen_compressed_public_key(
let client_key = get_ref_checked(client_key).unwrap();
let heap_allocated_compressed_public_key = Box::new(ShortintCompressedPublicKey(
shortint::public_key::CompressedPublicKey::new(&client_key.0),
));
let heap_allocated_compressed_public_key = match public_key_kind {
ShortintPublicKeyKind::ShortintPublicKeyBig => Box::new(ShortintCompressedPublicKey(
ShortintCompressedPublicKeyInner::Big(
shortint::public_key::CompressedPublicKeyBig::new(&client_key.0),
),
)),
ShortintPublicKeyKind::ShortintPublicKeySmall => Box::new(ShortintCompressedPublicKey(
ShortintCompressedPublicKeyInner::Small(
shortint::public_key::CompressedPublicKeySmall::new(&client_key.0),
),
)),
};
*result = Box::into_raw(heap_allocated_compressed_public_key);
})
@@ -130,9 +170,14 @@ pub unsafe extern "C" fn shortint_compressed_public_key_encrypt(
let compressed_public_key = get_ref_checked(compressed_public_key).unwrap();
let heap_allocated_ciphertext = Box::new(ShortintCiphertext(
compressed_public_key.0.encrypt(value_to_encrypt),
));
let heap_allocated_ciphertext = match &compressed_public_key.0 {
ShortintCompressedPublicKeyInner::Big(inner) => {
Box::new(ShortintCiphertext(inner.encrypt(value_to_encrypt).into()))
}
ShortintCompressedPublicKeyInner::Small(inner) => {
Box::new(ShortintCiphertext(inner.encrypt(value_to_encrypt).into()))
}
};
*result = Box::into_raw(heap_allocated_ciphertext);
})
@@ -166,8 +211,7 @@ pub unsafe extern "C" fn shortint_deserialize_compressed_public_key(
// checked, then any access to the result pointer will segfault (mimics malloc on failure)
*result = std::ptr::null_mut();
let compressed_public_key: shortint::public_key::CompressedPublicKey =
bincode::deserialize(buffer_view.into()).unwrap();
let compressed_public_key = bincode::deserialize(buffer_view.into()).unwrap();
let heap_allocated_public_key =
Box::new(ShortintCompressedPublicKey(compressed_public_key));
@@ -190,9 +234,14 @@ pub unsafe extern "C" fn shortint_decompress_public_key(
let compressed_public_key = get_ref_checked(compressed_public_key).unwrap();
let heap_allocated_public_key = Box::new(ShortintPublicKey(
shortint::public_key::PublicKey::from(compressed_public_key.0.clone()),
));
let heap_allocated_public_key = match &compressed_public_key.0 {
ShortintCompressedPublicKeyInner::Big(inner) => Box::new(ShortintPublicKey(
ShortintPublicKeyInner::Big(inner.clone().into()),
)),
ShortintCompressedPublicKeyInner::Small(inner) => Box::new(ShortintPublicKey(
ShortintPublicKeyInner::Small(inner.clone().into()),
)),
};
*result = Box::into_raw(heap_allocated_public_key);
})

View File

@@ -1,7 +1,7 @@
use crate::c_api::utils::*;
use std::os::raw::c_int;
use super::{ShortintCiphertext, ShortintServerKey};
use super::{ShortintCiphertext, ShortintCiphertextInner, ShortintServerKey};
#[no_mangle]
pub unsafe extern "C" fn shortint_server_key_smart_add(
@@ -17,9 +17,10 @@ pub unsafe extern "C" fn shortint_server_key_smart_add(
let ct_left = get_mut_checked(ct_left).unwrap();
let ct_right = get_mut_checked(ct_right).unwrap();
let heap_allocated_ct_result = Box::new(ShortintCiphertext(
server_key.0.smart_add(&mut ct_left.0, &mut ct_right.0),
));
let res =
dispatch_binary_server_key_call!(server_key, smart_add, &mut ct_left, &mut ct_right);
let heap_allocated_ct_result = Box::new(ShortintCiphertext(res));
*result = Box::into_raw(heap_allocated_ct_result);
})
@@ -28,20 +29,20 @@ pub unsafe extern "C" fn shortint_server_key_smart_add(
#[no_mangle]
pub unsafe extern "C" fn shortint_server_key_unchecked_add(
server_key: *const ShortintServerKey,
ct_left: *mut ShortintCiphertext,
ct_right: *mut ShortintCiphertext,
ct_left: *const ShortintCiphertext,
ct_right: *const ShortintCiphertext,
result: *mut *mut ShortintCiphertext,
) -> c_int {
catch_panic(|| {
check_ptr_is_non_null_and_aligned(result).unwrap();
let server_key = get_ref_checked(server_key).unwrap();
let ct_left = get_mut_checked(ct_left).unwrap();
let ct_right = get_mut_checked(ct_right).unwrap();
let ct_left = get_ref_checked(ct_left).unwrap();
let ct_right = get_ref_checked(ct_right).unwrap();
let heap_allocated_ct_result = Box::new(ShortintCiphertext(
server_key.0.unchecked_add(&ct_left.0, &ct_right.0),
));
let res = dispatch_binary_server_key_call!(server_key, unchecked_add, &ct_left, &ct_right);
let heap_allocated_ct_result = Box::new(ShortintCiphertext(res));
*result = Box::into_raw(heap_allocated_ct_result);
})
@@ -58,9 +59,12 @@ pub unsafe extern "C" fn shortint_server_key_smart_add_assign(
let ct_left_and_result = get_mut_checked(ct_left_and_result).unwrap();
let ct_right = get_mut_checked(ct_right).unwrap();
server_key
.0
.smart_add_assign(&mut ct_left_and_result.0, &mut ct_right.0);
dispatch_binary_assign_server_key_call!(
server_key,
smart_add_assign,
&mut ct_left_and_result,
&mut ct_right
);
})
}
@@ -68,15 +72,18 @@ pub unsafe extern "C" fn shortint_server_key_smart_add_assign(
pub unsafe extern "C" fn shortint_server_key_unchecked_add_assign(
server_key: *const ShortintServerKey,
ct_left_and_result: *mut ShortintCiphertext,
ct_right: *mut ShortintCiphertext,
ct_right: *const ShortintCiphertext,
) -> c_int {
catch_panic(|| {
let server_key = get_ref_checked(server_key).unwrap();
let ct_left_and_result = get_mut_checked(ct_left_and_result).unwrap();
let ct_right = get_mut_checked(ct_right).unwrap();
let ct_right = get_ref_checked(ct_right).unwrap();
server_key
.0
.unchecked_add_assign(&mut ct_left_and_result.0, &ct_right.0);
dispatch_binary_assign_server_key_call!(
server_key,
unchecked_add_assign,
&mut ct_left_and_result,
&ct_right
);
})
}

Some files were not shown because too many files have changed in this diff Show More