forked from tuneinsight/lattigo
/
evaluator.go
939 lines (725 loc) · 34.4 KB
/
evaluator.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
package ckks
import (
"errors"
"math"
"math/big"
"github.com/fedejinich/lattigo/v5/ring"
"github.com/fedejinich/lattigo/v5/rlwe"
"github.com/fedejinich/lattigo/v5/rlwe/ringqp"
"github.com/fedejinich/lattigo/v5/utils"
)
// Evaluator is an interface implementing the methods to conduct homomorphic operations between ciphertext and/or plaintexts.
type Evaluator interface {
// ========================
// === Basic Arithmetic ===
// ========================
// Addition
Add(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
AddNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext)
// Subtraction
Sub(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
SubNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext)
// Negation
Neg(ctIn *rlwe.Ciphertext, ctOut *rlwe.Ciphertext)
NegNew(ctIn *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext)
// Constant Addition
AddConstNew(ctIn *rlwe.Ciphertext, constant interface{}) (ctOut *rlwe.Ciphertext)
AddConst(ctIn *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext)
// Constant Multiplication
MultByConstNew(ctIn *rlwe.Ciphertext, constant interface{}) (ctOut *rlwe.Ciphertext)
MultByConst(ctIn *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext)
// Constant Multiplication followed by Addition
MultByConstThenAdd(ctIn *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext)
// Complex Conjugation
ConjugateNew(ctIn *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext)
Conjugate(ctIn *rlwe.Ciphertext, ctOut *rlwe.Ciphertext)
// Multiplication
Mul(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
MulNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext)
MulRelin(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
MulRelinNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext)
MulThenAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
MulRelinThenAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
// Slot Rotations
RotateNew(ctIn *rlwe.Ciphertext, k int) (ctOut *rlwe.Ciphertext)
Rotate(ctIn *rlwe.Ciphertext, k int, ctOut *rlwe.Ciphertext)
RotateHoistedNew(ctIn *rlwe.Ciphertext, rotations []int) (ctOut map[int]*rlwe.Ciphertext)
RotateHoisted(ctIn *rlwe.Ciphertext, rotations []int, ctOut map[int]*rlwe.Ciphertext)
RotateHoistedLazyNew(level int, rotations []int, c0 *ring.Poly, c2DecompQP []ringqp.Poly) (cOut map[int]rlwe.CiphertextQP)
// ===========================
// === Advanced Arithmetic ===
// ===========================
// Polynomial evaluation
EvaluatePoly(input interface{}, pol *Polynomial, targetScale rlwe.Scale) (ctOut *rlwe.Ciphertext, err error)
EvaluatePolyVector(input interface{}, pols []*Polynomial, encoder Encoder, slotIndex map[int][]int, targetScale rlwe.Scale) (ctOut *rlwe.Ciphertext, err error)
// Inversion
InverseNew(ctIn *rlwe.Ciphertext, steps int) (ctOut *rlwe.Ciphertext, err error)
// Linear Transformations
LinearTransformNew(ctIn *rlwe.Ciphertext, linearTransform interface{}) (ctOut []*rlwe.Ciphertext)
LinearTransform(ctIn *rlwe.Ciphertext, linearTransform interface{}, ctOut []*rlwe.Ciphertext)
MultiplyByDiagMatrix(ctIn *rlwe.Ciphertext, matrix LinearTransform, c2DecompQP []ringqp.Poly, ctOut *rlwe.Ciphertext)
MultiplyByDiagMatrixBSGS(ctIn *rlwe.Ciphertext, matrix LinearTransform, c2DecompQP []ringqp.Poly, ctOut *rlwe.Ciphertext)
// Inner sum
InnerSum(ctIn *rlwe.Ciphertext, batch, n int, ctOut *rlwe.Ciphertext)
Average(ctIn *rlwe.Ciphertext, batch int, ctOut *rlwe.Ciphertext)
// Replication (inverse of Inner sum)
Replicate(ctIn *rlwe.Ciphertext, batch, n int, ctOut *rlwe.Ciphertext)
// Trace
Trace(ctIn *rlwe.Ciphertext, logSlots int, ctOut *rlwe.Ciphertext)
TraceNew(ctIn *rlwe.Ciphertext, logSlots int) (ctOut *rlwe.Ciphertext)
// =============================
// === Ciphertext Management ===
// =============================
// Key-Switching
SwitchKeysNew(ctIn *rlwe.Ciphertext, switchingKey *rlwe.SwitchingKey) (ctOut *rlwe.Ciphertext)
SwitchKeys(ctIn *rlwe.Ciphertext, switchingKey *rlwe.SwitchingKey, ctOut *rlwe.Ciphertext)
// Degree Management
RelinearizeNew(ctIn *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext)
Relinearize(ctIn *rlwe.Ciphertext, ctOut *rlwe.Ciphertext)
// Scale Management
ScaleUpNew(ctIn *rlwe.Ciphertext, scale rlwe.Scale) (ctOut *rlwe.Ciphertext)
ScaleUp(ctIn *rlwe.Ciphertext, scale rlwe.Scale, ctOut *rlwe.Ciphertext)
SetScale(ctIn *rlwe.Ciphertext, scale rlwe.Scale)
Rescale(ctIn *rlwe.Ciphertext, minScale rlwe.Scale, ctOut *rlwe.Ciphertext) (err error)
// Level Management
DropLevelNew(ctIn *rlwe.Ciphertext, levels int) (ctOut *rlwe.Ciphertext)
DropLevel(ctIn *rlwe.Ciphertext, levels int)
// ==============
// === Others ===
// ==============
CheckBinary(op0, op1, opOut rlwe.Operand, opOutMinDegree int) (degree, level int)
CheckUnary(op0, opOut rlwe.Operand) (degree, level int)
GetRLWEEvaluator() *rlwe.Evaluator
BuffQ() [3]*ring.Poly
BuffCt() *rlwe.Ciphertext
ShallowCopy() Evaluator
WithKey(rlwe.EvaluationKey) 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.
type evaluator struct {
*evaluatorBase
*evaluatorBuffers
*rlwe.Evaluator
}
type evaluatorBase struct {
params Parameters
}
type evaluatorBuffers struct {
buffQ [3]*ring.Poly // Memory buffer in order: for MForm(c0), MForm(c1), c2
buffCt *rlwe.Ciphertext // Memory buffer for ciphertexts that need to be scaled up (to be eventually removed)
}
// BuffQ returns a pointer to the internal memory buffer buffQ.
func (eval *evaluator) BuffQ() [3]*ring.Poly {
return eval.buffQ
}
// BuffCt returns a pointer to the internal memory buffer buffCt.
func (eval *evaluator) BuffCt() *rlwe.Ciphertext {
return eval.buffCt
}
func newEvaluatorBase(params Parameters) *evaluatorBase {
ev := new(evaluatorBase)
ev.params = params
return ev
}
func newEvaluatorBuffers(evalBase *evaluatorBase) *evaluatorBuffers {
buff := new(evaluatorBuffers)
params := evalBase.params
ringQ := params.RingQ()
buff.buffQ = [3]*ring.Poly{ringQ.NewPoly(), ringQ.NewPoly(), ringQ.NewPoly()}
buff.buffCt = NewCiphertext(params, 2, params.MaxLevel())
return buff
}
// 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 NewEvaluator(params Parameters, evaluationKey rlwe.EvaluationKey) Evaluator {
eval := new(evaluator)
eval.evaluatorBase = newEvaluatorBase(params)
eval.evaluatorBuffers = newEvaluatorBuffers(eval.evaluatorBase)
eval.Evaluator = rlwe.NewEvaluator(params.Parameters, &evaluationKey)
return eval
}
// GetRLWEEvaluator returns the underlying *rlwe.Evaluator.
func (eval *evaluator) GetRLWEEvaluator() *rlwe.Evaluator {
return eval.Evaluator
}
func (eval *evaluator) PermuteNTTIndexesForKey(rtks *rlwe.RotationKeySet) *map[uint64][]uint64 {
if rtks == nil {
return &map[uint64][]uint64{}
}
PermuteNTTIndex := make(map[uint64][]uint64, len(rtks.Keys))
for galEl := range rtks.Keys {
PermuteNTTIndex[galEl] = eval.params.RingQ().PermuteNTTIndex(galEl)
}
return &PermuteNTTIndex
}
func (eval *evaluator) newCiphertextBinary(op0, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext) {
maxDegree := utils.MaxInt(op0.Degree(), op1.Degree())
minLevel := utils.MinInt(op0.Level(), op1.Level())
return NewCiphertext(eval.params, maxDegree, minLevel)
}
// Add adds op1 to ctIn and returns the result in ctOut.
func (eval *evaluator) Add(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
_, level := eval.CheckBinary(ctIn, op1, ctOut, utils.MaxInt(ctIn.Degree(), op1.Degree()))
eval.evaluateInPlace(level, ctIn, op1, ctOut, eval.params.RingQ().AtLevel(level).Add)
}
// AddNew adds op1 to ctIn and returns the result in a newly created element.
func (eval *evaluator) AddNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext) {
ctOut = eval.newCiphertextBinary(ctIn, op1)
eval.Add(ctIn, op1, ctOut)
return
}
// Sub subtracts op1 from ctIn and returns the result in ctOut.
func (eval *evaluator) Sub(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
_, level := eval.CheckBinary(ctIn, op1, ctOut, utils.MaxInt(ctIn.Degree(), op1.Degree()))
eval.evaluateInPlace(level, ctIn, op1, ctOut, eval.params.RingQ().AtLevel(level).Sub)
if ctIn.Degree() < op1.Degree() {
for i := ctIn.Degree() + 1; i < op1.Degree()+1; i++ {
eval.params.RingQ().AtLevel(level).Neg(ctOut.Value[i], ctOut.Value[i])
}
}
}
// SubNew subtracts op1 from ctIn and returns the result in a newly created element.
func (eval *evaluator) SubNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext) {
ctOut = eval.newCiphertextBinary(ctIn, op1)
eval.Sub(ctIn, op1, ctOut)
return
}
func (eval *evaluator) evaluateInPlace(level int, c0 *rlwe.Ciphertext, c1 rlwe.Operand, ctOut *rlwe.Ciphertext, evaluate func(*ring.Poly, *ring.Poly, *ring.Poly)) {
var tmp0, tmp1 *rlwe.Ciphertext
maxDegree := utils.MaxInt(c0.Degree(), c1.Degree())
minDegree := utils.MinInt(c0.Degree(), c1.Degree())
// Else resizes the receiver element
ctOut.El().Resize(maxDegree, ctOut.Level())
c0Scale := c0.GetScale().Float64()
c1Scale := c1.GetScale().Float64()
if ctOut.Level() > level {
eval.DropLevel(ctOut, ctOut.Level()-utils.MinInt(c0.Level(), c1.Level()))
}
cmp := c0.GetScale().Cmp(c1.GetScale())
// Checks whether or not the receiver element is the same as one of the input elements
// and acts accordingly to avoid unnecessary element creation or element overwriting,
// and scales properly the element before the evaluation.
if ctOut == c0 {
if cmp == 1 && math.Floor(c0Scale/c1Scale) > 1 {
tmp1 = rlwe.NewCiphertextAtLevelFromPoly(level, eval.buffCt.Value[:c1.Degree()+1])
tmp1.MetaData = ctOut.MetaData
eval.MultByConst(c1.El(), math.Floor(c0Scale/c1Scale), tmp1)
} else if cmp == -1 && math.Floor(c1Scale/c0Scale) > 1 {
eval.MultByConst(c0, math.Floor(c1Scale/c0Scale), c0)
ctOut.Scale = c1.GetScale()
tmp1 = c1.El()
} else {
tmp1 = c1.El()
}
tmp0 = c0.El()
} else if ctOut == c1 {
if cmp == 1 && math.Floor(c0Scale/c1Scale) > 1 {
eval.MultByConst(c1.El(), math.Floor(c0Scale/c1Scale), ctOut)
ctOut.Scale = c0.Scale
tmp0 = c0.El()
} else if cmp == -1 && math.Floor(c1Scale/c0Scale) > 1 {
// Will avoid resizing on the output
tmp0 = rlwe.NewCiphertextAtLevelFromPoly(level, eval.buffCt.Value[:c0.Degree()+1])
tmp0.MetaData = ctOut.MetaData
eval.MultByConst(c0, math.Floor(c1Scale/c0Scale), tmp0)
} else {
tmp0 = c0.El()
}
tmp1 = c1.El()
} else {
if cmp == 1 && math.Floor(c0Scale/c1Scale) > 1 {
// Will avoid resizing on the output
tmp1 = rlwe.NewCiphertextAtLevelFromPoly(level, eval.buffCt.Value[:c1.Degree()+1])
tmp1.MetaData = ctOut.MetaData
eval.MultByConst(c1.El(), math.Floor(c0Scale/c1Scale), tmp1)
tmp0 = c0.El()
} else if cmp == -1 && math.Floor(c1Scale/c0Scale) > 1 {
tmp0 = rlwe.NewCiphertextAtLevelFromPoly(level, eval.buffCt.Value[:c0.Degree()+1])
tmp0.MetaData = ctOut.MetaData
eval.MultByConst(c0, math.Floor(c1Scale/c0Scale), tmp0)
tmp1 = c1.El()
} else {
tmp0 = c0.El()
tmp1 = c1.El()
}
}
for i := 0; i < minDegree+1; i++ {
evaluate(tmp0.Value[i], tmp1.Value[i], ctOut.El().Value[i])
}
scale := c0.Scale.Max(c1.GetScale())
ctOut.MetaData = c0.MetaData
ctOut.Scale = scale
// If the inputs degrees differ, it copies the remaining degree on the receiver.
// Also checks that the receiver is not one of the inputs to avoid unnecessary work.
if c0.Degree() > c1.Degree() && tmp0 != ctOut.El() {
for i := minDegree + 1; i < maxDegree+1; i++ {
ring.Copy(tmp0.Value[i], ctOut.El().Value[i])
}
} else if c1.Degree() > c0.Degree() && tmp1 != ctOut.El() {
for i := minDegree + 1; i < maxDegree+1; i++ {
ring.Copy(tmp1.Value[i], ctOut.El().Value[i])
}
}
}
// Neg negates the value of ct0 and returns the result in ctOut.
func (eval *evaluator) Neg(ct0 *rlwe.Ciphertext, ctOut *rlwe.Ciphertext) {
level := utils.MinInt(ct0.Level(), ctOut.Level())
if ct0.Degree() != ctOut.Degree() {
panic("cannot Negate: invalid receiver Ciphertext does not match input Ciphertext degree")
}
for i := range ct0.Value {
eval.params.RingQ().AtLevel(level).Neg(ct0.Value[i], ctOut.Value[i])
}
ctOut.MetaData = ct0.MetaData
}
// NegNew negates ct0 and returns the result in a newly created element.
func (eval *evaluator) NegNew(ct0 *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.Neg(ct0, ctOut)
return
}
// AddConst adds the input constant to ct0 and returns the result in ctOut.
// The constant can be a complex128, float64, int, int64, uint64. *big.Float, *big.Int or *ring.Complex.
func (eval *evaluator) AddConst(ct0 *rlwe.Ciphertext, constant interface{}, ct1 *rlwe.Ciphertext) {
level := utils.MinInt(ct0.Level(), ct1.Level())
ct1.Resize(ct0.Degree(), level)
RNSReal, RNSImag := bigComplexToRNSScalar(eval.params.RingQ().AtLevel(level), &ct0.Scale.Value, valueToBigComplex(constant, scalingPrecision))
eval.evaluateWithScalar(level, ct0.Value[:1], RNSReal, RNSImag, ct1.Value[:1], eval.params.RingQ().AtLevel(level).AddDoubleRNSScalar)
}
// AddConstNew adds the input constant to ct0 and returns the result in a new element.
// The constant can be a complex128, float64, int, int64, uint64. *big.Float, *big.Int or *ring.Complex.
func (eval *evaluator) AddConstNew(ct0 *rlwe.Ciphertext, constant interface{}) (ctOut *rlwe.Ciphertext) {
ctOut = ct0.CopyNew()
eval.AddConst(ct0, constant, ctOut)
return
}
// MultByConstThenAdd multiplies ctIn by the input constant, and adds it to the receiver element,
// e.g., ctOut(x) = ctOut(x) + ctIn(x) * (a+bi). This functions removes the need of storing the intermediate value c(x) * (a+bi).
//
// This function will not modify ctIn but will multiply ctOut by Q[min(ctIn.Level(), ctOut.Level())] if:
// - ctIn.Scale == ctOut.Scale
// - constant is not a Gaussian integer.
//
// If ctIn.Scale == ctOut.Scale, and constant is not a Gaussian integer, then the constant will be scaled by
// Q[min(ctIn.Level(), ctOut.Level())] else if ctOut.Scale > ctIn.Scale, the constant will be scaled by ctOut.Scale/ctIn.Scale.
//
// To correctly use this function, make sure that either ctIn.Scale == ctOut.Scale or
// ctOut.Scale = ctIn.Scale * Q[min(ctIn.Level(), ctOut.Level())].
//
// This function will panic if ctIn.Scale > ctOut.Scale.
func (eval *evaluator) MultByConstThenAdd(ctIn *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext) {
var level = utils.MinInt(ctIn.Level(), ctOut.Level())
ringQ := eval.params.RingQ().AtLevel(level)
ctOut.Resize(ctOut.Degree(), level)
cmplxBig := valueToBigComplex(constant, scalingPrecision)
var scaleRLWE rlwe.Scale
// If ctIn and ctOut scales are identical, but the constant is not a Gaussian integer then multiplies ctOut by scaleRLWE.
// This ensures noiseless addition with ctOut = scaleRLWE * ctOut + ctIn * round(scalar * scaleRLWE).
if cmp := ctIn.Scale.Cmp(ctOut.Scale); cmp == 0 {
if cmplxBig.IsInt() {
scaleRLWE = rlwe.NewScale(1)
} else {
scaleRLWE = rlwe.NewScale(ringQ.SubRings[level].Modulus)
scaleInt := new(big.Int)
scaleRLWE.Value.Int(scaleInt)
eval.MultByConst(ctOut, scaleInt, ctOut)
ctOut.Scale = ctOut.Scale.Mul(scaleRLWE)
}
} else if cmp == -1 { // ctOut.Scale > ctIn.Scale then the scaling factor for the constant becomes the quotient between the two scales
scaleRLWE = ctOut.Scale.Div(ctIn.Scale)
} else {
panic("MultByConstThenAdd: ctIn.Scale > ctOut.Scale is not supported")
}
RNSReal, RNSImag := bigComplexToRNSScalar(ringQ, &scaleRLWE.Value, cmplxBig)
eval.evaluateWithScalar(level, ctIn.Value, RNSReal, RNSImag, ctOut.Value, ringQ.MulDoubleRNSScalarThenAdd)
}
func (eval *evaluator) evaluateWithScalar(level int, p0 []*ring.Poly, RNSReal, RNSImag ring.RNSScalar, p1 []*ring.Poly, evaluate func(*ring.Poly, ring.RNSScalar, ring.RNSScalar, *ring.Poly)) {
// Component wise operation with the following vector:
// [a + b*psi_qi^2, ....., a + b*psi_qi^2, a - b*psi_qi^2, ...., a - b*psi_qi^2] mod Qi
// [{ N/2 }{ N/2 }]
// Which is equivalent outside of the NTT domain to evaluating a to the first coefficient of ct0 and b to the N/2-th coefficient of ct0.
for i, s := range eval.params.RingQ().SubRings[:level+1] {
RNSImag[i] = ring.MRedLazy(RNSImag[i], s.RootsForward[1], s.Modulus, s.MRedConstant)
RNSReal[i], RNSImag[i] = RNSReal[i]+RNSImag[i], RNSReal[i]+2*s.Modulus-RNSImag[i]
}
for i := range p0 {
evaluate(p0[i], RNSReal, RNSImag, p1[i])
}
}
// MultByConstNew multiplies ct0 by the input constant and returns the result in a newly created element.
// The scale of the output element will depend on the scale of the input element and the constant (if the constant
// needs to be scaled (its rational part is not zero)).
// The constant can be a complex128, float64, int, int64, uint64. *big.Float, *big.Int or *ring.Complex.
func (eval *evaluator) MultByConstNew(ct0 *rlwe.Ciphertext, constant interface{}) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.MultByConst(ct0, constant, ctOut)
return
}
// MultByConst multiplies ct0 by the input constant and returns the result in ctOut.
// The scale of the output element will depend on the scale of the input element and the constant (if the constant
// needs to be scaled (its rational part is not zero)).
// The constant can be a complex128, float64, int, int64, uint64. *big.Float, *big.Int or *ring.Complex.
func (eval *evaluator) MultByConst(ct0 *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext) {
level := utils.MinInt(ct0.Level(), ctOut.Level())
ctOut.Resize(ct0.Degree(), level)
ringQ := eval.params.RingQ().AtLevel(level)
cmplxBig := valueToBigComplex(constant, scalingPrecision)
var scale rlwe.Scale
if cmplxBig.IsInt() {
scale = rlwe.NewScale(1)
} else {
scale = rlwe.NewScale(ringQ.SubRings[level].Modulus)
}
RNSReal, RNSImag := bigComplexToRNSScalar(ringQ, &scale.Value, cmplxBig)
eval.evaluateWithScalar(level, ct0.Value, RNSReal, RNSImag, ctOut.Value, ringQ.MulDoubleRNSScalar)
ctOut.MetaData = ct0.MetaData
ctOut.Scale = ct0.Scale.Mul(scale)
}
// ScaleUpNew multiplies ct0 by scale and sets its scale to its previous scale times scale returns the result in ctOut.
func (eval *evaluator) ScaleUpNew(ct0 *rlwe.Ciphertext, scale rlwe.Scale) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.ScaleUp(ct0, scale, ctOut)
return
}
// ScaleUp multiplies ct0 by scale and sets its scale to its previous scale times scale returns the result in ctOut.
func (eval *evaluator) ScaleUp(ct0 *rlwe.Ciphertext, scale rlwe.Scale, ctOut *rlwe.Ciphertext) {
eval.MultByConst(ct0, scale.Uint64(), ctOut)
ctOut.MetaData = ct0.MetaData
ctOut.Scale = ct0.Scale.Mul(scale)
}
// SetScale sets the scale of the ciphertext to the input scale (consumes a level).
func (eval *evaluator) SetScale(ct *rlwe.Ciphertext, scale rlwe.Scale) {
eval.MultByConst(ct, scale.Float64()/ct.Scale.Float64(), ct)
if err := eval.Rescale(ct, scale, ct); err != nil {
panic(err)
}
ct.Scale = scale
}
// DropLevelNew reduces the level of ct0 by levels and returns the result in a newly created element.
// No rescaling is applied during this procedure.
func (eval *evaluator) DropLevelNew(ct0 *rlwe.Ciphertext, levels int) (ctOut *rlwe.Ciphertext) {
ctOut = ct0.CopyNew()
eval.DropLevel(ctOut, levels)
return
}
// DropLevel reduces the level of ct0 by levels and returns the result in ct0.
// No rescaling is applied during this procedure.
func (eval *evaluator) DropLevel(ct0 *rlwe.Ciphertext, levels int) {
ct0.Resize(ct0.Degree(), ct0.Level()-levels)
}
// RescaleNew divides ct0 by the last modulus in the moduli chain, and repeats this
// procedure (consuming one level each time) until the scale reaches the original scale or before it goes below it, and returns the result
// in a newly created element. Since all the moduli in the moduli chain are generated to be close to the
// original scale, this procedure is equivalent to dividing the input element by the scale and adding
// some error.
// Returns an error if "threshold <= 0", ct.scale = 0, ct.Level() = 0, ct.IsNTT() != true
func (eval *evaluator) RescaleNew(ct0 *rlwe.Ciphertext, minScale rlwe.Scale) (ctOut *rlwe.Ciphertext, err error) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
return ctOut, eval.Rescale(ct0, minScale, ctOut)
}
// Rescale divides ct0 by the last modulus in the moduli chain, and repeats this
// procedure (consuming one level each time) until the scale reaches the original scale or before it goes below it, and returns the result
// in ctOut. Since all the moduli in the moduli chain are generated to be close to the
// original scale, this procedure is equivalent to dividing the input element by the scale and adding
// some error.
// Returns an error if "minScale <= 0", ct.scale = 0, ct.Level() = 0, ct.IsNTT() != true or if ct.Leve() != ctOut.Level()
func (eval *evaluator) Rescale(ctIn *rlwe.Ciphertext, minScale rlwe.Scale, ctOut *rlwe.Ciphertext) (err error) {
if minScale.Cmp(rlwe.NewScale(0)) != 1 {
return errors.New("cannot Rescale: minScale is <0")
}
minScale = minScale.Div(rlwe.NewScale(2))
if ctIn.Scale.Cmp(rlwe.NewScale(0)) != 1 {
return errors.New("cannot Rescale: ciphertext scale is <0")
}
if ctIn.Level() == 0 {
return errors.New("cannot Rescale: input Ciphertext already at level 0")
}
if ctOut.Degree() != ctIn.Degree() {
return errors.New("cannot Rescale: ctIn.Degree() != ctOut.Degree()")
}
ctOut.MetaData = ctIn.MetaData
newLevel := ctIn.Level()
ringQ := eval.params.RingQ().AtLevel(ctIn.Level())
// Divides the scale by each moduli of the modulus chain as long as the scale isn't smaller than minScale/2
// or until the output Level() would be zero
var nbRescales int
for newLevel >= 0 {
scale := ctOut.Scale.Div(rlwe.NewScale(ringQ.SubRings[newLevel].Modulus))
if scale.Cmp(minScale) == -1 {
break
}
ctOut.Scale = scale
nbRescales++
newLevel--
}
if nbRescales > 0 {
for i := range ctOut.Value {
ringQ.DivRoundByLastModulusManyNTT(nbRescales, ctIn.Value[i], eval.buffQ[0], ctOut.Value[i])
}
ctOut.Resize(ctOut.Degree(), newLevel)
} else {
if ctIn != ctOut {
ctOut.Copy(ctIn)
}
}
return nil
}
// MulNew multiplies ctIn with op1 without relinearization and returns the result in a newly created element.
// The procedure will panic if either ctIn.Degree or op1.Degree > 1.
func (eval *evaluator) MulNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ctIn.Degree()+op1.Degree(), utils.MinInt(ctIn.Level(), op1.Level()))
eval.mulRelin(ctIn, op1, false, ctOut)
return
}
// Mul multiplies ctIn with op1 without relinearization and returns the result in ctOut.
// The procedure will panic if either ctIn or op1 are have a degree higher than 1.
// The procedure will panic if ctOut.Degree != ctIn.Degree + op1.Degree.
func (eval *evaluator) Mul(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
eval.mulRelin(ctIn, op1, false, ctOut)
}
// MulRelinNew multiplies ctIn with op1 with relinearization and returns the result in a newly created element.
// The procedure will panic if either ctIn.Degree or op1.Degree > 1.
// The procedure will panic if the evaluator was not created with an relinearization key.
func (eval *evaluator) MulRelinNew(ctIn *rlwe.Ciphertext, op1 rlwe.Operand) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, 1, utils.MinInt(ctIn.Level(), op1.Level()))
eval.mulRelin(ctIn, op1, true, ctOut)
return
}
// MulRelin multiplies ctIn with op1 with relinearization and returns the result in ctOut.
// The procedure will panic if either ctIn.Degree or op1.Degree > 1.
// The procedure will panic if ctOut.Degree != ctIn.Degree + op1.Degree.
// The procedure will panic if the evaluator was not created with an relinearization key.
func (eval *evaluator) MulRelin(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
eval.mulRelin(ctIn, op1, true, ctOut)
}
func (eval *evaluator) mulRelin(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, relin bool, ctOut *rlwe.Ciphertext) {
if ctIn.Degree()+op1.Degree() > 2 {
panic("cannot MulRelin: the sum of the input elements' total degree cannot be larger than 2")
}
ctOut.MetaData = ctIn.MetaData
ctOut.Scale = ctIn.Scale.Mul(op1.GetScale())
var c00, c01, c0, c1, c2 *ring.Poly
// Case Ciphertext (x) Ciphertext
if ctIn.Degree() == 1 && op1.Degree() == 1 {
_, level := eval.CheckBinary(ctIn, op1, ctOut, ctOut.Degree())
ringQ := eval.params.RingQ().AtLevel(level)
c00 = eval.buffQ[0]
c01 = eval.buffQ[1]
c0 = ctOut.Value[0]
c1 = ctOut.Value[1]
if !relin {
ctOut.El().Resize(2, level)
c2 = ctOut.Value[2]
} else {
ctOut.El().Resize(1, level)
c2 = eval.buffQ[2]
}
// Avoid overwriting if the second input is the output
var tmp0, tmp1 *rlwe.Ciphertext
if op1.El() == ctOut.El() {
tmp0, tmp1 = op1.El(), ctIn.El()
} else {
tmp0, tmp1 = ctIn.El(), op1.El()
}
ringQ.MForm(tmp0.Value[0], c00)
ringQ.MForm(tmp0.Value[1], c01)
if ctIn.El() == op1.El() { // squaring case
ringQ.MulCoeffsMontgomery(c00, tmp1.Value[0], c0) // c0 = c[0]*c[0]
ringQ.MulCoeffsMontgomery(c01, tmp1.Value[1], c2) // c2 = c[1]*c[1]
ringQ.MulCoeffsMontgomery(c00, tmp1.Value[1], c1) // c1 = 2*c[0]*c[1]
ringQ.Add(c1, c1, c1)
} else { // regular case
ringQ.MulCoeffsMontgomery(c00, tmp1.Value[0], c0) // c0 = c0[0]*c0[0]
ringQ.MulCoeffsMontgomery(c01, tmp1.Value[1], c2) // c2 = c0[1]*c1[1]
ringQ.MulCoeffsMontgomery(c00, tmp1.Value[1], c1)
ringQ.MulCoeffsMontgomeryThenAdd(c01, tmp1.Value[0], c1) // c1 = c0[0]*c1[1] + c0[1]*c1[0]
}
if relin {
if eval.Rlk == nil {
panic("cannot MulRelin: relinearization key is missing")
}
tmpCt := &rlwe.Ciphertext{Value: []*ring.Poly{eval.BuffQP[1].Q, eval.BuffQP[2].Q}}
tmpCt.IsNTT = true
eval.GadgetProduct(level, c2, eval.Rlk.Keys[0].GadgetCiphertext, tmpCt)
ringQ.Add(c0, tmpCt.Value[0], ctOut.Value[0])
ringQ.Add(c1, tmpCt.Value[1], ctOut.Value[1])
}
// Case Plaintext (x) Ciphertext or Ciphertext (x) Plaintext
} else {
_, level := eval.CheckBinary(ctIn, op1, ctOut, ctOut.Degree())
ringQ := eval.params.RingQ().AtLevel(level)
var c0 *ring.Poly
var c1 []*ring.Poly
if ctIn.Degree() == 0 {
c0 = eval.buffQ[0]
ringQ.MForm(ctIn.Value[0], c0)
c1 = op1.El().Value
} else {
c0 = eval.buffQ[0]
ringQ.MForm(op1.El().Value[0], c0)
c1 = ctIn.Value
}
ctOut.El().Resize(ctIn.Degree()+op1.Degree(), level)
for i := range c1 {
ringQ.MulCoeffsMontgomery(c0, c1[i], ctOut.Value[i])
}
}
}
// MulThenAdd multiplies ctIn with op1 without relinearization and adds the result on ctOut.
// User must ensure that ctOut.scale <= ctIn.scale * op1.scale.
// If ctOut.scale < ctIn.scale * op1.scale, then scales up ctOut before adding the result.
// The procedure will panic if either ctIn or op1 are have a degree higher than 1.
// The procedure will panic if ctOut.Degree != ctIn.Degree + op1.Degree.
// The procedure will panic if ctOut = ctIn or op1.
func (eval *evaluator) MulThenAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
eval.mulRelinThenAdd(ctIn, op1, false, ctOut)
}
// MulRelinThenAdd multiplies ctIn with op1 with relinearization and adds the result on ctOut.
// User must ensure that ctOut.scale <= ctIn.scale * op1.scale.
// If ctOut.scale < ctIn.scale * op1.scale, then scales up ctOut before adding the result.
// The procedure will panic if either ctIn.Degree or op1.Degree > 1.
// The procedure will panic if ctOut.Degree != ctIn.Degree + op1.Degree.
// The procedure will panic if the evaluator was not created with an relinearization key.
// The procedure will panic if ctOut = ctIn or op1.
func (eval *evaluator) MulRelinThenAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext) {
eval.mulRelinThenAdd(ctIn, op1, true, ctOut)
}
func (eval *evaluator) mulRelinThenAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, relin bool, ctOut *rlwe.Ciphertext) {
_, level := eval.CheckBinary(ctIn, op1, ctOut, utils.MaxInt(ctIn.Degree(), op1.Degree()))
if ctIn.Degree()+op1.Degree() > 2 {
panic("cannot MulRelinThenAdd: the sum of the input elements' degree cannot be larger than 2")
}
if ctIn.El() == ctOut.El() || op1.El() == ctOut.El() {
panic("cannot MulRelinThenAdd: ctOut must be different from op0 and op1")
}
c0f64 := ctIn.Scale.Float64()
c1f64 := op1.GetScale().Float64()
c2f64 := ctOut.Scale.Float64()
resScale := c0f64 * c1f64
if c2f64 < resScale {
eval.MultByConst(ctOut, math.Round(resScale/c2f64), ctOut)
ctOut.Scale = rlwe.NewScale(resScale)
}
ringQ := eval.params.RingQ().AtLevel(level)
var c00, c01, c0, c1, c2 *ring.Poly
// Case Ciphertext (x) Ciphertext
if ctIn.Degree() == 1 && op1.Degree() == 1 {
c00 = eval.buffQ[0]
c01 = eval.buffQ[1]
c0 = ctOut.Value[0]
c1 = ctOut.Value[1]
if !relin {
ctOut.El().Resize(2, level)
c2 = ctOut.Value[2]
} else {
// No resize here since we add on ctOut
c2 = eval.buffQ[2]
}
tmp0, tmp1 := ctIn.El(), op1.El()
ringQ.MForm(tmp0.Value[0], c00)
ringQ.MForm(tmp0.Value[1], c01)
ringQ.MulCoeffsMontgomeryThenAdd(c00, tmp1.Value[0], c0) // c0 += c[0]*c[0]
ringQ.MulCoeffsMontgomeryThenAdd(c00, tmp1.Value[1], c1) // c1 += c[0]*c[1]
ringQ.MulCoeffsMontgomeryThenAdd(c01, tmp1.Value[0], c1) // c1 += c[1]*c[0]
if relin {
if eval.Rlk == nil {
panic("cannot MulRelinThenAdd: relinearization key is missing")
}
ringQ.MulCoeffsMontgomery(c01, tmp1.Value[1], c2) // c2 += c[1]*c[1]
tmpCt := &rlwe.Ciphertext{Value: []*ring.Poly{eval.BuffQP[1].Q, eval.BuffQP[2].Q}}
tmpCt.IsNTT = true
eval.GadgetProduct(level, c2, eval.Rlk.Keys[0].GadgetCiphertext, tmpCt)
ringQ.Add(c0, tmpCt.Value[0], c0)
ringQ.Add(c1, tmpCt.Value[1], c1)
} else {
ringQ.MulCoeffsMontgomeryThenAdd(c01, tmp1.Value[1], c2) // c2 += c[1]*c[1]
}
// Case Plaintext (x) Ciphertext or Ciphertext (x) Plaintext
} else {
if ctOut.Degree() < ctIn.Degree() {
ctOut.Resize(ctIn.Degree(), level)
}
c00 := eval.buffQ[0]
ringQ.MForm(op1.El().Value[0], c00)
for i := range ctIn.Value {
ringQ.MulCoeffsMontgomeryThenAdd(ctIn.Value[i], c00, ctOut.Value[i])
}
}
}
// RelinearizeNew applies the relinearization procedure on ct0 and returns the result in a newly
// created Ciphertext. The input Ciphertext must be of degree two.
func (eval *evaluator) RelinearizeNew(ct0 *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, 1, ct0.Level())
eval.Relinearize(ct0, ctOut)
return
}
// SwitchKeysNew re-encrypts ct0 under a different key and returns the result in a newly created element.
// It requires a SwitchingKey, which is computed from the key under which the Ciphertext is currently encrypted,
// and the key under which the Ciphertext will be re-encrypted.
func (eval *evaluator) SwitchKeysNew(ct0 *rlwe.Ciphertext, switchingKey *rlwe.SwitchingKey) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.SwitchKeys(ct0, switchingKey, ctOut)
return
}
// RotateNew rotates the columns of ct0 by k positions to the left, and returns the result in a newly created element.
// If the provided element is a Ciphertext, a key-switching operation is necessary and a rotation key for the specific rotation needs to be provided.
func (eval *evaluator) RotateNew(ct0 *rlwe.Ciphertext, k int) (ctOut *rlwe.Ciphertext) {
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.Rotate(ct0, k, ctOut)
return
}
// Rotate rotates the columns of ct0 by k positions to the left and returns the result in ctOut.
// If the provided element is a Ciphertext, a key-switching operation is necessary and a rotation key for the specific rotation needs to be provided.
func (eval *evaluator) Rotate(ct0 *rlwe.Ciphertext, k int, ctOut *rlwe.Ciphertext) {
eval.Automorphism(ct0, eval.params.GaloisElementForColumnRotationBy(k), ctOut)
}
// ConjugateNew conjugates ct0 (which is equivalent to a row rotation) and returns the result in a newly
// created element. If the provided element is a Ciphertext, a key-switching operation is necessary and a rotation key
// for the row rotation needs to be provided.
func (eval *evaluator) ConjugateNew(ct0 *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot ConjugateNew: method is not supported when params.RingType() == ring.ConjugateInvariant")
}
ctOut = NewCiphertext(eval.params, ct0.Degree(), ct0.Level())
eval.Conjugate(ct0, ctOut)
return
}
// Conjugate conjugates ct0 (which is equivalent to a row rotation) and returns the result in ctOut.
// If the provided element is a Ciphertext, a key-switching operation is necessary and a rotation key for the row rotation needs to be provided.
func (eval *evaluator) Conjugate(ct0 *rlwe.Ciphertext, ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot Conjugate: method is not supported when params.RingType() == ring.ConjugateInvariant")
}
eval.Automorphism(ct0, eval.params.GaloisElementForRowRotation(), ctOut)
}
func (eval *evaluator) RotateHoistedLazyNew(level int, rotations []int, c0 *ring.Poly, c2DecompQP []ringqp.Poly) (cOut map[int]rlwe.CiphertextQP) {
cOut = make(map[int]rlwe.CiphertextQP)
for _, i := range rotations {
if i != 0 {
cOut[i] = rlwe.NewCiphertextQP(eval.params.Parameters, level, eval.params.MaxLevelP())
eval.AutomorphismHoistedLazy(level, c0, c2DecompQP, eval.params.GaloisElementForColumnRotationBy(i), cOut[i])
}
}
return
}
// 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 (eval *evaluator) ShallowCopy() Evaluator {
return &evaluator{
evaluatorBase: eval.evaluatorBase,
Evaluator: eval.Evaluator.ShallowCopy(),
evaluatorBuffers: newEvaluatorBuffers(eval.evaluatorBase),
}
}
// 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.
func (eval *evaluator) WithKey(evaluationKey rlwe.EvaluationKey) Evaluator {
return &evaluator{
Evaluator: eval.Evaluator.WithKey(&evaluationKey),
evaluatorBase: eval.evaluatorBase,
evaluatorBuffers: eval.evaluatorBuffers,
}
}