Homomorphic Parity Bit
Last updated
Last updated
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.
To use Booleans, the booleans
feature in our Cargo.toml must be enabled:
Other configurations can be found .
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.
After the mandatory configuration steps, the function is called:
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.
The function has the following signature:
To make it generic, the first step is:
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:
However, the compiler will complain:
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
.
The Compiler is still not happy:
The way to fix this is to use Higher-Rank Trait Bounds
:
The final code will look like this:
Here is a complete example that uses this function for both clear and FHE values: