hefloat

package
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 31, 2024 License: Apache-2.0, BSD-3-Clause, ISC, + 1 more Imports: 22 Imported by: 0

README

HEFLOAT

The package HEFLOAT is an RNS-accelerated version of the Homomorphic Encryption for Arithmetic of Approximate Numbers (HEAAN, a.k.a. CKKS) scheme originally proposed by Cheon, Kim, Kim and Song. The package supports two variants of the scheme: the standard one that encrypts vectors of complex numbers, and the conjugate-invariant one that encrypts vectors of real numbers, as proposed by Kim and Song.The RingType field of the Parameter struct controls which variant is instantiated:

For RingType: ring.Standard, the standard variant of CKKS is used. This requires that all moduli in the chain are congruent to 1 modulo 2N for N the ring degree. This variant supports packing of up to N/2 plaintext complex values into a single ciphertext.

For RingType: ring.ConjugateInvariant, the conjugate-invariant variant of CKKS is used. This requires that all moduli in the chain are congruent to 1 modulo 4N for N the ring degree. This variant supports packing of up to N plaintext real values into a single ciphertext.

Brief description of the Standard variant

This scheme can be used to do arithmetic over equation. The plaintext space and the ciphertext space share the same domain

,

with a power of 2.

The batch encoding of this scheme

.

maps an array of complex numbers to a polynomial with the property:

,

where represents a component-wise product, and represents a nega-cyclic convolution.

Security parameters

equation: the ring dimension, which defines the degree of the cyclotomic polynomial, and the number of coefficients of the plaintext/ciphertext polynomials; it should always be a power of two. This parameter has an impact on both security and performance (security increases with N and performance decreases with N). It should be chosen carefully to suit the intended use of the scheme.

equation: the ciphertext modulus. In lattigo, it is chosen to be the product of a chain of small coprime moduli equation that verify equation in order to enable both the RNS and NTT representation. The used moduli equation are chosen to be of size 30 to 60 bits for the best performance. This parameter has an impact on both security and performance (for a fixed equation, a larger equation implies both lower security and lower performance). It is closely related to equation and should be carefully chosen to suit the intended use of the scheme.

equation: the variance used for the error polynomials. This parameter is closely tied to the security of the scheme (a larger equation implies higher security).

Other parameters

equation: the plaintext scale. Since complex numbers are encoded on polynomials with integer coefficients, the original values must be scaled during the encoding, before being rounded to the nearest integer. The equation parameter is the power of two by which the values are multiplied during the encoding. It has an impact on the precision of the output and on the amount of operations a fresh encryption can undergo before overflowing.

Choosing the right parameters for a given application

There are 3 application-dependent parameters:

  • LogN: it determines (a) how many values can be encoded (batched) at once (maximum N/2) in one plaintext, and (b) the maximum total modulus bit size (the product of all the moduli) for a given security parameter.
  • Modulichain: it determines how many consecutive scalar and non-scalar multiplications (the depth of the arithmetic circuit) can be evaluated before requiring decryption. Since lattigo features an RNS implementation, this parameter requires careful fine-tuning depending on the application; i.e., the rescaling procedure can only rescale by one of the RNS modulus at a time, whose size has to be chosen when creating the HEFLOAT context. Additionally, the individual size of each of the moduli also has an effect on the error introduced during the rescaling, since they cannot be powers of 2, so they should be chosen as NTT primes as close as possible to a power of 2 instead.
  • LogDefaultScale: it determines the scale of the plaintext, affecting both the precision and the maximum allowed depth for a given security parameter.

Configuring parameters for HEFLOAT is very application dependent, requiring a prior analysis of the circuit to be executed under encryption. The following example illustrates how this parametrization can be done, showing that it is possible to come up with different parameter sets for a given circuit, each set having pros and cons.

Let us define the evaluation of an arbitrary smooth function f(x) on an array of ~4000 complex elements contained in a square of side 2 centered at the complex origin (with values ranging between -1-1i and 1+1i). We first need to find a good polynomial approximation for the given range. The library provides an automatic Chebyshev approximation for any given polynomial degree, which can be used for this purpose (it is also possible to define a different polynomial approximation of lower degree with an acceptable error).

Let us assume that we find an approximation of degree 5, i.e., a + bx + cx^3 + dx^5. This function can be evaluated with 3 scalar multiplications, 3 additions and 3 non-scalar multiplications, consuming a total of 4 levels (one for the scalar multiplications and 3 for the non-scalar multiplications).

We then need to chose a scale for the plaintext, that will influence both the bit consumption for the rescaling, and the precision of the computation. If we choose a scale of 2^40, we need to consume at least 160 bits (4 levels) during the evaluation, and we still need some bits left to store the final result with an acceptable precision. Let us assume that the output of the approximation lies always in the square between -20-20i and 20+20i; then, the final modulus must be at least 5 bits larger than the final scale (to preserve the integer precision).

The following parameters will work for the posed example:

  • LogN = 13
  • Modulichain = [45, 40, 40, 40, 40], for a logQ <= 205
  • LogDefaultScale = 40

But it is also possible to use less levels to have ciphertexts of smaller size and, therefore, a faster evaluation, at the expense of less precision. This can be achieved by using a scale of 30 bits and squeezing two multiplications in a single level, while pre-computing the last scalar multiplication already in the plaintext. Instead of evaluating a + bx + cx^3 + dx^5, we pre-multiply the plaintext by d^(1/5) and evaluate a + b/(d^(1/5))x + c/(d^(3/5)) + x^5.

The following parameters are enough to evaluate this modified function:

  • LogN = 13
  • Modulichain = [35, 60, 60], for a logQ <= 155
  • LogDefaultScale = 30

To summarize, several parameter sets can be used to evaluate a given function, achieving different trade-offs for space and time versus precision.

Choosing secure parameters

The CKKS scheme supports the standard recommended parameters chosen to offer a security of 128 bits for a secret key with uniform ternary distribution equation, according to the Homomorphic Encryption Standards group (https://homomorphicencryption.org/standard/).

Each set of security parameters is defined by the tuple equation :

  • {12, 109, 3.2}
  • {13, 218, 3.2}
  • {14, 438, 3.2}
  • {15, 881, 3.2}

As mentioned, setting parameters for CKKS involves not only choosing this tuple, but also defining the actual moduli chain depending on the application at hand, which is why the provided default parameter sets have to be fine-tuned, preserving the values of the aforementioned tuples, in order to maintain the required security level of 128 bits. That is, lattigo provides a set of default parameters for CKKS, including example moduli chains, ensuring 128 bit security. The user might want to choose different values in the moduli chain optimized for a specific application. As long as the total modulus is equal or below the above values for a given logN, the scheme will still provide a security of at least 128 bits against the current best known attacks.

Finally, it is worth noting that these security parameters are computed for fully entropic ternary keys (with probability distribution {1/3,1/3,1/3} for values {-1,0,1}). Lattigo uses this fully-entropic key configuration by default. It is possible, though, to generate keys with lower entropy, by modifying their distribution to {(1-p)/2, p, (1-p)/2}, for any p between 0 and 1, which for p>>1/3 can result in low Hamming weight keys (sparse keys). We recall that it has been tshown hat the security of sparse keys can be considerably lower than that of fully entropic keys, and the CKKS security parameters should be re-evaluated if sparse keys are used.

References

  1. Homomorphic Encryption for Arithmetic of Approximate Numbers (https://eprint.iacr.org/2016/421)
  2. A Full RNS Variant of Approximate Homomorphic Encryption (https://eprint.iacr.org/2018/931)
  3. Approximate Homomorphic Encryption over the Conjugate-invariant Ring (https://eprint.iacr.org/2018/952)
  4. Approximate Homomorphic Encryption with Reduced Approximation Error (https://eprint.iacr.org/2020/1118)
  5. On the precision loss in approximate homomorphic encryption (https://eprint.iacr.org/2022/162)
  6. Minimax Approximation of Sign Function by Composite Polynomial for Homomorphic Comparison (https://ieeexplore.ieee.org/abstract/document/9517029)

Documentation

Overview

Package hefloat implements Homomorphic Encryption with fixed-point approximate arithmetic over the complex or real numbers. It is implemented using an RNS-accelerated version of the Homomorphic Encryption for Arithmetic for Approximate Numbers (HEAAN, a.k.a. CKKS) scheme.

Index

Constants

View Source
const (
	HomomorphicEncode = DFTType(0) // Homomorphic Encoding (IDFT)
	HomomorphicDecode = DFTType(1) // Homomorphic Decoding (DFT)
)

HomomorphicEncode (IDFT) and HomomorphicDecode (DFT) are two available linear transformations for homomorphic encoding and decoding.

View Source
const (
	// Standard: designates the regular DFT.
	// Example: [a+bi, c+di] -> DFT([a+bi, c+di])
	Standard = DFTFormat(0)
	// SplitRealAndImag: HomomorphicEncode will return the real and
	// imaginary part into separate ciphertexts, both as real vectors.
	// Example: [a+bi, c+di] -> DFT([a, c]) and DFT([b, d])
	SplitRealAndImag = DFTFormat(1)
	// RepackImagAsReal: behaves the same as SplitRealAndImag except that
	// if the ciphertext is sparsely packed (at most N/4 slots), HomomorphicEncode
	// will repacks the real part into the left N/2 slots and the imaginary part
	// into the right N/2 slots. HomomorphicDecode must be specified with the same
	// format for correctness.
	// Example: [a+bi, 0, c+di, 0] -> [DFT([a, b]), DFT([b, d])]
	RepackImagAsReal = DFTFormat(2)
)
View Source
const (
	CosDiscrete   = Mod1Type(0) // Special approximation (Han and Ki) of pow((1/2pi), 1/2^r) * cos(2pi(x-0.25)/2^r); this method requires a minimum degree of 2*(K-1).
	SinContinuous = Mod1Type(1) // Standard Chebyshev approximation of (1/2pi) * sin(2pix) on the full Mod1Interval
	CosContinuous = Mod1Type(2) // Standard Chebyshev approximation of pow((1/2pi), 1/2^r) * cos(2pi(x-0.25)/2^r) on the full Mod1Interval
)

Sin and Cos are the two proposed functions for Mod1Type. These trigonometric functions offer a good approximation of the function x mod 1 when the values are close to the origin.

View Source
const (
	NTTFlag = true
	PREC64  = PrecisionMode(0)
	PREC128 = PrecisionMode(1)
)
View Source
const GaloisGen uint64 = ring.GaloisGen

GaloisGen is an integer of order N/2 modulo M and that spans Z_M with the integer -1. The j-th ring automorphism takes the root zeta to zeta^(5j).

Variables

View Source
var CoeffsSignX2Cheby = []string{"0", "1.125", "0", "-0.125"}

CoeffsSignX2Cheby (from https://eprint.iacr.org/2019/1234.pdf) are the coefficients of 1.5*x - 0.5*x^3 in Chebyshev basis. Evaluating this polynomial on values already close to -1, or 1 ~doubles the number of of correct digits. For example, if x = -0.9993209 then p(x) = -0.999999308 This polynomial can be composed after the minimax composite polynomial to double the output precision (up to the scheme precision) each time it is evaluated.

View Source
var CoeffsSignX4Cheby = []string{"0", "1.1962890625", "0", "-0.2392578125", "0", "0.0478515625", "0", "-0.0048828125"}

CoeffsSignX4Cheby (from https://eprint.iacr.org/2019/1234.pdf) are the coefficients of 35/16 * x - 35/16 * x^3 + 21/16 * x^5 - 5/16 * x^7 in Chebyshev basis. Evaluating this polynomial on values already close to -1, or 1 ~quadruples the number of of correct digits. For example, if x = -0.9993209 then p(x) = -0.9999999999990705 This polynomial can be composed after the minimax composite polynomial to quadruple the output precision (up to the scheme precision) each time it is evaluated.

View Source
var DefaultMinimaxCompositePolynomialForSign = [][]string{
	{"0", "0.6371462957672043333", "0", "-0.2138032460610765328", "0", "0.1300439303835664499", "0", "-0.0948842756566191044", "0", "0.0760417811618939909", "0", "-0.0647714820920817557", "0", "0.0577904411211959048", "0", "-0.5275634328386103792"},
	{"0", "0.6371463830322414578", "0", "-0.2138032749880402509", "0", "0.1300439475440832118", "0", "-0.0948842877009570762", "0", "0.0760417903036533484", "0", "-0.0647714893343788749", "0", "0.0577904470018789283", "0", "-0.5275633669027163690"},
	{"0", "0.6371474873319408921", "0", "-0.2138036410457105809", "0", "0.1300441647026617059", "0", "-0.0948844401165889295", "0", "0.0760419059884502454", "0", "-0.0647715809823254389", "0", "0.0577905214191996406", "0", "-0.5275625325136631842"},
	{"0", "0.6370469776996076431", "0", "-0.2134526779726600620", "0", "0.1294300181775238920", "0", "-0.0939692999460324791", "0", "0.0747629355709698798", "0", "-0.0630298319949635571", "0", "0.0554299627688379896", "0", "-0.0504549111784642023", "0", "0.5242368268605847996"},
	{"0", "0.6371925153898374380", "0", "-0.2127272333844484291", "0", "0.1280350175397897124", "0", "-0.0918861831051024970", "0", "0.0719237384158242601", "0", "-0.0593247422790627989", "0", "0.0506973946536399213", "0", "-0.0444605229007162961", "0", "0.0397788020190944552", "0", "-0.0361705584687241925", "0", "0.0333397971860406254", "0", "-0.0310960060432036761", "0", "0.0293126335952747929", "0", "-0.0279042579223662982", "0", "0.0268135229627401517", "0", "-0.5128179323757194002"},
	{"0", "0.6484328404896112084", "0", "-0.2164688471885406655", "0", "0.1302737771018761402", "0", "-0.0934786176742356885", "0", "0.0731553324133884104", "0", "-0.0603252338481440981", "0", "0.0515366139595849853", "0", "-0.0451803385226980999", "0", "0.0404062758116036740", "0", "-0.0367241775307736352", "0", "0.0338327393147257876", "0", "-0.0315379870551266008", "0", "0.0297110181467332488", "0", "-0.0282647625290482803", "0", "0.0271406820054187399", "0", "-0.5041440308249296747"},
	{"0", "0.8988231150519633581", "0", "-0.2996064625122592138", "0", "0.1797645789317822353", "0", "-0.1284080039344265678", "0", "0.0998837306152582349", "0", "-0.0817422066647773587", "0", "0.0691963884439569899", "0", "-0.0600136111161848355", "0", "0.0530132660795356506", "0", "-0.0475133961913746909", "0", "0.0430936248086665091", "0", "-0.0394819050695222720", "0", "0.0364958013826412785", "0", "-0.0340100990129699835", "0", "0.0319381346687564699", "0", "-0.3095637759472512887"},
	{"0", "1.2654405107323937767", "0", "-0.4015427502443620045", "0", "0.2182109348265640036", "0", "-0.1341692540177466882", "0", "0.0852282854825304735", "0", "-0.0539043807248265057", "0", "0.0332611560159092728", "0", "-0.0197419082926337129", "0", "0.0111368708758574529", "0", "-0.0058990205011466309", "0", "0.0028925861201479251", "0", "-0.0012889673944941461", "0", "0.0005081425552893727", "0", "-0.0001696330470066833", "0", "0.0000440808328172753", "0", "-0.0000071549240608255"},
	CoeffsSignX4Cheby,
}

DefaultMinimaxCompositePolynomialForSign is an example of composite minimax polynomial for the sign function that is able to distinguish between value with a delta of up to 2^{-alpha=30}, tolerates a scheme error of 2^{-35} and outputs a binary value (-1, or 1) of up to 20x4 bits of precision.

It was computed with GenMinimaxCompositePolynomialForSign(256, 30, 35, []int{15, 15, 15, 17, 31, 31, 31, 31}) which outputs a minimax composite polynomial of precision 21.926741, which is further composed with CoeffsSignX4Cheby to bring it to ~80bits of precision.

View Source
var (
	// ExampleParameters128BitLogN14LogQP438 is an example parameters set with logN=14, logQP=435
	// offering 128-bit of security.
	ExampleParameters128BitLogN14LogQP438 = ParametersLiteral{

		LogN: 14,

		LogQ: []int{55, 45, 45, 45, 45, 45, 45},

		LogDefaultScale: 45,

		LogP: []int{55, 55},

		RingType: ring.Standard,

		Xs: &rlwe.DefaultXs,

		Xe: &rlwe.DefaultXe,
	}
)

Functions

func BigFloatToFixedPointCRT

func BigFloatToFixedPointCRT(r ring.RNSRing, values []big.Float, scale *big.Float, coeffs ring.RNSPoly)

func Complex128ToFixedPointCRT

func Complex128ToFixedPointCRT(r ring.RNSRing, values []complex128, scale float64, coeffs ring.RNSPoly)

Complex128ToFixedPointCRT encodes a vector of complex128 on a CRT polynomial. The real part is put in a left N/2 coefficient and the imaginary in the right N/2 coefficients.

func ComplexArbitraryToFixedPointCRT

func ComplexArbitraryToFixedPointCRT(r ring.RNSRing, values []bignum.Complex, scale *big.Float, coeffs ring.RNSPoly)

func Float64ToFixedPointCRT

func Float64ToFixedPointCRT(r ring.RNSRing, values []float64, scale float64, coeffs ring.RNSPoly)

Float64ToFixedPointCRT encodes a vector of floats on a CRT polynomial.

func GenMinimaxCompositePolynomial

func GenMinimaxCompositePolynomial(prec uint, logalpha, logerr int, deg []int, f func(*big.Float) *big.Float) (coeffs [][]big.Float)

GenMinimaxCompositePolynomial generates the minimax composite polynomial P(x) = pk(x) o pk-1(x) o ... o p1(x) o p0(x) for the provided function in the interval in their interval [min-err, -2^{-alpha}] U [2^{-alpha}, max+err] where alpha is the desired distinguishing precision between two values and err an upperbound on the scheme error.

The user must provide the following inputs:

  • prec: the bit precision of the big.Float values used by the algorithm to compute the polynomials. This will impact the speed of the algorithm. A too low precision can prevent convergence or induce a slope zero during the zero finding. A sign that the precision is too low is when the iteration continue without the error getting smaller.
  • logalpha: log2(alpha)
  • logerr: log2(err), the upperbound on the scheme precision. Usually this value should be smaller or equal to logalpha. Correctly setting this value is mandatory for correctness, because if x is outside of the interval (i.e. smaller than -1-e or greater than 1+e), then the values will explode during the evaluation. Note that it is not required to apply change of interval [-1, 1] -> [-1-e, 1+e] because the function to evaluate is the sign (i.e. it will evaluate to the same value).
  • deg: the degree of each polynomial, ordered as follow [deg(p0(x)), deg(p1(x)), ..., deg(pk(x))]. It is highly recommended that deg(p0) <= deg(p1) <= ... <= deg(pk) for optimal approximation.

The polynomials are returned in the Chebyshev basis and pre-scaled for the interval [-1, 1] (no further scaling is required on the ciphertext).

Be aware that finding the minimax polynomials can take a while (in the order of minutes for high precision when using large degree polynomials).

The function will print information about each step of the computation in real time so that it can be monitored.

The underlying algorithm use the multi-interval Remez algorithm of https://eprint.iacr.org/2020/834.pdf.

func GenMinimaxCompositePolynomialForSign

func GenMinimaxCompositePolynomialForSign(prec uint, logalpha, logerr int, deg []int)

GenMinimaxCompositePolynomialForSign generates the minimax composite polynomial P(x) = pk(x) o pk-1(x) o ... o p1(x) o p0(x) of the sign function in their interval [min-err, -2^{-alpha}] U [2^{-alpha}, max+err] where alpha is the desired distinguishing precision between two values and err an upperbound on the scheme error.

The sign function is defined as: -1 if -1 <= x < 0, 0 if x = 0, 1 if 0 < x <= 1.

See GenMinimaxCompositePolynomial for information about how to instantiate and parameterize each input value of the algorithm.

func GetEncodedPolynomialVector

func GetEncodedPolynomialVector(params Parameters, ecd *Encoder, polys *he.PolynomialVector, inputLevel int, inputScale, targetScale rlwe.Scale) (pspe *he.EncodedPolynomialVector, err error)

func GetRootsBigComplex

func GetRootsBigComplex(NthRoot int, prec uint) (roots []bignum.Complex)

GetRootsBigComplex returns the roots e^{2*pi*i/m *j} for 0 <= j <= NthRoot with prec bits of precision.

func GetRootsComplex128

func GetRootsComplex128(NthRoot int) (roots []complex128)

GetRootsComplex128 returns the roots e^{2*pi*i/m *j} for 0 <= j <= NthRoot.

func NewCiphertext

func NewCiphertext(params Parameters, degree, level int) (ct *rlwe.Ciphertext)

NewCiphertext allocates a new rlwe.Ciphertext.

inputs:

  • params: an rlwe.ParameterProvider interface
  • degree: the degree of the ciphertext
  • level: the level of the Ciphertext

output: a newly allocated rlwe.Ciphertext of the specified degree and level.

func NewDecryptor

func NewDecryptor(params Parameters, key *rlwe.SecretKey) *rlwe.Decryptor

NewDecryptor instantiates a new rlwe.Decryptor.

inputs:

  • params: an rlwe.ParameterProvider interface
  • key: *rlwe.SecretKey

output: an rlwe.Decryptor instantiated with the provided key.

func NewEncryptor

func NewEncryptor(params Parameters, key rlwe.EncryptionKey) *rlwe.Encryptor

NewEncryptor instantiates a new rlwe.Encryptor.

inputs:

  • params: an rlwe.ParameterProvider interface
  • key: *rlwe.SecretKey or *rlwe.PublicKey

output: an rlwe.Encryptor instantiated with the provided key.

func NewKeyGenerator

func NewKeyGenerator(params Parameters) *rlwe.KeyGenerator

NewKeyGenerator instantiates a new rlwe.KeyGenerator.

inputs:

  • params: an rlwe.ParameterProvider interface

output: an rlwe.KeyGenerator.

func NewPlaintext

func NewPlaintext(params Parameters, level int) (pt *rlwe.Plaintext)

NewPlaintext allocates a new rlwe.Plaintext.

inputs:

  • params: an rlwe.ParameterProvider interface
  • level: the level of the plaintext

output: a newly allocated rlwe.Plaintext at the specified level.

Note: the user can update the field `MetaData` to set a specific scaling factor, plaintext dimensions (if applicable) or encoding domain, before encoding values on the created plaintext.

func NewPowerBasis

func NewPowerBasis(ct *rlwe.Ciphertext, basis bignum.Basis) *he.PowerBasis

NewPowerBasis is a wrapper of NewPolynomialBasis. This function creates a new powerBasis from the input ciphertext. The input ciphertext is treated as the base monomial X used to generate the other powers X^{n}.

func PrettyPrintCoefficients

func PrettyPrintCoefficients(decimals int, coeffs []big.Float, odd, even, first bool)

PrettyPrintCoefficients prints the coefficients formatted. If odd = true, even coefficients are zeroed. If even = true, odd coefficients are zeroed.

func SingleFloat64ToFixedPointCRT

func SingleFloat64ToFixedPointCRT(r ring.RNSRing, i int, value float64, scale float64, coeffs ring.RNSPoly)

SingleFloat64ToFixedPointCRT encodes a single float64 on a CRT polynomialon in the i-th coefficient.

func SpecialFFTArbitrary

func SpecialFFTArbitrary(values []bignum.Complex, N, M int, rotGroup []int, roots []bignum.Complex)

SpecialFFTArbitrary evaluates the decoding matrix on a slice of ring.Complex values.

func SpecialFFTDouble

func SpecialFFTDouble(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialFFTDouble performs the CKKS special FFT transform in place.

func SpecialFFTDoubleUL8

func SpecialFFTDoubleUL8(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialFFTDoubleUL8 performs the CKKS special FFT transform in place with unrolled loops of size 8.

func SpecialIFFTArbitrary

func SpecialIFFTArbitrary(values []bignum.Complex, N, M int, rotGroup []int, roots []bignum.Complex)

SpecialIFFTArbitrary evaluates the encoding matrix on a slice of ring.Complex values.

func SpecialIFFTDouble

func SpecialIFFTDouble(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialIFFTDouble performs the CKKS special inverse FFT transform in place.

func SpecialiFFTDoubleUnrolled8

func SpecialiFFTDoubleUnrolled8(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialiFFTDoubleUnrolled8 performs the CKKS special inverse FFT transform in place with unrolled loops of size 8.

func StandardDeviation

func StandardDeviation(vec interface{}, scale rlwe.Scale) (std float64)

StandardDeviation computes the scaled standard deviation of the input vector.

func VerifyTestVectors

func VerifyTestVectors(params Parameters, encoder *Encoder, decryptor *rlwe.Decryptor, valuesWant, valuesHave interface{}, log2MinPrec int, logprec float64, printPrecisionStats bool, t *testing.T)

Types

type CoefficientGetter

type CoefficientGetter struct {
	Values []bignum.Complex
}

CoefficientGetter is a struct that implements the he.CoefficientGetter[bignum.Complex] interface.

func (CoefficientGetter) GetSingleCoefficient

func (c CoefficientGetter) GetSingleCoefficient(pol *he.Polynomial, k int) (value bignum.Complex)

GetSingleCoefficient returns the k-th coefficient of Polynomial as the type *bignum.Complex.

func (CoefficientGetter) GetVectorCoefficient

func (c CoefficientGetter) GetVectorCoefficient(pol *he.PolynomialVector, k int) (values []bignum.Complex)

GetVectorCoefficient return a slice []bignum.Complex containing the k-th coefficient of each polynomial of PolynomialVector indexed by its Mapping. See PolynomialVector for additional information about the Mapping.

func (CoefficientGetter) ShallowCopy

ShallowCopy returns a thread-safe copy of the original CoefficientGetter.

type ComparisonEvaluator

type ComparisonEvaluator struct {
	MinimaxCompositePolynomialEvaluator
	MinimaxCompositeSignPolynomial MinimaxCompositePolynomial
}

ComparisonEvaluator is an evaluator providing an API for homomorphic comparisons. All fields of this struct are public, enabling custom instantiations.

func NewComparisonEvaluator

NewComparisonEvaluator instantiates a new ComparisonEvaluator. The default hefloat.Evaluator is compliant with the EvaluatorForMinimaxCompositePolynomial interface. The field he.Bootstrapper[rlwe.Ciphertext] can be nil if the parameters have enough level to support the computation.

Giving a MinimaxCompositePolynomial is optional, but it is highly recommended to provide one that is optimized for the circuit requiring the comparisons as this polynomial will define the internal precision of all computations performed by this evaluator.

The MinimaxCompositePolynomial must be a composite minimax approximation of the sign function: f(x) = 1 if x > 0, -1 if x < 0, else 0, in the interval [-1, 1]. Such composite polynomial can be obtained with the function GenMinimaxCompositePolynomialForSign.

If no MinimaxCompositePolynomial is given, then it will use by default the variable DefaultMinimaxCompositePolynomialForSign. See the doc of DefaultMinimaxCompositePolynomialForSign for additional information about the performance of this approximation.

This method is allocation free if a MinimaxCompositePolynomial is given.

func (ComparisonEvaluator) Max

func (eval ComparisonEvaluator) Max(op0, op1 *rlwe.Ciphertext) (max *rlwe.Ciphertext, err error)

Max returns the smooth maximum of op0 and op1, which is defined as: op0 * x + op1 * (1-x) where x = step(diff = op0-op1). Use must ensure that:

  • op0 + op1 is in the interval [-1, 1].
  • op0.Scale = op1.Scale.

This method ensures that max.Scale = params.DefaultScale.

func (ComparisonEvaluator) Min

func (eval ComparisonEvaluator) Min(op0, op1 *rlwe.Ciphertext) (min *rlwe.Ciphertext, err error)

Min returns the smooth min of op0 and op1, which is defined as: op0 * (1-x) + op1 * x where x = step(diff = op0-op1) Use must ensure that:

  • op0 + op1 is in the interval [-1, 1].
  • op0.Scale = op1.Scale.

This method ensures that min.Scale = params.DefaultScale.

func (ComparisonEvaluator) Sign

func (eval ComparisonEvaluator) Sign(op0 *rlwe.Ciphertext) (sign *rlwe.Ciphertext, err error)

Sign evaluates f(x) = 1 if x > 0, -1 if x < 0, else 0. This will ensure that sign.Scale = params.DefaultScale().

func (ComparisonEvaluator) Step

func (eval ComparisonEvaluator) Step(op0 *rlwe.Ciphertext) (step *rlwe.Ciphertext, err error)

Step evaluates f(x) = 1 if x > 0, 0 if x < 0, else 0.5 (i.e. (sign+1)/2). This will ensure that step.Scale = params.DefaultScale().

type DFTEvaluator

type DFTEvaluator struct {
	EvaluatorForDFT
	*he.LinearTransformationEvaluator
	// contains filtered or unexported fields
}

DFTEvaluator is an evaluator providing an API for homomorphic DFT. All fields of this struct are public, enabling custom instantiations.

func NewDFTEvaluator

func NewDFTEvaluator(params Parameters, eval EvaluatorForDFT) *DFTEvaluator

NewDFTEvaluator instantiates a new DFTEvaluator. The default hefloat.Evaluator is compliant to the EvaluatorForDFT interface.

func (*DFTEvaluator) CoeffsToSlots

func (eval *DFTEvaluator) CoeffsToSlots(ctIn *rlwe.Ciphertext, ctsMatrices *DFTMatrix, buf rlwe.HoistingBuffer, ctReal, ctImag *rlwe.Ciphertext) (err error)

CoeffsToSlots applies the homomorphic encoding and returns the results on the provided ciphertexts. Homomorphically encodes a complex vector vReal + i*vImag of size n on a real vector of size 2n. If the packing is sparse (n < N/2), then returns ctReal = Ecd(vReal || vImag) and ctImag = nil. If the packing is dense (n == N/2), then returns ctReal = Ecd(vReal) and ctImag = Ecd(vImag).

func (*DFTEvaluator) CoeffsToSlotsNew

func (eval *DFTEvaluator) CoeffsToSlotsNew(ctIn *rlwe.Ciphertext, ctsMatrices *DFTMatrix, buf rlwe.HoistingBuffer) (ctReal, ctImag *rlwe.Ciphertext, err error)

CoeffsToSlotsNew applies the homomorphic encoding and returns the result on new ciphertexts. Homomorphically encodes a complex vector vReal + i*vImag. Given n = current number of slots and N/2 max number of slots (half the ring degree): If the packing is sparse (n < N/2), then returns ctReal = Ecd(vReal || vImag) and ctImag = nil. If the packing is dense (n == N/2), then returns ctReal = Ecd(vReal) and ctImag = Ecd(vImag).

func (*DFTEvaluator) Evaluate

func (eval *DFTEvaluator) Evaluate(ctIn *rlwe.Ciphertext, dft *DFTMatrix, buf rlwe.HoistingBuffer, opOut *rlwe.Ciphertext) (err error)

Evaluate evaluates the homomorphic DFT/IDFT.

func (*DFTEvaluator) SlotsToCoeffs

func (eval *DFTEvaluator) SlotsToCoeffs(ctReal, ctImag *rlwe.Ciphertext, stcMatrices *DFTMatrix, buf rlwe.HoistingBuffer, opOut *rlwe.Ciphertext) (err error)

SlotsToCoeffs applies the homomorphic decoding and returns the result on the provided ciphertext. Homomorphically decodes a real vector of size 2n on a complex vector vReal + i*vImag of size n. If the packing is sparse (n < N/2) then ctReal = Ecd(vReal || vImag) and ctImag = nil. If the packing is dense (n == N/2), then ctReal = Ecd(vReal) and ctImag = Ecd(vImag).

func (*DFTEvaluator) SlotsToCoeffsNew

func (eval *DFTEvaluator) SlotsToCoeffsNew(ctReal, ctImag *rlwe.Ciphertext, stcMatrices *DFTMatrix, buf rlwe.HoistingBuffer) (opOut *rlwe.Ciphertext, err error)

SlotsToCoeffsNew applies the homomorphic decoding and returns the result on a new ciphertext. Homomorphically decodes a real vector of size 2n on a complex vector vReal + i*vImag of size n. If the packing is sparse (n < N/2) then ctReal = Ecd(vReal || vImag) and ctImag = nil. If the packing is dense (n == N/2), then ctReal = Ecd(vReal) and ctImag = Ecd(vImag).

type DFTFormat

type DFTFormat int

DFTFormat is a type used to distinguish between the different input/output formats of the Homomorphic DFT.

type DFTMatrix

type DFTMatrix struct {
	DFTMatrixLiteral
	Matrices []*he.LinearTransformation
}

DFTMatrix is a struct storing the factorized IDFT, DFT matrices, which are used to homomorphically encode and decode a ciphertext respectively.

func NewDFTMatrixFromLiteral

func NewDFTMatrixFromLiteral(params Parameters, d DFTMatrixLiteral, encoder *Encoder) (*DFTMatrix, error)

NewDFTMatrixFromLiteral generates the factorized DFT/IDFT matrices for the homomorphic encoding/decoding.

type DFTMatrixLiteral

type DFTMatrixLiteral struct {
	// Mandatory
	Type     DFTType
	LogSlots int
	LevelQ   int
	LevelP   int
	Levels   []int
	// Optional
	Format      DFTFormat  // Default: standard.
	Scaling     *big.Float // Default 1.0.
	BitReversed bool       // Default: False.
}

DFTMatrixLiteral is a struct storing the parameters to generate the factorized DFT/IDFT matrices. This struct has mandatory and optional fields.

Mandatory:

  • Type: HomomorphicEncode (a.k.a. CoeffsToSlots) or HomomorphicDecode (a.k.a. SlotsToCoeffs)
  • LogSlots: log2(slots)
  • LevelQ: starting level of the linear transformation
  • Levels: depth of the linear transform (i.e. the degree of factorization of the encoding matrix)

Optional:

  • Format: which post-processing (if any) to apply to the DFT.
  • Scaling: constant by which the matrix is multiplied
  • BitReversed: if true, then applies the transformation bit-reversed and expects bit-reversed inputs

func (DFTMatrixLiteral) Depth

func (d DFTMatrixLiteral) Depth(actual bool) (depth int)

Depth returns the number of levels allocated to the linear transform. If actual == true then returns the number of moduli consumed, else returns the factorization depth.

func (DFTMatrixLiteral) GaloisElements

func (d DFTMatrixLiteral) GaloisElements(params Parameters) (galEls []uint64)

GaloisElements returns the list of rotations performed during the CoeffsToSlot operation.

func (DFTMatrixLiteral) GenMatrices

func (d DFTMatrixLiteral) GenMatrices(LogN int, prec uint) (plainVector []he.Diagonals[bignum.Complex])

GenMatrices returns the ordered list of factors of the non-zero diagonals of the IDFT (encoding) or DFT (decoding) matrix.

func (DFTMatrixLiteral) MarshalBinary

func (d DFTMatrixLiteral) MarshalBinary() (data []byte, err error)

MarshalBinary returns a JSON representation of the the target DFTMatrixLiteral on a slice of bytes. See `Marshal` from the `encoding/json` package.

func (*DFTMatrixLiteral) UnmarshalBinary

func (d *DFTMatrixLiteral) UnmarshalBinary(data []byte) error

UnmarshalBinary reads a JSON representation on the target DFTMatrixLiteral struct. See `Unmarshal` from the `encoding/json` package.

type DFTType

type DFTType int

DFTType is a type used to distinguish between different discrete Fourier transformations.

type DomainSwitcher

type DomainSwitcher struct {
	// contains filtered or unexported fields
}

DomainSwitcher is a type for switching between the standard CKKS domain (which encrypts vectors of complex numbers) and the conjugate invariant variant of CKKS (which encrypts vectors of real numbers).

func NewDomainSwitcher

func NewDomainSwitcher(params Parameters, comlexToRealEvk, realToComplexEvk *rlwe.EvaluationKey) (DomainSwitcher, error)

NewDomainSwitcher instantiate a new DomainSwitcher type. It may be instantiated from parameters from either RingType. The method returns an error if the parameters cannot support the switching (e.g., the NTTs are undefined for either of the two ring types). The comlexToRealEvk and comlexToRealEvk EvaluationKeys can be generated using the rlwe.KeyGenerator.GenEvaluationKeysForRingSwap(*).

func (DomainSwitcher) ComplexToReal

func (switcher DomainSwitcher) ComplexToReal(eval *Evaluator, ctIn, opOut *rlwe.Ciphertext) (err error)

ComplexToReal switches the provided ciphertext `ctIn` from the standard domain to the conjugate invariant domain and writes the result into `opOut`. Given ctInCKKS = enc(real(m) + imag(m)) in Z[X](X^N + 1), returns opOutCI = enc(real(m)) in Z[X+X^-1]/(X^N + 1) in compressed form (N/2 coefficients). The scale of the output ciphertext is twice the scale of the input one. Requires the ring degree of opOut to be half the ring degree of ctIn. The security is changed from Z[X]/(X^N+1) to Z[X]/(X^N/2+1). The method will return an error if the DomainSwitcher was not initialized with a the appropriate EvaluationKeys.

func (DomainSwitcher) RealToComplex

func (switcher DomainSwitcher) RealToComplex(eval *Evaluator, ctIn, opOut *rlwe.Ciphertext) (err error)

RealToComplex switches the provided ciphertext `ctIn` from the conjugate invariant domain to the standard domain and writes the result into `opOut`. Given ctInCI = enc(real(m)) in Z[X+X^-1]/(X^2N+1) in compressed form (N coefficients), returns opOutCKKS = enc(real(m) + imag(0)) in Z[X]/(X^2N+1). Requires the ring degree of opOut to be twice the ring degree of ctIn. The security is changed from Z[X]/(X^N+1) to Z[X]/(X^2N+1). The method will return an error if the DomainSwitcher was not initialized with a the appropriate EvaluationKeys.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder is a type that implements the encoding and decoding interface for the CKKS scheme. It provides methods to encode/decode []complex128/[]bignum.Complex and []float64/[]big.Float types into/from Plaintext types.

Two different encodings domains are provided:

  • Coefficients: The coefficients are directly embedded on the plaintext. This encoding only allows to encode []float64/[]big.Float slices, but of size up to N (N being the ring degree) and does not preserve the point-wise multiplication. A ciphertext multiplication will result in a negacyclic polynomial convolution in the plaintext domain. This encoding does not provide native slot cyclic rotation. Other operations, like addition or constant multiplication, behave as usual.

  • Slots: The coefficients are first subjected to a special Fourier transform before being embedded in the plaintext by using Coeffs encoding. This encoding can embed []complex128/[]bignum.Complex and []float64/[]big.Float slices of size at most N/2 (N being the ring degree) and leverages the convolution property of the DFT to preserve point-wise complex multiplication in the plaintext domain, i.e. a ciphertext multiplication will result in an element-wise multiplication in the plaintext domain. It also enables cyclic rotations on plaintext slots. Other operations, like constant multiplication, behave as usual. It is considered the default encoding method for CKKS.

The figure bellow illustrates the relationship between these two encodings:

                                                    Z_Q[X]/(X^N+1)
	Coefficients: ---------------> Real^{N} ---------> Plaintext
                                      |
                                      |
	Slots: Complex^{N/2} -> iDFT -----┘

func NewEncoder

func NewEncoder(parameters Parameters, precision ...uint) (ecd *Encoder)

NewEncoder creates a new Encoder from the target parameters. Optional field `precision` can be given. If precision is empty or <= 53, then float64 and complex128 types will be used to perform the encoding. Else big.Float and bignum.Complex will be used.

func (Encoder) Decode

func (ecd Encoder) Decode(pt *rlwe.Plaintext, values FloatSlice) (err error)

Decode decodes the input plaintext on a new FloatSlice.

func (Encoder) DecodePublic

func (ecd Encoder) DecodePublic(pt *rlwe.Plaintext, values FloatSlice, logprec float64) (err error)

DecodePublic decodes the input plaintext on a FloatSlice. It adds, before the decoding step (i.e. in the Ring) noise that follows the given distribution parameters. If the underlying ringType is ConjugateInvariant, the imaginary part (and its related error) are zero.

func (Encoder) Embed

func (ecd Encoder) Embed(values interface{}, metadata *rlwe.MetaData, polyOut interface{}) (err error)

Embed is a generic method to encode a FloatSlice on the target polyOut. This method it as the core of the slot encoding. Values are encoded according to the provided metadata. Accepted polyOut.(type) are rlwe.Point and ring.RNSPoly. The imaginary part will be discarded if ringType == ring.ConjugateInvariant.

func (Encoder) Encode

func (ecd Encoder) Encode(values FloatSlice, pt *rlwe.Plaintext) (err error)

Encode encodes an hefloat.FloatSlice on the target plaintext. Encoding is done at the level and scale of the plaintext. Encoding domain is done according to the metadata of the plaintext. User must ensure that 1 <= len(values) <= 2^pt.LogMaxDimensions < 2^logN. The imaginary part will be discarded if ringType == ring.ConjugateInvariant.

func (Encoder) FFT

func (ecd Encoder) FFT(values FloatSlice, logN int) (err error)

FFT evaluates the special 2^{LogN}-th decoding discrete Fourier transform on FloatSlice.

func (Encoder) GetRLWEParameters

func (ecd Encoder) GetRLWEParameters() rlwe.Parameters

func (Encoder) IFFT

func (ecd Encoder) IFFT(values FloatSlice, logN int) (err error)

IFFT evaluates the special 2^{LogN}-th encoding discrete Fourier transform on FloatSlice.

func (Encoder) Parameters

func (ecd Encoder) Parameters() Parameters

func (Encoder) Prec

func (ecd Encoder) Prec() uint

Prec returns the precision in bits used by the target Encoder. A precision <= 53 will use float64, else big.Float.

func (Encoder) ShallowCopy

func (ecd Encoder) ShallowCopy() *Encoder

ShallowCopy returns a lightweight copy of the target object that can be used concurrently with the original object.

type Evaluator

type Evaluator struct {
	*Encoder
	*rlwe.Evaluator
}

Evaluator is a struct that holds the necessary elements to execute the homomorphic operations between Ciphertexts and/or Plaintexts. It also holds a memory buffer used to store intermediate computations.

func NewEvaluator

func NewEvaluator(params Parameters, evk rlwe.EvaluationKeySet) *Evaluator

NewEvaluator creates a new Evaluator, that can be used to do homomorphic operations on the Ciphertexts and/or Plaintexts. It stores a memory buffer and Ciphertexts that will be used for intermediate values.

func (*Evaluator) Add

func (eval *Evaluator) Add(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Add adds op1 to op0 and returns the result in opOut. The following types are accepted for op1:

  • rlwe.Element
  • he.Float, he.Complex or he.Integer
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

func (*Evaluator) AddNew

func (eval *Evaluator) AddNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

AddNew adds op1 to op0 and returns the result in a newly created element opOut. The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

func (*Evaluator) ApplyEvaluationKeyNew

func (eval *Evaluator) ApplyEvaluationKeyNew(op0 *rlwe.Ciphertext, evk *rlwe.EvaluationKey) (opOut *rlwe.Ciphertext, err error)

ApplyEvaluationKeyNew applies the rlwe.EvaluationKey on op0 and returns the result on a new ciphertext opOut.

func (Evaluator) Average

func (eval Evaluator) Average(ctIn *rlwe.Ciphertext, logBatchSize int, buf rlwe.HoistingBuffer, opOut *rlwe.Ciphertext) (err error)

Average returns the average of vectors of batchSize elements. The operation assumes that ctIn encrypts SlotCount/'batchSize' sub-vectors of size 'batchSize'. It then replaces all values of those sub-vectors by the component-wise average between all the sub-vectors. Example for batchSize=4 and slots=8: [{a, b, c, d}, {e, f, g, h}] -> [0.5*{a+e, b+f, c+g, d+h}, 0.5*{a+e, b+f, c+g, d+h}] Operation requires log2(SlotCout/'batchSize') rotations. Required rotation keys can be generated with 'RotationsForInnerSumLog(batchSize, SlotCount/batchSize)”

func (*Evaluator) Conjugate

func (eval *Evaluator) Conjugate(op0 *rlwe.Ciphertext, opOut *rlwe.Ciphertext) (err error)

Conjugate conjugates op0 (which is equivalent to a row rotation) and returns the result in opOut. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (*Evaluator) ConjugateNew

func (eval *Evaluator) ConjugateNew(op0 *rlwe.Ciphertext) (opOut *rlwe.Ciphertext, err error)

ConjugateNew conjugates op0 (which is equivalent to a row rotation) and returns the result in a newly created element. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (*Evaluator) DropLevel

func (eval *Evaluator) DropLevel(op0 *rlwe.Ciphertext, levels int)

DropLevel reduces the level of op0 by levels and returns the result in op0. No rescaling is applied during this procedure.

func (*Evaluator) DropLevelNew

func (eval *Evaluator) DropLevelNew(op0 *rlwe.Ciphertext, levels int) (opOut *rlwe.Ciphertext)

DropLevelNew reduces the level of op0 by levels and returns the result in a newly created element. No rescaling is applied during this procedure.

func (*Evaluator) GetRLWEParameters

func (eval *Evaluator) GetRLWEParameters() *rlwe.Parameters

GetRLWEParameters returns a pointer to the underlying rlwe.Parameters.

func (*Evaluator) LevelsConsumedPerRescaling

func (eval *Evaluator) LevelsConsumedPerRescaling() int

LevelsConsumedPerRescaling returns the number of level consumed by a rescaling.

func (*Evaluator) MatchScalesForMul

func (eval *Evaluator) MatchScalesForMul(op0, op1 *rlwe.Ciphertext, targetScale rlwe.Scale) (err error)

MatchScalesForMul updates the scale of either op0 or op1 if op0.Level() > op1.Level() or op1.Level() > op0.Level() respectively, such taht Rescale(Mul(op0, op1)).Scale = targetScale. If op0.Level() == op1.Scale() nothing is done.

func (*Evaluator) Mul

func (eval *Evaluator) Mul(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Mul multiplies op0 with op1 without relinearization and returns the result in opOut.

The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

If op1.(type) == rlwe.Element:

  • The procedure will return an error if either op0 or op1 are have a degree higher than 1.
  • The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree.

func (*Evaluator) MulNew

func (eval *Evaluator) MulNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

MulNew multiplies op0 with op1 without relinearization and returns the result in a newly created element opOut.

op1.(type) can be

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

If op1.(type) == rlwe.Element:

  • The procedure will return an error if either op0.Degree or op1.Degree > 1.

func (*Evaluator) MulRelin

func (eval *Evaluator) MulRelin(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulRelin multiplies op0 with op1 with relinearization and returns the result in opOut.

The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree. The procedure will return an error if the evaluator was not created with an relinearization key.

func (*Evaluator) MulRelinNew

func (eval *Evaluator) MulRelinNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

MulRelinNew multiplies op0 with op1 with relinearization and returns the result in a newly created element.

The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if the evaluator was not created with an relinearization key.

func (*Evaluator) MulRelinThenAdd

func (eval *Evaluator) MulRelinThenAdd(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulRelinThenAdd multiplies op0 with op1 with relinearization and adds the result on opOut.

The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

User must ensure that opOut.Scale <= op0.Scale * op1.Scale.

If opOut.Scale < op0.Scale * op1.Scale, then scales up opOut before adding the result.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree. The procedure will return an error if the evaluator was not created with an relinearization key. The procedure will return an error if opOut = op0 or op1.

func (*Evaluator) MulThenAdd

func (eval *Evaluator) MulThenAdd(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulThenAdd evaluate opOut = opOut + op0 * op1.

The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

If op1.(type) is he.Complex, he.Float or he.Int (single value):

This function will not modify op0 but will multiply opOut by Q[min(op0.Level(), opOut.Level())] if:

  • op0.Scale == opOut.Scale
  • constant is not a Gaussian integer.

If op0.Scale == opOut.Scale, and constant is not a Gaussian integer, then the constant will be scaled by Q[min(op0.Level(), opOut.Level())] else if opOut.Scale > op0.Scale, the constant will be scaled by opOut.Scale/op0.Scale.

To correctly use this function, make sure that either op0.Scale == opOut.Scale or opOut.Scale = op0.Scale * Q[min(op0.Level(), opOut.Level())].

If op1.(type) is []complex128, []float64, []big.Float or []bignum.Complex:

  • If opOut.Scale == op0.Scale, op1 will be encoded and scaled by Q[min(op0.Level(), opOut.Level())]
  • If opOut.Scale > op0.Scale, op1 will be encoded ans scaled by opOut.Scale/op1.Scale.

Then the method will recurse with op1 given as rlwe.Element.

If op1.(type) is rlwe.Element, the multiplication is carried outwithout relinearization and:

This function will return an error if op0.Scale > opOut.Scale and user must ensure that opOut.Scale <= op0.Scale * op1.Scale. If opOut.Scale < op0.Scale * op1.Scale, then scales up opOut before adding the result. Additionally, the procedure will return an error if:

  • either op0 or op1 are have a degree higher than 1.
  • opOut.Degree != op0.Degree + op1.Degree.
  • opOut = op0 or op1.

func (*Evaluator) Relinearize

func (eval *Evaluator) Relinearize(op0, opOut *rlwe.Ciphertext) (err error)

Relinearize applies the relinearization procedure on op0 and returns the result in opOut. The input Ciphertext must be of degree two.

func (*Evaluator) RelinearizeNew

func (eval *Evaluator) RelinearizeNew(op0 *rlwe.Ciphertext) (opOut *rlwe.Ciphertext, err error)

RelinearizeNew applies the relinearization procedure on op0 and returns the result in a newly created Ciphertext. The input Ciphertext must be of degree two.

func (*Evaluator) Rescale

func (eval *Evaluator) Rescale(op0, opOut *rlwe.Ciphertext) (err error)

Rescale divides op0 by the last prime of the moduli chain and repeats this procedure params.LevelsConsumedPerRescaling() times.

Returns an error if:

  • Either op0 or opOut MetaData are nil
  • The level of op0 is too low to enable a rescale

func (*Evaluator) RescaleTo

func (eval *Evaluator) RescaleTo(op0 *rlwe.Ciphertext, minScale rlwe.Scale, opOut *rlwe.Ciphertext) (err error)

RescaleTo divides op0 by the last prime in the moduli chain, and repeats this procedure (consuming one level each time) and stops if the scale reaches `minScale` or if it would go below `minscale/2`, and returns the result in opOut. Returns an error if: - minScale <= 0 - ct.Scale <= 0 - ct.Level() = 0

func (*Evaluator) Rotate

func (eval *Evaluator) Rotate(op0 *rlwe.Ciphertext, k int, opOut *rlwe.Ciphertext) (err error)

Rotate rotates the columns of op0 by k positions to the left and returns the result in opOut. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (*Evaluator) RotateHoisted

func (eval *Evaluator) RotateHoisted(ctIn *rlwe.Ciphertext, rotations []int, buf rlwe.HoistingBuffer, opOut map[int]*rlwe.Ciphertext) (err error)

RotateHoisted takes an input Ciphertext and a list of rotations and populates a map of pre-allocated Ciphertexts, where each element of the map is the input Ciphertext rotation by one element of the list. It is much faster than sequential calls to Rotate.

func (*Evaluator) RotateHoistedLazyNew

func (eval *Evaluator) RotateHoistedLazyNew(level int, rotations []int, ct *rlwe.Ciphertext, buf rlwe.HoistingBuffer) (cOut map[int]*rlwe.Ciphertext, err error)

func (*Evaluator) RotateHoistedNew

func (eval *Evaluator) RotateHoistedNew(ctIn *rlwe.Ciphertext, rotations []int, buf rlwe.HoistingBuffer) (opOut map[int]*rlwe.Ciphertext, err error)

RotateHoistedNew takes an input Ciphertext and a list of rotations and returns a map of Ciphertext, where each element of the map is the input Ciphertext rotation by one element of the list. It is much faster than sequential calls to Rotate.

func (*Evaluator) RotateNew

func (eval *Evaluator) RotateNew(op0 *rlwe.Ciphertext, k int) (opOut *rlwe.Ciphertext, err error)

RotateNew rotates the columns of op0 by k positions to the left, and returns the result in a newly created element. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (*Evaluator) ScaleUp

func (eval *Evaluator) ScaleUp(op0 *rlwe.Ciphertext, scale rlwe.Scale, opOut *rlwe.Ciphertext) (err error)

ScaleUp multiplies op0 by scale and sets its scale to its previous scale times scale returns the result in opOut.

func (*Evaluator) ScaleUpNew

func (eval *Evaluator) ScaleUpNew(op0 *rlwe.Ciphertext, scale rlwe.Scale) (opOut *rlwe.Ciphertext, err error)

ScaleUpNew multiplies op0 by scale and sets its scale to its previous scale times scale returns the result in opOut.

func (*Evaluator) SetScale

func (eval *Evaluator) SetScale(ct *rlwe.Ciphertext, scale rlwe.Scale) (err error)

SetScale sets the scale of the ciphertext to the input scale (consumes a level).

func (*Evaluator) ShallowCopy

func (eval *Evaluator) ShallowCopy() *Evaluator

ShallowCopy creates a shallow copy of this evaluator in which all the read-only data-structures are shared with the receiver and the temporary buffers are reallocated. The receiver and the returned Evaluators can be used concurrently.

func (*Evaluator) Sub

func (eval *Evaluator) Sub(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Sub subtracts op1 from op0 and returns the result in opOut. The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

func (*Evaluator) SubNew

func (eval *Evaluator) SubNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

SubNew subtracts op1 from op0 and returns the result in a newly created element opOut. The following types are accepted for op1:

  • rlwe.Element
  • he.Complex, he.Float, he.Int
  • []complex128, []float64, []big.Float or []bignum.Complex of size at most params.MaxSlots()

Passing an invalid type will return an error.

func (Evaluator) TraceNew

func (eval Evaluator) TraceNew(ctIn *rlwe.Ciphertext, logSlots int) (opOut *rlwe.Ciphertext, err error)

TraceNew maps X -> sum((-1)^i * X^{i*n+1}) for 0 <= i < N and returns the result on a new ciphertext. For log(n) = logSlots.

func (*Evaluator) WithKey

func (eval *Evaluator) WithKey(evk rlwe.EvaluationKeySet) *Evaluator

WithKey creates a shallow copy of the receiver Evaluator for which the new EvaluationKey is evaluationKey and where the temporary buffers are shared. The receiver and the returned Evaluators cannot be used concurrently.

type EvaluatorForDFT

type EvaluatorForDFT interface {
	rlwe.ParameterProvider
	he.EvaluatorForLinearTransformation
	Add(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)
	Sub(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)
	Mul(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)
	Conjugate(op0 *rlwe.Ciphertext, opOut *rlwe.Ciphertext) (err error)
	Rotate(op0 *rlwe.Ciphertext, k int, opOut *rlwe.Ciphertext) (err error)
	Rescale(op0 *rlwe.Ciphertext, opOut *rlwe.Ciphertext) (err error)
}

EvaluatorForDFT is an interface defining the set of methods required to instantiate a DFTEvaluator. The default hefloat.Evaluator is compliant to this interface.

type EvaluatorForInverse

type EvaluatorForInverse interface {
	EvaluatorForMinimaxCompositePolynomial
	MatchScalesForMul(op0, op1 *rlwe.Ciphertext, targetScale rlwe.Scale) (err error)
	SetScale(op0 *rlwe.Ciphertext, scale rlwe.Scale) (err error)
}

EvaluatorForInverse defines a set of common and scheme agnostic methods that are necessary to instantiate an InverseEvaluator. The default hefloat.Evaluator is compliant to this interface.

type EvaluatorForMinimaxCompositePolynomial

type EvaluatorForMinimaxCompositePolynomial interface {
	he.Evaluator
	ConjugateNew(ct *rlwe.Ciphertext) (ctConj *rlwe.Ciphertext, err error)
}

EvaluatorForMinimaxCompositePolynomial defines a set of common and scheme agnostic method that are necessary to instantiate a MinimaxCompositePolynomialEvaluator.

type EvaluatorForMod1

type EvaluatorForMod1 interface {
	he.Evaluator
	Parameters() Parameters
}

EvaluatorForMod1 defines a set of common and scheme agnostic methods that are necessary to instantiate a Mod1Evaluator. The default hefloat.Evaluator is compliant to this interface.

type FloatSlice

type FloatSlice interface {
}

FloatSlice is an empty interface whose goal is to indicate that the expected input should be []he.Float or []he.Complex.

type InverseEvaluator

InverseEvaluator is an evaluator used to evaluate the inverses of ciphertexts. All fields of this struct are public, enabling custom instantiations.

func NewInverseEvaluator

func NewInverseEvaluator(params Parameters, eval EvaluatorForInverse, btp he.Bootstrapper[rlwe.Ciphertext]) InverseEvaluator

NewInverseEvaluator instantiates a new InverseEvaluator. The default hefloat.Evaluator is compliant to the EvaluatorForInverse interface. The field he.Bootstrapper[rlwe.Ciphertext] can be nil if the parameters have enough levels to support the computation. This method is allocation free.

func (*InverseEvaluator) GoldschmidtDivision

func (eval *InverseEvaluator) GoldschmidtDivision(iters int, ct *rlwe.Ciphertext) (err error)

GoldschmidtDivision homomorphically computes 1/x in the domain [0, 2]. input: ct: Enc(x) with values in the interval [0+2^{-log2min}, 2-2^{-log2min}]. output: Enc(1/x - e), where |e| <= (1-x)^2^(#iterations+1) -> the bit-precision doubles after each iteration. This method automatically estimates how many iterations are needed to achieve the optimal precision, which is derived from the plaintext scale. This method will return an error if the input ciphertext does not have enough remaining level and if the InverseEvaluator was instantiated with no bootstrapper. This method will return an error if something goes wrong with the bootstrapping or the rescaling operations.

func (*InverseEvaluator) IntervalNormalization

func (eval *InverseEvaluator) IntervalNormalization(in *rlwe.Ciphertext, scaling, Max float64, Fac int) (norm *rlwe.Ciphertext, err error)

IntervalNormalization applies a modified version of Algorithm 2 of Efficient Homomorphic Evaluation on Large Intervals (https://eprint.iacr.org/2022/280) to normalize the interval from [-Max/Fac, Max/Fac] to [-1*scaling, 1*scaling]. Also returns the encrypted normalization factor.

The original algorithm of https://eprint.iacr.org/2022/280 works by successive evaluation of a function that compresses values greater than some threshold to this threshold and let values smaller than the threshold untouched (mostly). The process is iterated, each time reducing the threshold by a pre-defined factor L. We can modify the algorithm to keep track of the compression factor so that we can get back the original values (before the compression) afterward.

Given ct with values [-max, max], the method will compute y such that ct * y has values in [-1, 1]. The normalization factor is independant to each slot:

  • values smaller than 1 will have a normalization factor that tends to 1
  • values greater than 1 will have a normalization factor that tends to 1/x

func (*InverseEvaluator) InvSqrt

func (eval *InverseEvaluator) InvSqrt(in, inHalf *rlwe.Ciphertext, r int) (err error)

InvSqrt evaluates y = 1/sqrt(x) with r iterations of y = y * 1.5 - (x/2*y)*(y*y), which provides a quadratic convergence.

  • cts: values already "rougthly" close to 1/sqrt(x). This can be done by first evaluating a low-precision polynomial approximation of 1/sqrt(x).
  • half: x/2

The total depth is 2*r.

func (*InverseEvaluator) InverseFullDomainNew

func (eval *InverseEvaluator) InverseFullDomainNew(in *rlwe.Ciphertext, Min, Max float64, signMinimaxPoly ...MinimaxCompositePolynomial) (err error)

InverseFullDomainNew computes 1/x for x in [-Max, -Min] U [Min, Max].

  1. Reduce the interval from [-Max, -Min] U [Min, Max] to [-1, -Min] U [Min, 1] by computing an approximate inverse c such that |c * x| <= 1. For |x| > 1, c tends to 1/x while for |x| < c tends to 1. This is done by using the work Efficient Homomorphic Evaluation on Large Intervals (https://eprint.iacr.org/2022/280.pdf).
  2. Compute |c * x| = sign(x * c) * (x * c), this is required for the next step, which can only accept positive values.
  3. Compute y' = 1/(|c * x|) with the iterative Goldschmidt division algorithm.
  4. Compute y = y' * c * sign(x * c)

The user can provide a Minimax composite polynomial (signMinimaxPoly) for the sign function in the interval [-1-e, -Min] U [Min, 1+e] (where e is an upperbound on the scheme error). If no such polynomial is provided, then the DefaultMinimaxCompositePolynomialForSign is used by default. Note that the precision of the output of sign(x * c) does not impact the circuit precision since this value ends up being both at the numerator and denoMinator, thus cancelling itself.

func (*InverseEvaluator) InverseNegativeDomainNew

func (eval *InverseEvaluator) InverseNegativeDomainNew(in *rlwe.Ciphertext, Min, Max float64) (err error)

InverseNegativeDomainNew computes 1/x for x in [-Max, -Min].

  1. Reduce the interval from [-Max, -Min] to [-1, -Min] by computing an approximate inverse c such that |c * x| <= 1. For |x| > 1, c tends to 1/x while for |x| < c tends to 1. This is done by using the work Efficient Homomorphic Evaluation on Large Intervals (https://eprint.iacr.org/2022/280.pdf).
  2. Compute y' = 1/(c * x) with the iterative Goldschmidt division algorithm.
  3. Compute y = y' * c

func (*InverseEvaluator) InversePositiveDomainNew

func (eval *InverseEvaluator) InversePositiveDomainNew(in *rlwe.Ciphertext, Min, Max float64) (err error)

InversePositiveDomainNew computes 1/x for x in [Min, Max].

  1. Reduce the interval from [Min, Max] to [Min, 1] by computing an approximate inverse c such that |c * x| <= 1. For |x| > 1, c tends to 1/x while for |x| < c tends to 1. This is done by using the work Efficient Homomorphic Evaluation on Large Intervals (https://eprint.iacr.org/2022/280.pdf).
  2. Compute y' = 1/(c * x) with the iterative Goldschmidt division algorithm.
  3. Compute y = y' * c

type MinimaxCompositePolynomial

type MinimaxCompositePolynomial []bignum.Polynomial

MinimaxCompositePolynomial is a struct storing P(x) = pk(x) o pk-1(x) o ... o p1(x) o p0(x).

func NewMinimaxCompositePolynomial

func NewMinimaxCompositePolynomial(coeffsStr [][]string) MinimaxCompositePolynomial

NewMinimaxCompositePolynomial creates a new MinimaxCompositePolynomial from a list of coefficients. Coefficients are expected to be given in the Chebyshev basis.

func (MinimaxCompositePolynomial) Evaluate

func (mcp MinimaxCompositePolynomial) Evaluate(x interface{}) (y *bignum.Complex)

func (MinimaxCompositePolynomial) MaxDepth

func (mcp MinimaxCompositePolynomial) MaxDepth() (depth int)

type MinimaxCompositePolynomialEvaluator

type MinimaxCompositePolynomialEvaluator struct {
	EvaluatorForMinimaxCompositePolynomial
	PolynomialEvaluator
	he.Bootstrapper[rlwe.Ciphertext]
	Parameters Parameters
}

MinimaxCompositePolynomialEvaluator is an evaluator used to evaluate composite polynomials on ciphertexts. All fields of this struct are publics, enabling custom instantiations.

func NewMinimaxCompositePolynomialEvaluator

func NewMinimaxCompositePolynomialEvaluator(params Parameters, eval EvaluatorForMinimaxCompositePolynomial, bootstrapper he.Bootstrapper[rlwe.Ciphertext]) *MinimaxCompositePolynomialEvaluator

NewMinimaxCompositePolynomialEvaluator instantiates a new MinimaxCompositePolynomialEvaluator. The default hefloat.Evaluator is compliant to the EvaluatorForMinimaxCompositePolynomial interface. This method is allocation free.

func (MinimaxCompositePolynomialEvaluator) Evaluate

Evaluate evaluates the provided MinimaxCompositePolynomial on the input ciphertext.

type Mod1Evaluator

type Mod1Evaluator struct {
	EvaluatorForMod1
	PolynomialEvaluator *PolynomialEvaluator
	Mod1Parameters      Mod1Parameters
}

Mod1Evaluator is an evaluator providing an API for homomorphic evaluations of scaled x mod 1. All fields of this struct are public, enabling custom instantiations.

func NewMod1Evaluator

func NewMod1Evaluator(eval EvaluatorForMod1, evalPoly *PolynomialEvaluator, Mod1Parameters Mod1Parameters) *Mod1Evaluator

NewMod1Evaluator instantiates a new Mod1Evaluator evaluator. The default hefloat.Evaluator is compliant to the EvaluatorForMod1 interface. This method is allocation free.

func (Mod1Evaluator) EvaluateNew

func (eval Mod1Evaluator) EvaluateNew(ct *rlwe.Ciphertext) (*rlwe.Ciphertext, error)

EvaluateNew applies a homomorphic mod Q on a vector scaled by Delta, scaled down to mod 1 :

  1. Delta * (Q/Delta * I(X) + m(X)) (Delta = scaling factor, I(X) integer poly, m(X) message)
  2. Delta * (I(X) + Delta/Q * m(X)) (divide by Q/Delta)
  3. Delta * (Delta/Q * m(X)) (x mod 1)
  4. Delta * (m(X)) (multiply back by Q/Delta)

Since Q is not a power of two, but Delta is, then does an approximate division by the closest power of two to Q instead. Hence, it assumes that the input plaintext is already scaled by the correcting factor Q/2^{round(log(Q))}.

!! Assumes that the input is normalized by 1/K for K the range of the approximation.

Scaling back error correction by 2^{round(log(Q))}/Q afterward is included in the polynomial.

func (Mod1Evaluator) EvaluateWithAffineTransformationNew

func (eval Mod1Evaluator) EvaluateWithAffineTransformationNew(ct *rlwe.Ciphertext, a, b complex128) (*rlwe.Ciphertext, error)

EvaluateWithAffineTransformationNew calls EvaluateNew and then applies the affine transformation y = ax + b on the output, without consumming an additional level.

type Mod1Parameters

type Mod1Parameters struct {
	LevelQ          int                // starting level of the operation
	LogDefaultScale int                // log2 of the default scaling factor
	Mod1Type        Mod1Type           // type of approximation for the f: x mod 1 function
	LogMessageRatio int                // Log2 of the ratio between Q0 and m, i.e. Q[0]/|m|
	DoubleAngle     int                // Number of rescale and double angle formula (only applies for cos and is ignored if sin is used)
	QDiff           float64            // Q / 2^round(Log2(Q))
	Sqrt2Pi         float64            // (1/2pi)^(1.0/scFac)
	Mod1Poly        *bignum.Polynomial // Polynomial for f: x mod 1
	Mod1InvPoly     *bignum.Polynomial // Polynomial for f^-1: (x mod 1)^-1
}

Mod1Parameters is a struct storing the parameters and polynomials approximating the function x mod Q[0] (the first prime of the moduli chain).

func NewMod1ParametersFromLiteral

func NewMod1ParametersFromLiteral(params Parameters, evm Mod1ParametersLiteral) (Mod1Parameters, error)

NewMod1ParametersFromLiteral generates an Mod1Parameters struct from the Mod1ParametersLiteral struct. The Mod1Parameters struct is to instantiates a Mod1Evaluator, which homomorphically evaluates x mod 1.

func (Mod1Parameters) MessageRatio

func (evp Mod1Parameters) MessageRatio() float64

MessageRatio returns the pre-set ratio Q[0]/|m|.

func (Mod1Parameters) Mod1Interval

func (evp Mod1Parameters) Mod1Interval() float64

Mod1Interval returns the unscaled interval of the polynomial approximation of f: x mod 1.

func (Mod1Parameters) Mod1IntervalScaled

func (evp Mod1Parameters) Mod1IntervalScaled() float64

Mod1IntervalScaled returns the scaled interval (by 1/2^{DoubleAngle}) of the polynomial approximation of f: x mod 1.

func (Mod1Parameters) Mod1IntervalScalingFactor

func (evp Mod1Parameters) Mod1IntervalScalingFactor() float64

Mod1IntervalScalingFactor returns the value by which the interval of the polynomial approximation of f: x mod 1 is scaled by. This value is equal to 1/2^{DoubleAngle}.

func (Mod1Parameters) ScalingFactor

func (evp Mod1Parameters) ScalingFactor() rlwe.Scale

ScalingFactor returns scaling factor used during the x mod 1.

type Mod1ParametersLiteral

type Mod1ParametersLiteral struct {
	LevelQ          int      // Starting level of x mod 1
	LogScale        int      // Log2 of the scaling factor used during x mod 1
	Mod1Type        Mod1Type // Chose between [Sin(2*pi*x)] or [cos(2*pi*x/r) with double angle formula]
	Scaling         float64  // Value by which the output is scaled by
	LogMessageRatio int      // Log2 of the ratio between Q0 and m, i.e. Q[0]/|m|
	Mod1Degree      int      // Degree of f: x mod 1
	Mod1Interval    int      // Interval of f: x mod 1
	DoubleAngle     int      // Number of rescale and double angle formula (only applies for cos and is ignored if sin is used)
	Mod1InvDegree   int      // Degree of f^-1: (x mod 1)^-1
}

Mod1ParametersLiteral a struct for the parameters of the mod 1 procedure. The x mod 1 procedure goal is to homomorphically evaluate a modular reduction by Q[0] (the first prime of the moduli chain) on the encrypted plaintext. This struct is consumed by `NewMod1ParametersLiteralFromLiteral` to generate the `Mod1ParametersLiteral` struct, which notably stores the coefficient of the polynomial approximating the function x mod Q[0].

func (Mod1ParametersLiteral) Depth

func (evm Mod1ParametersLiteral) Depth() (depth int)

Depth returns the depth required to evaluate x mod 1.

func (Mod1ParametersLiteral) MarshalBinary

func (evm Mod1ParametersLiteral) MarshalBinary() (data []byte, err error)

MarshalBinary returns a JSON representation of the the target Mod1ParametersLiteral struct on a slice of bytes. See `Marshal` from the `encoding/json` package.

func (*Mod1ParametersLiteral) UnmarshalBinary

func (evm *Mod1ParametersLiteral) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary reads a JSON representation on the target Mod1ParametersLiteral struct. See `Unmarshal` from the `encoding/json` package.

type Mod1Type

type Mod1Type uint64

Mod1Type is the type of function/approximation used to evaluate x mod 1.

type Parameters

type Parameters struct {
	rlwe.Parameters
	// contains filtered or unexported fields
}

Parameters represents a parameter set for the CKKS cryptosystem. Its fields are private and immutable. See ParametersLiteral for user-specified parameters.

func NewParametersFromLiteral

func NewParametersFromLiteral(pl ParametersLiteral) (Parameters, error)

NewParametersFromLiteral instantiate a set of CKKS parameters from a ParametersLiteral specification. It returns the empty parameters Parameters{} and a non-nil error if the specified parameters are invalid.

If the `LogSlots` field is left unset, its value is set to `LogN-1` for the Standard ring and to `LogN` for the conjugate-invariant ring.

See `rlwe.NewParametersFromLiteral` for default values of the other optional fields.

func (Parameters) BinarySize

func (p Parameters) BinarySize() int

BinarySize returns the serialized size of the object in bytes.

func (Parameters) EncodingPrecision

func (p Parameters) EncodingPrecision() (prec uint)

EncodingPrecision returns the encoding precision in bits of the plaintext values which is max(53, log2(DefaultScale)).

func (Parameters) Equal

func (p Parameters) Equal(other *Parameters) bool

Equal compares two sets of parameters for equality.

func (Parameters) GaloisElementForComplexConjugation

func (p Parameters) GaloisElementForComplexConjugation() uint64

GaloisElementForComplexConjugation returns the Galois element for generating the automorphism X -> X^{-1 mod NthRoot} mod (X^{N} + 1). This automorphism acts as a swapping the rows of the plaintext algebra when the plaintext is batched.

Example: Recall that batched plaintexts are 2xN/2 matrices of the form [m, conjugate(m)] (the conjugate is implicitely ingored) thus given the following plaintext matrix:

[a, b, c, d][conj(a), conj(b), conj(c), conj(d)]

the complex conjugation will return the following plaintext matrix:

[conj(a), conj(b), conj(c), conj(d)][a, b, c, d]

Note that when using the ConjugateInvariant variant of the scheme, the conjugate is dropped and this operation is not defined.

func (Parameters) GaloisElementForRotation

func (p Parameters) GaloisElementForRotation(k int) uint64

GaloisElementForRotation returns the Galois element for generating the automorphism phi(k): X -> X^{5^k mod 2N} mod (X^{N} + 1), which acts as a cyclic rotation by k position to the left on batched plaintexts.

Example: Recall that batched plaintexts are 2xN/2 matrices of the form [m, conjugate(m)] (the conjugate is implicitely ingored) thus given the following plaintext matrix:

[a, b, c, d][conj(a), conj(b), conj(c), conj(d)]

a rotation by k=3 will change the plaintext to:

[d, a, b, c][conj(d), conj(a), conj(b), conj(c)]

Providing a negative k will change direction of the cyclic rotation to the right.

Note that when using the ConjugateInvariant variant of the scheme, the conjugate is dropped and the matrix becomes an 1xN matrix.

func (Parameters) GaloisElementsForInnerSum

func (p Parameters) GaloisElementsForInnerSum(batch, n int) []uint64

GaloisElementsForInnerSum returns the list of Galois elements necessary to apply the method `InnerSum` operation with parameters `batch` and `n`.

func (Parameters) GaloisElementsForReplicate

func (p Parameters) GaloisElementsForReplicate(batch, n int) []uint64

GaloisElementsForReplicate returns the list of Galois elements necessary to perform the `Replicate` operation with parameters `batch` and `n`.

func (Parameters) GaloisElementsForTrace

func (p Parameters) GaloisElementsForTrace(logN int) []uint64

GaloisElementsForTrace returns the list of Galois elements requored for the for the `Trace` operation. Trace maps X -> sum((-1)^i * X^{i*n+1}) for 2^{LogN} <= i < N.

func (Parameters) GetRLWEParameters

func (p Parameters) GetRLWEParameters() *rlwe.Parameters

GetRLWEParameters returns a pointer to the underlying RLWE parameters.

func (Parameters) GetScalingFactor

func (p Parameters) GetScalingFactor(a, c rlwe.Scale, level int) (b rlwe.Scale)

GetScalingFactor returns a scaling factor b such that Rescale(a * b) = c

func (Parameters) LevelsConsumedPerRescaling

func (p Parameters) LevelsConsumedPerRescaling() int

LevelsConsumedPerRescaling returns the number of levels (i.e. primes) consumed per rescaling. This value is 1 if the precision mode is PREC64 and is 2 if the precision mode is PREC128.

func (Parameters) LogDefaultScale

func (p Parameters) LogDefaultScale() int

LogDefaultScale returns the log2 of the default plaintext scaling factor (rounded to the nearest integer).

func (Parameters) LogMaxDimensions

func (p Parameters) LogMaxDimensions() ring.Dimensions

LogMaxDimensions returns the log2 of maximum dimension of the matrix that can be SIMD packed in a single plaintext polynomial.

func (Parameters) LogMaxSlots

func (p Parameters) LogMaxSlots() int

LogMaxSlots returns the total number of entries (`slots`) that a plaintext can store. This value is obtained by summing all log dimensions from LogDimensions.

func (Parameters) LogQLvl

func (p Parameters) LogQLvl(level int) int

LogQLvl returns the size of the modulus Q in bits at a specific level

func (Parameters) MarshalBinary

func (p Parameters) MarshalBinary() (data []byte, err error)

MarshalBinary encodes the object into a binary form on a newly allocated slice of bytes.

func (Parameters) MaxDepth

func (p Parameters) MaxDepth() int

MaxDepth returns the maximum depth enabled by the parameters, which is obtained as p.MaxLevel() / p.LevelsConsumedPerRescaling().

func (Parameters) MaxDimensions

func (p Parameters) MaxDimensions() ring.Dimensions

MaxDimensions returns the maximum dimension of the matrix that can be SIMD packed in a single plaintext polynomial.

func (Parameters) MaxLevel

func (p Parameters) MaxLevel() int

MaxLevel returns the maximum ciphertext level

func (Parameters) MaxSlots

func (p Parameters) MaxSlots() int

MaxSlots returns the total number of entries (`slots`) that a plaintext can store. This value is obtained by multiplying all dimensions from MaxDimensions.

func (Parameters) ParametersLiteral

func (p Parameters) ParametersLiteral() (pLit ParametersLiteral)

ParametersLiteral returns the ParametersLiteral of the target Parameters.

func (Parameters) PrecisionMode

func (p Parameters) PrecisionMode() PrecisionMode

PrecisionMode returns the precision mode of the parameters. This value can be ckks.PREC64 or ckks.PREC128.

func (Parameters) QLvl

func (p Parameters) QLvl(level int) *big.Int

QLvl returns the product of the moduli at the given level as a big.Int

func (*Parameters) ReadFrom

func (p *Parameters) ReadFrom(r io.Reader) (n int64, err error)

ReadFrom reads on the object from an io.Writer. It implements the io.ReaderFrom interface.

Unless r implements the buffer.Reader interface (see see lattigo/utils/buffer/reader.go), it will be wrapped into a bufio.Reader. Since this requires allocation, it is preferable to pass a buffer.Reader directly:

  • When reading multiple values from a io.Reader, it is preferable to first first wrap io.Reader in a pre-allocated bufio.Reader.
  • When reading from a var b []byte, it is preferable to pass a buffer.NewBuffer(b) as w (see lattigo/utils/buffer/buffer.go).

func (Parameters) StandardParameters

func (p Parameters) StandardParameters() (pckks Parameters, err error)

StandardParameters returns the CKKS parameters corresponding to the receiver parameter set. If the receiver is already a standard parameter set (i.e., RingType==Standard), then the method returns the receiver.

func (*Parameters) UnmarshalBinary

func (p *Parameters) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary decodes a slice of bytes generated by MarshalBinary or WriteTo on the object.

func (*Parameters) UnmarshalJSON

func (p *Parameters) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON reads a JSON representation of a parameter set into the receiver Parameter. See `Unmarshal` from the `encoding/json` package.

func (Parameters) WriteTo

func (p Parameters) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes the object on an io.Writer. It implements the io.WriterTo interface, and will write exactly object.BinarySize() bytes on w.

Unless w implements the buffer.Writer interface (see lattigo/utils/buffer/writer.go), it will be wrapped into a bufio.Writer. Since this requires allocations, it is preferable to pass a buffer.Writer directly:

  • When writing multiple times to a io.Writer, it is preferable to first wrap the io.Writer in a pre-allocated bufio.Writer.
  • When writing to a pre-allocated var b []byte, it is preferable to pass buffer.NewBuffer(b) as w (see lattigo/utils/buffer/buffer.go).

type ParametersLiteral

type ParametersLiteral struct {
	LogN            int
	LogNthRoot      int                         `json:",omitempty"`
	Q               structs.Vector[uint64]      `json:",omitempty"`
	P               structs.Vector[uint64]      `json:",omitempty"`
	LogQ            structs.Vector[int]         `json:",omitempty"`
	LogP            structs.Vector[int]         `json:",omitempty"`
	Xe              ring.DistributionParameters `json:",omitempty"`
	Xs              ring.DistributionParameters `json:",omitempty"`
	RingType        ring.Type                   `json:",omitempty"`
	LogDefaultScale int                         `json:",omitempty"`
}

ParametersLiteral is a literal representation of CKKS parameters. It has public fields and is used to express unchecked user-defined parameters literally into Go programs. The NewParametersFromLiteral function is used to generate the actual checked parameters from the literal representation.

Users must set the polynomial degree (in log_2, LogN) and the coefficient modulus, by either setting the Q and P fields to the desired moduli chain, or by setting the LogQ and LogP fields to the desired moduli sizes (in log_2). Users must also specify a default initial scale for the plaintexts.

Optionally, users may specify the error variance (Sigma), the secrets' density (H), the ring type (RingType) and the number of slots (in log_2, LogSlots). If left unset, standard default values for these field are substituted at parameter creation (see NewParametersFromLiteral).

func (ParametersLiteral) BinarySize

func (p ParametersLiteral) BinarySize() (size int)

func (ParametersLiteral) GetRLWEParametersLiteral

func (p ParametersLiteral) GetRLWEParametersLiteral() rlwe.ParametersLiteral

GetRLWEParametersLiteral returns the rlwe.ParametersLiteral from the target ckks.ParameterLiteral.

func (ParametersLiteral) MarshalBinary

func (p ParametersLiteral) MarshalBinary() (data []byte, err error)

func (*ParametersLiteral) ReadFrom

func (p *ParametersLiteral) ReadFrom(r io.Reader) (n int64, err error)

func (*ParametersLiteral) UnmarshalBinary

func (p *ParametersLiteral) UnmarshalBinary(data []byte) (err error)

func (*ParametersLiteral) UnmarshalJSON

func (p *ParametersLiteral) UnmarshalJSON(b []byte) (err error)

func (ParametersLiteral) WriteTo

func (p ParametersLiteral) WriteTo(w io.Writer) (n int64, err error)

type PolynomialEvaluator

type PolynomialEvaluator struct {
	Parameters Parameters
	he.EvaluatorForPolynomial
}

PolynomialEvaluator is a wrapper of the he.PolynomialEvaluator. All fields of this struct are public, enabling custom instantiations.

func NewPolynomialEvaluator

func NewPolynomialEvaluator(params Parameters, eval he.Evaluator) *PolynomialEvaluator

NewPolynomialEvaluator instantiates a new PolynomialEvaluator from a circuit.Evaluator. The default hefloat.Evaluator is compliant to the circuit.Evaluator interface. This method is allocation free.

func (PolynomialEvaluator) Evaluate

func (eval PolynomialEvaluator) Evaluate(ct *rlwe.Ciphertext, p interface{}, targetScale rlwe.Scale) (opOut *rlwe.Ciphertext, err error)

Evaluate evaluates a polynomial on the input Ciphertext in ceil(log2(deg+1)) levels. Returns an error if the input ciphertext does not have enough levels to carry out the full polynomial evaluation. Returns an error if something is wrong with the scale.

If the polynomial is given in Chebyshev basis, then the user must apply change of basis ct' = scale * ct + offset before the polynomial evaluation to ensure correctness. The values `scale` and `offet` can be obtained from the polynomial with the method .ChangeOfBasis().

pol: a *bignum.Polynomial, *Polynomial or *PolynomialVector targetScale: the desired output scale. This value shouldn't differ too much from the original ciphertext scale. It can for example be used to correct small deviations in the ciphertext scale and reset it to the default scale.

func (PolynomialEvaluator) EvaluateFromPowerBasis

func (eval PolynomialEvaluator) EvaluateFromPowerBasis(pb *he.PowerBasis, p interface{}, targetScale rlwe.Scale) (opOut *rlwe.Ciphertext, err error)

EvaluateFromPowerBasis evaluates a polynomial using the provided PowerBasis, holding pre-computed powers of X. This method is the same as Evaluate except that the encrypted input is a PowerBasis. See Evaluate for additional information.

type PrecisionMode

type PrecisionMode int

PrecisionMode is a variable that defines how many primes (one per machine word) are required to store initial message values. This also sets how many primes are consumed per rescaling.

There are currently two modes supported: - PREC64 (one 64 bit word) - PREC128 (two 64 bit words)

PREC64 is the default mode and supports reference plaintext scaling factors of up to 2^{64}, while PREC128 scaling factors of up to 2^{128}.

The PrecisionMode is chosen automatically based on the provided initial `LogDefaultScale` value provided by the user.

type PrecisionStats

type PrecisionStats struct {
	MaxPrec Stats
	MinPrec Stats
	AvgPrec Stats
	MedPrec Stats
	StdPrec Stats

	MaxErr Stats
	MinErr Stats
	AvgErr Stats
	MedErr Stats
	StdErr Stats

	RealDist, ImagDist, L2Dist []struct {
		Prec  big.Float
		Count int
	}
	// contains filtered or unexported fields
}

PrecisionStats is a struct storing statistic about the precision of a CKKS plaintext

func GetPrecisionStats

func GetPrecisionStats(params Parameters, encoder *Encoder, decryptor *rlwe.Decryptor, want, have interface{}, logprec float64, computeDCF bool) (prec PrecisionStats)

GetPrecisionStats generates a PrecisionStats struct from the reference values and the decrypted values vWant.(type) must be either []complex128 or []float64 element.(type) must be either *Plaintext, *Ciphertext, []complex128 or []float64. If not *Ciphertext, then decryptor can be nil.

func (PrecisionStats) String

func (prec PrecisionStats) String() string

type Stats

type Stats struct {
	Real, Imag, L2 float64
}

Stats is a struct storing the real, imaginary and L2 norm (modulus) about the precision of a complex value.

Directories

Path Synopsis
Package bootstrapping implements bootstrapping for fixed-point encrypted approximate homomorphic encryption over the complex/real numbers.
Package bootstrapping implements bootstrapping for fixed-point encrypted approximate homomorphic encryption over the complex/real numbers.
Package cosine method is the Go implementation of the polynomial-approximation algorithm by Han and Ki in
Package cosine method is the Go implementation of the polynomial-approximation algorithm by Han and Ki in

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL