forked from tuneinsight/lattigo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
evaluator.go
1355 lines (1028 loc) · 45.8 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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package ckks
import (
"errors"
"math"
"math/big"
"github.com/jzhchu/lattigo/ring"
"github.com/jzhchu/lattigo/rlwe"
"github.com/jzhchu/lattigo/rlwe/ringqp"
"github.com/jzhchu/lattigo/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)
MultByGaussianInteger(ctIn *rlwe.Ciphertext, cReal, cImag interface{}, ctOut *rlwe.Ciphertext)
// Constant Multiplication with Addition
MultByConstAndAdd(ctIn *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext)
MultByGaussianIntegerAndAdd(ctIn *rlwe.Ciphertext, cReal, cImag interface{}, ctOut *rlwe.Ciphertext)
// Multiplication by the imaginary unit
MultByiNew(ctIn *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext)
MultByi(ctIn *rlwe.Ciphertext, ctOut *rlwe.Ciphertext)
DivByiNew(ctIn *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext)
DivByi(ctIn *rlwe.Ciphertext, ctOut *rlwe.Ciphertext)
// 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)
MulAndAdd(ctIn *rlwe.Ciphertext, op1 rlwe.Operand, ctOut *rlwe.Ciphertext)
MulRelinAndAdd(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)
RotateHoistedNoModDownNew(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 ===
// ==============
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) checkBinary(op0, op1, opOut rlwe.Operand, opOutMinDegree int) {
if op0 == nil || op1 == nil || opOut == nil {
panic("cannot checkBinary: rlwe.Operands cannot be nil")
}
if op0.Degree()+op1.Degree() == 0 {
panic("cannot checkBinary: rlwe.Operands cannot be both plaintext")
}
if opOut.Degree() < opOutMinDegree {
panic("cannot checkBinary: receiver rlwe.Operand degree is too small")
}
if !op0.El().IsNTT {
panic("cannot checkBinary: op0 must be in NTT")
}
if !op1.El().IsNTT {
panic("cannot checkBinary: op1 must be in NTT")
}
}
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) {
eval.checkBinary(ctIn, op1, ctOut, utils.MaxInt(ctIn.Degree(), op1.Degree()))
eval.evaluateInPlace(ctIn, op1, ctOut, eval.params.RingQ().AddLvl)
}
// 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) {
eval.checkBinary(ctIn, op1, ctOut, utils.MaxInt(ctIn.Degree(), op1.Degree()))
eval.evaluateInPlace(ctIn, op1, ctOut, eval.params.RingQ().SubLvl)
level := utils.MinInt(utils.MinInt(ctIn.Level(), op1.Level()), ctOut.Level())
if ctIn.Degree() < op1.Degree() {
for i := ctIn.Degree() + 1; i < op1.Degree()+1; i++ {
eval.params.RingQ().NegLvl(level, 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(c0 *rlwe.Ciphertext, c1 rlwe.Operand, ctOut *rlwe.Ciphertext, evaluate func(int, *ring.Poly, *ring.Poly, *ring.Poly)) {
var tmp0, tmp1 *rlwe.Ciphertext
level := utils.MinInt(utils.MinInt(c0.Level(), c1.Level()), ctOut.Level())
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 = eval.buffCt.El()
tmp1.Scale = ctOut.Scale
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 {
tmp0 = eval.buffCt.El()
tmp0.Scale = ctOut.Scale
eval.MultByConst(c0, math.Floor(c1Scale/c0Scale), tmp0)
} else {
tmp0 = c0.El()
}
tmp1 = c1.El()
} else {
if cmp == 1 && math.Floor(c0Scale/c1Scale) > 1 {
tmp1 = eval.buffCt.El()
tmp1.Scale = ctOut.Scale
eval.MultByConst(c1.El(), math.Floor(c0Scale/c1Scale), tmp1)
tmp0 = c0.El()
} else if cmp == -1 && math.Floor(c1Scale/c0Scale) > 1 {
tmp0 = eval.buffCt.El()
tmp0.Scale = ctOut.Scale
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(level, tmp0.Value[i], tmp1.Value[i], ctOut.El().Value[i])
}
ctOut.MetaData = c0.MetaData
ctOut.Scale = c0.Scale.Max(c1.GetScale())
// 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.CopyLvl(level, 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.CopyLvl(level, 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().NegLvl(level, 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
}
// AddConstNew adds the input constant (which can be a uint64, int64, float64 or complex128) to ct0 and returns the result in a new element.
func (eval *evaluator) AddConstNew(ct0 *rlwe.Ciphertext, constant interface{}) (ctOut *rlwe.Ciphertext) {
ctOut = ct0.CopyNew()
eval.AddConst(ct0, constant, ctOut)
return ctOut
}
func (eval *evaluator) getConstAndScale(level int, constant interface{}) (cReal, cImag, scale float64) {
// Converts to float64 and determines if a scaling is required (which is the case if either real or imag have a rational part)
scale = 1
switch constant := constant.(type) {
case complex128:
cReal = real(constant)
cImag = imag(constant)
if cReal != 0 {
valueInt := int64(cReal)
valueFloat := cReal - float64(valueInt)
if valueFloat != 0 {
scale = float64(eval.params.RingQ().Modulus[level])
}
}
if cImag != 0 {
valueInt := int64(cImag)
valueFloat := cImag - float64(valueInt)
if valueFloat != 0 {
scale = float64(eval.params.RingQ().Modulus[level])
}
}
case float64:
cReal = constant
cImag = float64(0)
if cReal != 0 {
valueInt := int64(cReal)
valueFloat := cReal - float64(valueInt)
if valueFloat != 0 {
scale = float64(eval.params.RingQ().Modulus[level])
}
}
case *big.Float:
cf64, _ := constant.Float64()
return eval.getConstAndScale(level, cf64)
case uint64:
cReal = float64(constant)
cImag = float64(0)
case int64:
cReal = float64(constant)
cImag = float64(0)
case int:
cReal = float64(constant)
cImag = float64(0)
}
if eval.params.RingType() == ring.ConjugateInvariant {
cImag = float64(0)
}
return
}
// AddConst adds the input constant (which can be a uint64, int64, float64 or complex128) to ct0 and returns the result in ctOut.
func (eval *evaluator) AddConst(ct0 *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext) {
var level = utils.MinInt(ct0.Level(), ctOut.Level())
var scaledConst, scaledConstReal, scaledConstImag, qi uint64
cReal, cImag, _ := eval.getConstAndScale(level, constant)
ringQ := eval.params.RingQ()
cf64 := ctOut.Scale.Float64()
ctOut.MetaData = ct0.MetaData
// Component wise addition of the following vector to the ciphertext:
// [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 adding a to the first coefficient of ct0 and b to the N/2-th coefficient of ct0.
for i := 0; i < level+1; i++ {
scaledConstReal, scaledConstImag, scaledConst = 0, 0, 0
qi = ringQ.Modulus[i]
if cReal != 0 {
scaledConstReal = scaleUpExact(cReal, cf64, qi)
scaledConst = scaledConstReal
}
if cImag != 0 {
scaledConstImag = ring.MRed(scaleUpExact(cImag, cf64, qi), ringQ.NttPsi[i][1], qi, ringQ.MredParams[i])
scaledConst = ring.CRed(scaledConst+scaledConstImag, qi)
}
p0tmp := ct0.Value[0].Coeffs[i]
p1tmp := ctOut.Value[0].Coeffs[i]
ring.AddScalarVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], scaledConst, qi)
if cImag != 0 {
scaledConst = ring.CRed(scaledConstReal+(qi-scaledConstImag), qi)
}
ring.AddScalarVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], scaledConst, qi)
}
}
// MultByConstAndAdd multiplies ct0 by the input constant, and adds it to the receiver element (it does not modify the input
// element), e.g., ctOut(x) = ctOut(x) + ct0(x) * (a+bi). This functions removes the need of storing the intermediate value c(x) * (a+bi).
// This function will modify the level and the scale of the receiver element depending on the level and the scale of the input
// element and the type of the constant. The level of the receiver element will be set to min(input.level, receiver.level).
// The scale of the receiver element will be set to the scale that the input element would have after the multiplication by the constant.
func (eval *evaluator) MultByConstAndAdd(ct0 *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext) {
var level = utils.MinInt(ct0.Level(), ctOut.Level())
// Forces a drop of ctOut level to ct0 level
if ctOut.Level() > level {
eval.DropLevel(ctOut, ctOut.Level()-level)
}
cReal, cImag, scale := eval.getConstAndScale(level, constant)
var scaledConst, scaledConstReal, scaledConstImag uint64
c0f64 := ct0.Scale.Float64()
c1f64 := ctOut.Scale.Float64()
ringQ := eval.params.RingQ()
// If a scaling would be required to multiply by the constant,
// it equalizes scales such that the scales match in the end.
if scale != 1 {
// If ctOut scaling is smaller than ct0's scale + the default scaling,
// then brings ctOut scale to ct0's scale.
if c1f64 < c0f64*scale {
if scale := math.Floor((scale * c0f64) / c1f64); scale > 1 {
eval.MultByConst(ctOut, scale, ctOut)
}
ctOut.MetaData = ct0.MetaData
ctOut.Scale = ct0.Scale.Mul(rlwe.NewScale(scale))
// If ctOut.scale > ((a+bi)*scale)*ct0(x), then it sets the scale to
// bring c(x)*scale to the level of ctOut(x) scale
} else if c1f64 > c0f64*scale {
scale = c1f64 / c0f64
}
// If no scaling is required, then it sets the appropriate scale such that
// ct0(x)*scale matches ctOut(x) scale without modifying ct0(x) scale.
} else {
if c1f64 > c0f64 {
scale = c1f64 / c0f64
} else if c0f64 > c1f64 {
if scale := math.Floor(c0f64 / c1f64); scale > 1 {
eval.MultByConst(ctOut, scale, ctOut)
}
ctOut.MetaData = ct0.MetaData
ctOut.Scale = ct0.Scale
}
}
// Component-wise multiplication of the following vector to the ciphertext:
// [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 adding a to the first coefficient of ct0 and b to the N/2-th coefficient of ct0.
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
mredParams := ringQ.MredParams[i]
bredParams := ringQ.BredParams[i]
scaledConstReal = 0
scaledConstImag = 0
scaledConst = 0
if cReal != 0 {
scaledConstReal = scaleUpExact(cReal, scale, qi)
scaledConst = scaledConstReal
}
if cImag != 0 {
scaledConstImag = scaleUpExact(cImag, scale, qi)
scaledConstImag = ring.MRed(scaledConstImag, ringQ.NttPsi[i][1], qi, mredParams)
scaledConst = ring.CRed(scaledConst+scaledConstImag, qi)
}
scaledConst = ring.MForm(scaledConst, qi, bredParams)
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryAndAddVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], scaledConst, qi, mredParams)
}
if cImag != 0 {
scaledConst = ring.CRed(scaledConstReal+(qi-scaledConstImag), qi)
scaledConst = ring.MForm(scaledConst, qi, bredParams)
}
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryAndAddVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], scaledConst, qi, mredParams)
}
}
}
// 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 uint64, int64, float64 or complex128.
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 uint64, int64, float64 or complex128.
func (eval *evaluator) MultByConst(ct0 *rlwe.Ciphertext, constant interface{}, ctOut *rlwe.Ciphertext) {
var level = utils.MinInt(ct0.Level(), ctOut.Level())
cReal, cImag, scale := eval.getConstAndScale(level, constant)
// Component wise multiplication of the following vector with the ciphertext:
// [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 adding a to the first coefficient of ct0 and b to the N/2-th coefficient of ct0.
ringQ := eval.params.RingQ()
var scaledConst, scaledConstReal, scaledConstImag uint64
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
bredParams := ringQ.BredParams[i]
mredParams := ringQ.MredParams[i]
scaledConstReal = 0
scaledConstImag = 0
scaledConst = 0
if cReal != 0 {
scaledConstReal = scaleUpExact(cReal, scale, qi)
scaledConst = scaledConstReal
}
if cImag != 0 {
scaledConstImag = scaleUpExact(cImag, scale, qi)
scaledConstImag = ring.MRed(scaledConstImag, ringQ.NttPsi[i][1], qi, mredParams)
scaledConst = ring.CRed(scaledConst+scaledConstImag, qi)
}
scaledConst = ring.MForm(scaledConst, qi, bredParams)
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], scaledConst, qi, mredParams)
}
if cImag != 0 {
scaledConst = ring.CRed(scaledConstReal+(qi-scaledConstImag), qi)
scaledConst = ring.MForm(scaledConst, qi, bredParams)
}
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], scaledConst, qi, mredParams)
}
}
ctOut.MetaData = ct0.MetaData
ctOut.Scale = ct0.Scale.Mul(rlwe.NewScale(scale))
}
// MultByGaussianInteger multiples the ct0 by the gaussian integer cReal + i*cImag and returns the result on ctOut.
// Accepted types for cReal and cImag are uint64, int64 and big.Int.
func (eval *evaluator) MultByGaussianInteger(ct0 *rlwe.Ciphertext, cReal, cImag interface{}, ctOut *rlwe.Ciphertext) {
ringQ := eval.params.RingQ()
level := utils.MinInt(ct0.Level(), ctOut.Level())
var scaledConst, scaledConstReal, scaledConstImag uint64
ctOut.MetaData = ct0.MetaData
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
bredParams := ringQ.BredParams[i]
mredParams := ringQ.MredParams[i]
scaledConstReal = interfaceMod(cReal, qi)
if eval.params.RingType() != ring.ConjugateInvariant {
scaledConstImag = interfaceMod(cImag, qi)
}
scaledConst = scaledConstReal
if scaledConstImag != 0 {
scaledConstImag = ring.MRed(scaledConstImag, ringQ.NttPsi[i][1], qi, mredParams)
scaledConst = ring.CRed(scaledConst+scaledConstImag, qi)
}
scaledConst = ring.MForm(scaledConst, qi, bredParams)
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], scaledConst, qi, mredParams)
}
if cImag != 0 {
scaledConst = ring.CRed(scaledConstReal+(qi-scaledConstImag), qi)
scaledConst = ring.MForm(scaledConst, qi, bredParams)
}
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], scaledConst, qi, mredParams)
}
}
}
// MultByGaussianIntegerAndAdd multiples the ct0 by the gaussian integer cReal + i*cImag and adds the result on ctOut.
// Accepted types for cReal and cImag are uint64, int64 and big.Int.
func (eval *evaluator) MultByGaussianIntegerAndAdd(ct0 *rlwe.Ciphertext, cReal, cImag interface{}, ctOut *rlwe.Ciphertext) {
ringQ := eval.params.RingQ()
level := utils.MinInt(ct0.Level(), ctOut.Level())
var scaledConst, scaledConstReal, scaledConstImag uint64
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
bredParams := ringQ.BredParams[i]
mredParams := ringQ.MredParams[i]
scaledConstReal = interfaceMod(cReal, qi)
if eval.params.RingType() != ring.ConjugateInvariant {
scaledConstImag = interfaceMod(cImag, qi)
}
scaledConst = scaledConstReal
if scaledConstImag != 0 {
scaledConstImag = ring.MRed(scaledConstImag, ringQ.NttPsi[i][1], qi, mredParams)
scaledConst = ring.CRed(scaledConst+scaledConstImag, qi)
}
scaledConst = ring.MForm(scaledConst, qi, bredParams)
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryAndAddVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], scaledConst, qi, mredParams)
}
if cImag != 0 {
scaledConst = ring.CRed(scaledConstReal+(qi-scaledConstImag), qi)
scaledConst = ring.MForm(scaledConst, qi, bredParams)
}
for u := range ct0.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryAndAddVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], scaledConst, qi, mredParams)
}
}
}
// MultByiNew multiplies ct0 by the imaginary number i, and returns the result in a newly created element.
// It does not change the scale.
func (eval *evaluator) MultByiNew(ct0 *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot MultByiNew: method not supported when params.RingType() == ring.ConjugateInvariant")
}
ctOut = NewCiphertext(eval.params, 1, ct0.Level())
eval.MultByi(ct0, ctOut)
return ctOut
}
// MultByi multiplies ct0 by the imaginary number i, and returns the result in ctOut.
// It does not change the scale.
func (eval *evaluator) MultByi(ct0 *rlwe.Ciphertext, ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot MultByi: method not supported when params.RingType() == ring.ConjugateInvariant")
}
var level = utils.MinInt(ct0.Level(), ctOut.Level())
ctOut.MetaData = ct0.MetaData
ringQ := eval.params.RingQ()
var imag uint64
// Equivalent to a product by the monomial x^(n/2) outside of the NTT domain
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
mredParams := ringQ.MredParams[i]
imag = ringQ.NttPsi[i][1] // Psi^2
for u := range ctOut.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], imag, qi, mredParams)
}
imag = qi - imag
for u := range ctOut.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], imag, qi, mredParams)
}
}
}
// DivByiNew multiplies ct0 by the imaginary number 1/i = -i, and returns the result in a newly created element.
// It does not change the scale.
func (eval *evaluator) DivByiNew(ct0 *rlwe.Ciphertext) (ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot DivByiNew: method not supported when params.RingType() == ring.ConjugateInvariant")
}
ctOut = NewCiphertext(eval.params, 1, ct0.Level())
eval.DivByi(ct0, ctOut)
return
}
// DivByi multiplies ct0 by the imaginary number 1/i = -i, and returns the result in ctOut.
// It does not change the scale.
func (eval *evaluator) DivByi(ct0 *rlwe.Ciphertext, ctOut *rlwe.Ciphertext) {
if eval.params.RingType() == ring.ConjugateInvariant {
panic("cannot DivByi: method not supported when params.RingType() == ring.ConjugateInvariant")
}
var level = utils.MinInt(ct0.Level(), ctOut.Level())
ringQ := eval.params.RingQ()
ctOut.MetaData = ct0.MetaData
var imag uint64
// Equivalent to a product by the monomial x^(3*n/2) outside of the NTT domain
for i := 0; i < level+1; i++ {
qi := ringQ.Modulus[i]
mredParams := ringQ.MredParams[i]
imag = qi - ringQ.NttPsi[i][1] // -Psi^2
for u := range ctOut.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[:ringQ.N>>1], p1tmp[:ringQ.N>>1], imag, qi, mredParams)
}
imag = ringQ.NttPsi[i][1] // Psi^2
for u := range ctOut.Value {
p0tmp := ct0.Value[u].Coeffs[i]
p1tmp := ctOut.Value[u].Coeffs[i]
ring.MulScalarMontgomeryVec(p0tmp[ringQ.N>>1:], p1tmp[ringQ.N>>1:], imag, qi, mredParams)
}
}
}
// ScaleUpNew multiplies ct0 by 2^scale and sets its scale to its previous scale
// plus 2^n. It returns the result in a newly created element.
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 2^scale and sets its scale to its previous scale
// plus 2^n. It 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) {
ringQ := eval.params.RingQ()
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
currentLevel := 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 currentLevel >= 0 {
scale := ctOut.Scale.Div(rlwe.NewScale(ringQ.Modulus[currentLevel]))