-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathintegers.go
More file actions
1102 lines (939 loc) · 31 KB
/
integers.go
File metadata and controls
1102 lines (939 loc) · 31 KB
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
// Copyright (c) 2025, Lux Industries Inc
// SPDX-License-Identifier: BSD-3-Clause
package fhe
import (
"fmt"
"math/big"
"github.com/luxfi/lattice/v7/core/rgsw/blindrot"
"github.com/luxfi/lattice/v7/core/rlwe"
)
// FheUintType represents the type of encrypted integer
type FheUintType uint8
const (
FheBool FheUintType = 0
FheUint4 FheUintType = 1
FheUint8 FheUintType = 2
FheUint16 FheUintType = 3
FheUint32 FheUintType = 4
FheUint64 FheUintType = 5
FheUint128 FheUintType = 6
FheUint160 FheUintType = 7 // For Ethereum addresses
FheUint256 FheUintType = 8
)
// NumBits returns the number of bits for the type
func (t FheUintType) NumBits() int {
switch t {
case FheBool:
return 1
case FheUint4:
return 4
case FheUint8:
return 8
case FheUint16:
return 16
case FheUint32:
return 32
case FheUint64:
return 64
case FheUint128:
return 128
case FheUint160:
return 160
case FheUint256:
return 256
default:
return 0
}
}
func (t FheUintType) String() string {
switch t {
case FheBool:
return "ebool"
case FheUint4:
return "euint4"
case FheUint8:
return "euint8"
case FheUint16:
return "euint16"
case FheUint32:
return "euint32"
case FheUint64:
return "euint64"
case FheUint128:
return "euint128"
case FheUint160:
return "euint160"
case FheUint256:
return "euint256"
default:
return "unknown"
}
}
// RadixCiphertext represents an encrypted integer using radix decomposition.
// Each block is a ShortInt holding a few bits of the value.
// LSB is at index 0.
type RadixCiphertext struct {
blocks []*ShortInt
blockBits int // Bits per block (typically 2 or 4)
numBlocks int // Number of blocks
fheType FheUintType // The integer type
}
// Type returns the FHE type
func (rc *RadixCiphertext) Type() FheUintType {
return rc.fheType
}
// NumBits returns total bits
func (rc *RadixCiphertext) NumBits() int {
return rc.blockBits * rc.numBlocks
}
// IntegerParams holds parameters for radix integer operations
type IntegerParams struct {
fheParams Parameters
shortParams *ShortIntParams
blockBits int // Bits per radix block (2 or 4)
}
// NewIntegerParams creates parameters for integer operations
func NewIntegerParams(params Parameters, blockBits int) (*IntegerParams, error) {
if blockBits != 2 && blockBits != 4 {
return nil, fmt.Errorf("blockBits must be 2 or 4, got %d", blockBits)
}
shortParams, err := NewShortIntParams(params, blockBits)
if err != nil {
return nil, err
}
return &IntegerParams{
fheParams: params,
shortParams: shortParams,
blockBits: blockBits,
}, nil
}
// IntegerEncryptor encrypts integers of various sizes
type IntegerEncryptor struct {
params *IntegerParams
shortEnc *ShortIntEncryptor
}
// NewIntegerEncryptor creates a new integer encryptor
func NewIntegerEncryptor(params *IntegerParams, sk *SecretKey) *IntegerEncryptor {
return &IntegerEncryptor{
params: params,
shortEnc: NewShortIntEncryptor(params.shortParams, sk),
}
}
// numBlocksForType returns the number of radix blocks needed for a type
func (enc *IntegerEncryptor) numBlocksForType(t FheUintType) int {
return (t.NumBits() + enc.params.blockBits - 1) / enc.params.blockBits
}
// EncryptUint64 encrypts a uint64 value
func (enc *IntegerEncryptor) EncryptUint64(value uint64, t FheUintType) (*RadixCiphertext, error) {
numBlocks := enc.numBlocksForType(t)
blockMask := uint64((1 << enc.params.blockBits) - 1)
blocks := make([]*ShortInt, numBlocks)
for i := 0; i < numBlocks; i++ {
blockValue := int((value >> (i * enc.params.blockBits)) & blockMask)
block, err := enc.shortEnc.Encrypt(blockValue)
if err != nil {
return nil, fmt.Errorf("encrypting block %d: %w", i, err)
}
blocks[i] = block
}
return &RadixCiphertext{
blocks: blocks,
blockBits: enc.params.blockBits,
numBlocks: numBlocks,
fheType: t,
}, nil
}
// EncryptBigInt encrypts a big.Int value (for types > 64 bits)
func (enc *IntegerEncryptor) EncryptBigInt(value *big.Int, t FheUintType) (*RadixCiphertext, error) {
numBlocks := enc.numBlocksForType(t)
blockMask := big.NewInt(int64((1 << enc.params.blockBits) - 1))
blocks := make([]*ShortInt, numBlocks)
remaining := new(big.Int).Set(value)
for i := 0; i < numBlocks; i++ {
blockBig := new(big.Int).And(remaining, blockMask)
blockValue := int(blockBig.Int64())
block, err := enc.shortEnc.Encrypt(blockValue)
if err != nil {
return nil, fmt.Errorf("encrypting block %d: %w", i, err)
}
blocks[i] = block
remaining.Rsh(remaining, uint(enc.params.blockBits))
}
return &RadixCiphertext{
blocks: blocks,
blockBits: enc.params.blockBits,
numBlocks: numBlocks,
fheType: t,
}, nil
}
// EncryptBool encrypts a boolean
func (enc *IntegerEncryptor) EncryptBool(value bool) (*RadixCiphertext, error) {
v := 0
if value {
v = 1
}
block, err := enc.shortEnc.Encrypt(v)
if err != nil {
return nil, err
}
return &RadixCiphertext{
blocks: []*ShortInt{block},
blockBits: enc.params.blockBits,
numBlocks: 1,
fheType: FheBool,
}, nil
}
// Encrypt4 encrypts a 4-bit value
func (enc *IntegerEncryptor) Encrypt4(value uint8) (*RadixCiphertext, error) {
return enc.EncryptUint64(uint64(value&0xF), FheUint4)
}
// Encrypt8 encrypts an 8-bit value
func (enc *IntegerEncryptor) Encrypt8(value uint8) (*RadixCiphertext, error) {
return enc.EncryptUint64(uint64(value), FheUint8)
}
// Encrypt16 encrypts a 16-bit value
func (enc *IntegerEncryptor) Encrypt16(value uint16) (*RadixCiphertext, error) {
return enc.EncryptUint64(uint64(value), FheUint16)
}
// Encrypt32 encrypts a 32-bit value
func (enc *IntegerEncryptor) Encrypt32(value uint32) (*RadixCiphertext, error) {
return enc.EncryptUint64(uint64(value), FheUint32)
}
// Encrypt64 encrypts a 64-bit value
func (enc *IntegerEncryptor) Encrypt64(value uint64) (*RadixCiphertext, error) {
return enc.EncryptUint64(value, FheUint64)
}
// IntegerDecryptor decrypts integers
type IntegerDecryptor struct {
params *IntegerParams
shortDec *ShortIntDecryptor
}
// NewIntegerDecryptor creates a new integer decryptor
func NewIntegerDecryptor(params *IntegerParams, sk *SecretKey) *IntegerDecryptor {
return &IntegerDecryptor{
params: params,
shortDec: NewShortIntDecryptor(params.shortParams, sk),
}
}
// DecryptUint64 decrypts to a uint64 (for types <= 64 bits)
func (dec *IntegerDecryptor) DecryptUint64(rc *RadixCiphertext) uint64 {
var result uint64
for i, block := range rc.blocks {
blockValue := dec.shortDec.Decrypt(block)
result |= uint64(blockValue) << (i * rc.blockBits)
}
// Mask to the actual bit width
mask := uint64((1 << rc.fheType.NumBits()) - 1)
if rc.fheType.NumBits() >= 64 {
mask = ^uint64(0)
}
return result & mask
}
// DecryptBigInt decrypts to a big.Int (for any size)
func (dec *IntegerDecryptor) DecryptBigInt(rc *RadixCiphertext) *big.Int {
result := new(big.Int)
for i := len(rc.blocks) - 1; i >= 0; i-- {
blockValue := dec.shortDec.Decrypt(rc.blocks[i])
result.Lsh(result, uint(rc.blockBits))
result.Or(result, big.NewInt(int64(blockValue)))
}
return result
}
// DecryptBool decrypts a boolean
func (dec *IntegerDecryptor) DecryptBool(rc *RadixCiphertext) bool {
if len(rc.blocks) == 0 {
return false
}
return dec.shortDec.Decrypt(rc.blocks[0]) != 0
}
// Decrypt4 decrypts a 4-bit value
func (dec *IntegerDecryptor) Decrypt4(rc *RadixCiphertext) uint8 {
return uint8(dec.DecryptUint64(rc) & 0xF)
}
// Decrypt8 decrypts an 8-bit value
func (dec *IntegerDecryptor) Decrypt8(rc *RadixCiphertext) uint8 {
return uint8(dec.DecryptUint64(rc))
}
// Decrypt16 decrypts a 16-bit value
func (dec *IntegerDecryptor) Decrypt16(rc *RadixCiphertext) uint16 {
return uint16(dec.DecryptUint64(rc))
}
// Decrypt32 decrypts a 32-bit value
func (dec *IntegerDecryptor) Decrypt32(rc *RadixCiphertext) uint32 {
return uint32(dec.DecryptUint64(rc))
}
// Decrypt64 decrypts a 64-bit value
func (dec *IntegerDecryptor) Decrypt64(rc *RadixCiphertext) uint64 {
return dec.DecryptUint64(rc)
}
// IntegerEvaluator performs operations on radix integers
type IntegerEvaluator struct {
params *IntegerParams
shortEval *ShortIntEvaluator
boolEval *Evaluator // For boolean operations
}
// NewIntegerEvaluator creates a new integer evaluator
// NewIntegerEvaluator creates a new integer evaluator
// SECURITY: No secret key is required - uses public key switching for bootstrapping.
func NewIntegerEvaluator(params *IntegerParams, bsk *BootstrapKey) *IntegerEvaluator {
return &IntegerEvaluator{
params: params,
shortEval: NewShortIntEvaluator(params.shortParams, bsk),
boolEval: NewEvaluator(params.fheParams, bsk),
}
}
// Add performs radix addition with carry propagation
func (eval *IntegerEvaluator) Add(a, b *RadixCiphertext) (*RadixCiphertext, error) {
if a.fheType != b.fheType {
return nil, fmt.Errorf("type mismatch: %s vs %s", a.fheType, b.fheType)
}
if len(a.blocks) != len(b.blocks) {
return nil, fmt.Errorf("block count mismatch: %d vs %d", len(a.blocks), len(b.blocks))
}
numBlocks := len(a.blocks)
resultBlocks := make([]*ShortInt, numBlocks)
var carry *Ciphertext
for i := 0; i < numBlocks; i++ {
var sum *ShortInt
var newCarry *Ciphertext
var err error
if carry == nil {
// First block: simple add
sum, newCarry, err = eval.shortEval.AddWithCarry(a.blocks[i], b.blocks[i])
} else {
// Add a and b first
sumAB, carryAB, err := eval.shortEval.AddWithCarry(a.blocks[i], b.blocks[i])
if err != nil {
return nil, fmt.Errorf("block %d add: %w", i, err)
}
// Add carry from previous block to current sum
// The carry is an encrypted bit. We need to add it to sumAB.
// Convert carry to ShortInt format and add to sumAB
sumWithCarry, carryFromSum, err := eval.addCarryToBlock(sumAB, carry)
if err != nil {
return nil, fmt.Errorf("block %d carry add: %w", i, err)
}
// Combine carries: newCarry = carryAB OR carryFromSum
// Both are encrypted bits indicating overflow
newCarry, err = eval.boolEval.OR(carryAB, carryFromSum)
if err != nil {
return nil, fmt.Errorf("block %d carry combine: %w", i, err)
}
sum = sumWithCarry
}
if err != nil {
return nil, fmt.Errorf("block %d: %w", i, err)
}
resultBlocks[i] = sum
carry = newCarry
}
return &RadixCiphertext{
blocks: resultBlocks,
blockBits: a.blockBits,
numBlocks: numBlocks,
fheType: a.fheType,
}, nil
}
// addCarryToBlock adds an encrypted carry bit to a ShortInt block
// Returns the sum and a new carry bit (1 if addition overflowed)
func (eval *IntegerEvaluator) addCarryToBlock(block *ShortInt, carry *Ciphertext) (*ShortInt, *Ciphertext, error) {
// The carry is encoded as an encrypted boolean.
// We need to add it (as 0 or 1) to the block.
//
// Create a ShortInt containing the carry value (0 or 1)
// by using a conditional: if carry then 1 else 0
// Create trivial encryptions of 0 and 1
zero, err := eval.shortEval.EncryptTrivial(0)
if err != nil {
return nil, nil, err
}
one, err := eval.shortEval.EncryptTrivial(1)
if err != nil {
return nil, nil, err
}
// Select between 0 and 1 based on carry bit using MUX
// MUX(sel, trueVal, falseVal) = sel ? trueVal : falseVal
carryAsShort, err := eval.selectShortInt(carry, one, zero)
if err != nil {
return nil, nil, err
}
// Now add block + carryAsShort
return eval.shortEval.AddWithCarry(block, carryAsShort)
}
// selectShortInt selects between two ShortInts based on an encrypted boolean selector
func (eval *IntegerEvaluator) selectShortInt(selector *Ciphertext, trueVal, falseVal *ShortInt) (*ShortInt, error) {
// Use MUX operation: result = selector ? trueVal : falseVal
// Implemented as: (selector AND trueVal) OR (NOT(selector) AND falseVal)
// For ShortInt, we use the underlying ciphertext operations
// Since ShortInt holds a value in [0, msgSpace), we need to
// compute: result = selector * trueVal + (1-selector) * falseVal
// Using LUT-based evaluation
msgSpace := trueVal.msgSpace
scale := rlwe.NewScale(float64(eval.params.fheParams.QBR()) / float64(2*msgSpace))
// Combine selector with trueVal and falseVal for bivariate evaluation
// We add the ciphertexts in a specific encoding to enable LUT evaluation
// Simpler approach: use the boolean selector directly with scalar multiplication
// result = selector * (trueVal - falseVal) + falseVal
// = selector * delta + falseVal
// where delta = trueVal - falseVal
// For our case (trueVal=1, falseVal=0), result = selector * 1 + 0 = selector
// So we just need to convert the boolean selector to a ShortInt
// Create MUX LUT that evaluates the selection
selectLUT := blindrot.InitTestPolynomial(func(x float64) float64 {
// x encodes the selector in [-1, 1] where -1 = false, 1 = true
if x > 0 {
// selector is true, return trueVal (1)
return float64(1)*2/float64(msgSpace) - 1
}
// selector is false, return falseVal (0)
return float64(0)*2/float64(msgSpace) - 1
}, scale, eval.shortEval.ringQBR, -1, 1)
resultCt, err := eval.shortEval.bootstrap(selector.Ciphertext, &selectLUT)
if err != nil {
return nil, err
}
return &ShortInt{
ct: resultCt,
msgBits: trueVal.msgBits,
msgSpace: trueVal.msgSpace,
}, nil
}
// ScalarAdd adds a scalar to a radix integer
// This uses encrypted addition to properly handle carries
func (eval *IntegerEvaluator) ScalarAdd(a *RadixCiphertext, scalar uint64) (*RadixCiphertext, error) {
// For proper carry propagation, we encrypt the scalar and use encrypted addition
// This is slower but guarantees correctness
// Encrypt the scalar as a trivial ciphertext (no noise, plaintext encoded in ciphertext)
scalarCt, err := eval.encryptScalar(scalar, a.fheType, a.blockBits)
if err != nil {
return nil, fmt.Errorf("encrypt scalar: %w", err)
}
// Use encrypted addition which handles carries correctly
return eval.Add(a, scalarCt)
}
// encryptScalar creates a trivial encryption of a scalar (plaintext in ciphertext format)
func (eval *IntegerEvaluator) encryptScalar(scalar uint64, fheType FheUintType, blockBits int) (*RadixCiphertext, error) {
numBlocks := (fheType.NumBits() + blockBits - 1) / blockBits
blockMask := uint64((1 << blockBits) - 1)
blocks := make([]*ShortInt, numBlocks)
for i := 0; i < numBlocks; i++ {
blockValue := int((scalar >> (i * blockBits)) & blockMask)
block, err := eval.shortEval.EncryptTrivial(blockValue)
if err != nil {
return nil, fmt.Errorf("block %d: %w", i, err)
}
blocks[i] = block
}
return &RadixCiphertext{
blocks: blocks,
blockBits: blockBits,
numBlocks: numBlocks,
fheType: fheType,
}, nil
}
// Sub performs radix subtraction
func (eval *IntegerEvaluator) Sub(a, b *RadixCiphertext) (*RadixCiphertext, error) {
if a.fheType != b.fheType {
return nil, fmt.Errorf("type mismatch: %s vs %s", a.fheType, b.fheType)
}
numBlocks := len(a.blocks)
resultBlocks := make([]*ShortInt, numBlocks)
for i := 0; i < numBlocks; i++ {
result, err := eval.shortEval.Sub(a.blocks[i], b.blocks[i])
if err != nil {
return nil, fmt.Errorf("block %d: %w", i, err)
}
resultBlocks[i] = result
}
return &RadixCiphertext{
blocks: resultBlocks,
blockBits: a.blockBits,
numBlocks: numBlocks,
fheType: a.fheType,
}, nil
}
// ScalarSub subtracts a scalar from a radix integer
func (eval *IntegerEvaluator) ScalarSub(a *RadixCiphertext, scalar uint64) (*RadixCiphertext, error) {
numBlocks := len(a.blocks)
resultBlocks := make([]*ShortInt, numBlocks)
blockMask := (1 << a.blockBits) - 1
for i := 0; i < numBlocks; i++ {
scalarBlock := int((scalar >> (i * a.blockBits)) & uint64(blockMask))
result, err := eval.shortEval.ScalarSub(a.blocks[i], scalarBlock)
if err != nil {
return nil, fmt.Errorf("block %d: %w", i, err)
}
resultBlocks[i] = result
}
return &RadixCiphertext{
blocks: resultBlocks,
blockBits: a.blockBits,
numBlocks: numBlocks,
fheType: a.fheType,
}, nil
}
// ScalarMul multiplies a radix integer by a scalar
func (eval *IntegerEvaluator) ScalarMul(a *RadixCiphertext, scalar uint64) (*RadixCiphertext, error) {
// For small scalars, use repeated addition
// For larger scalars, use binary decomposition
if scalar == 0 {
// Return encryption of 0
enc := NewIntegerEncryptor(eval.params, nil) // Need proper key access
return enc.EncryptUint64(0, a.fheType)
}
if scalar == 1 {
// Return copy
return eval.copy(a), nil
}
// Binary multiplication: compute a * scalar using shift-and-add
result := eval.copy(a)
for i := 1; scalar > 1; i++ {
if scalar&1 == 1 {
var err error
result, err = eval.Add(result, a)
if err != nil {
return nil, err
}
}
scalar >>= 1
if scalar > 0 {
// Shift a left by one (multiply by 2)
a, _ = eval.ScalarAdd(a, 0) // This is a placeholder - need proper shift
}
}
return result, nil
}
// copy creates a copy of a RadixCiphertext
func (eval *IntegerEvaluator) copy(rc *RadixCiphertext) *RadixCiphertext {
blocks := make([]*ShortInt, len(rc.blocks))
for i, b := range rc.blocks {
blocks[i] = &ShortInt{
ct: b.ct.CopyNew(),
msgBits: b.msgBits,
msgSpace: b.msgSpace,
}
}
return &RadixCiphertext{
blocks: blocks,
blockBits: rc.blockBits,
numBlocks: rc.numBlocks,
fheType: rc.fheType,
}
}
// Neg negates a radix integer (two's complement)
func (eval *IntegerEvaluator) Neg(a *RadixCiphertext) (*RadixCiphertext, error) {
// Two's complement: -a = ~a + 1
numBlocks := len(a.blocks)
resultBlocks := make([]*ShortInt, numBlocks)
for i := 0; i < numBlocks; i++ {
negated, err := eval.shortEval.Neg(a.blocks[i])
if err != nil {
return nil, err
}
resultBlocks[i] = negated
}
result := &RadixCiphertext{
blocks: resultBlocks,
blockBits: a.blockBits,
numBlocks: numBlocks,
fheType: a.fheType,
}
// Add 1 for two's complement
return eval.ScalarAdd(result, 1)
}
// ========== Multiplication, Division, and Remainder ==========
// Mul performs encrypted multiplication: a * b
// Uses schoolbook multiplication with block-level operations.
// For each block of b, multiplies a by that block's value and shifts appropriately.
// Complexity: O(n^2) block operations for n blocks.
func (eval *IntegerEvaluator) Mul(a, b *RadixCiphertext) (*RadixCiphertext, error) {
if a.fheType != b.fheType {
return nil, fmt.Errorf("type mismatch: %s vs %s", a.fheType, b.fheType)
}
if len(a.blocks) != len(b.blocks) {
return nil, fmt.Errorf("block count mismatch: %d vs %d", len(a.blocks), len(b.blocks))
}
numBlocks := len(a.blocks)
blockBits := a.blockBits
// Initialize result to zero
result, err := eval.zeroRadix(a.fheType)
if err != nil {
return nil, fmt.Errorf("init zero: %w", err)
}
// Schoolbook multiplication at block level:
// For each block b[i], compute partial = a * b[i] * (base^i)
// where base = 2^blockBits
// Sum all partials
for i := 0; i < numBlocks; i++ {
// Multiply a by block b[i] (scalar multiplication per block)
partial, err := eval.mulByBlock(a, b.blocks[i], i, blockBits)
if err != nil {
return nil, fmt.Errorf("block %d multiply: %w", i, err)
}
// Add partial to result
result, err = eval.Add(result, partial)
if err != nil {
return nil, fmt.Errorf("block %d accumulate: %w", i, err)
}
}
return result, nil
}
// mulByBlock multiplies a RadixCiphertext by a single encrypted block
// and shifts the result by shiftBlocks positions (i.e., multiplies by base^shiftBlocks)
func (eval *IntegerEvaluator) mulByBlock(a *RadixCiphertext, block *ShortInt, shiftBlocks, blockBits int) (*RadixCiphertext, error) {
numBlocks := len(a.blocks)
// Result has same structure as a, but shifted
resultBlocks := make([]*ShortInt, numBlocks)
// Initialize lower blocks to zero (due to shift)
for i := 0; i < shiftBlocks && i < numBlocks; i++ {
zero, err := eval.shortEval.EncryptTrivial(0)
if err != nil {
return nil, err
}
resultBlocks[i] = zero
}
// For each block of a (that fits after shift), multiply by block
// This requires a two-input multiplication LUT for blocks
for i := 0; i+shiftBlocks < numBlocks && i < len(a.blocks); i++ {
destIdx := i + shiftBlocks
// Multiply a.blocks[i] by block using LUT
product, err := eval.mulBlocks(a.blocks[i], block)
if err != nil {
return nil, fmt.Errorf("block %d mul: %w", i, err)
}
resultBlocks[destIdx] = product
}
// Fill remaining blocks with zeros if any
for i := len(a.blocks) + shiftBlocks; i < numBlocks; i++ {
zero, err := eval.shortEval.EncryptTrivial(0)
if err != nil {
return nil, err
}
resultBlocks[i] = zero
}
return &RadixCiphertext{
blocks: resultBlocks,
blockBits: a.blockBits,
numBlocks: numBlocks,
fheType: a.fheType,
}, nil
}
// mulBlocks multiplies two encrypted blocks using a bivariate LUT
// Returns the lower bits of the product (upper bits/carry handled separately)
func (eval *IntegerEvaluator) mulBlocks(a, b *ShortInt) (*ShortInt, error) {
msgSpace := a.msgSpace
// Create bivariate multiplication LUT
// We combine a and b into single input by adding their ciphertexts
// Then use LUT to compute (a * b) mod msgSpace
sum := eval.shortEval.addCiphertexts(a.ct, b.ct)
scale := rlwe.NewScale(float64(eval.params.fheParams.QBR()) / float64(2*msgSpace*msgSpace))
mulLUT := blindrot.InitTestPolynomial(func(x float64) float64 {
// Decode combined input to get a and b
combined := int((x + 1) * float64(msgSpace*msgSpace) / 2)
aVal := combined / msgSpace
bVal := combined % msgSpace
if aVal >= msgSpace {
aVal = msgSpace - 1
}
if bVal >= msgSpace {
bVal = msgSpace - 1
}
result := (aVal * bVal) % msgSpace
return float64(result)*2/float64(msgSpace) - 1
}, scale, eval.shortEval.ringQBR, -1, 1)
resultCt, err := eval.shortEval.bootstrap(sum, &mulLUT)
if err != nil {
return nil, err
}
return &ShortInt{
ct: resultCt,
msgBits: a.msgBits,
msgSpace: a.msgSpace,
}, nil
}
// Div performs encrypted division: a / b (unsigned)
// Uses binary long division algorithm.
// Note: Division by zero returns max value (all 1s) per EVM semantics.
func (eval *IntegerEvaluator) Div(a, b *RadixCiphertext) (*RadixCiphertext, error) {
if a.fheType != b.fheType {
return nil, fmt.Errorf("type mismatch: %s vs %s", a.fheType, b.fheType)
}
if len(a.blocks) != len(b.blocks) {
return nil, fmt.Errorf("block count mismatch: %d vs %d", len(a.blocks), len(b.blocks))
}
_ = len(a.blocks) // numBlocks - reserved for future optimization
totalBits := a.NumBits()
// Check if b is zero
bIsZero, err := eval.isZeroRadix(b)
if err != nil {
return nil, fmt.Errorf("zero check: %w", err)
}
// Initialize quotient and remainder
quotient := make([]*Ciphertext, totalBits)
remainder, err := eval.zeroRadix(a.fheType)
if err != nil {
return nil, fmt.Errorf("init remainder: %w", err)
}
// Process from MSB to LSB of dividend
for i := totalBits - 1; i >= 0; i-- {
// Shift remainder left by 1 bit
remainder, err = eval.Shl(remainder, 1)
if err != nil {
return nil, fmt.Errorf("bit %d shift: %w", i, err)
}
// Get bit i of a
blockIdx := i / a.blockBits
bitIdx := i % a.blockBits
aBit, err := eval.extractBit(a.blocks[blockIdx], bitIdx)
if err != nil {
return nil, fmt.Errorf("bit %d extract: %w", i, err)
}
// Set LSB of remainder to aBit
err = eval.setLSB(remainder, aBit)
if err != nil {
return nil, fmt.Errorf("bit %d setLSB: %w", i, err)
}
// Compare: remainder >= b
rGeB, err := eval.Ge(remainder, b)
if err != nil {
return nil, fmt.Errorf("bit %d compare: %w", i, err)
}
// quotient bit = rGeB
quotient[i] = &Ciphertext{rGeB.blocks[0].ct}
// If remainder >= b, remainder -= b
diff, err := eval.Sub(remainder, b)
if err != nil {
return nil, fmt.Errorf("bit %d subtract: %w", i, err)
}
remainder, err = eval.Select(rGeB, diff, remainder)
if err != nil {
return nil, fmt.Errorf("bit %d select: %w", i, err)
}
}
// Pack quotient bits back into blocks
result, err := eval.packBitsToRadix(quotient, a.fheType, a.blockBits)
if err != nil {
return nil, fmt.Errorf("pack quotient: %w", err)
}
// If b was zero, return max value
maxVal, err := eval.maxRadix(a.fheType)
if err != nil {
return nil, fmt.Errorf("max value: %w", err)
}
return eval.Select(bIsZero, maxVal, result)
}
// Rem performs encrypted remainder: a % b (unsigned)
// Returns remainder after division.
// Note: Remainder by zero returns a (dividend) per EVM semantics.
func (eval *IntegerEvaluator) Rem(a, b *RadixCiphertext) (*RadixCiphertext, error) {
if a.fheType != b.fheType {
return nil, fmt.Errorf("type mismatch: %s vs %s", a.fheType, b.fheType)
}
if len(a.blocks) != len(b.blocks) {
return nil, fmt.Errorf("block count mismatch: %d vs %d", len(a.blocks), len(b.blocks))
}
totalBits := a.NumBits()
// Check if b is zero
bIsZero, err := eval.isZeroRadix(b)
if err != nil {
return nil, fmt.Errorf("zero check: %w", err)
}
// Initialize remainder
remainder, err := eval.zeroRadix(a.fheType)
if err != nil {
return nil, fmt.Errorf("init remainder: %w", err)
}
// Process from MSB to LSB of dividend
for i := totalBits - 1; i >= 0; i-- {
// Shift remainder left by 1 bit
remainder, err = eval.Shl(remainder, 1)
if err != nil {
return nil, fmt.Errorf("bit %d shift: %w", i, err)
}
// Get bit i of a
blockIdx := i / a.blockBits
bitIdx := i % a.blockBits
aBit, err := eval.extractBit(a.blocks[blockIdx], bitIdx)
if err != nil {
return nil, fmt.Errorf("bit %d extract: %w", i, err)
}
// Set LSB of remainder to aBit
err = eval.setLSB(remainder, aBit)
if err != nil {
return nil, fmt.Errorf("bit %d setLSB: %w", i, err)
}
// Compare: remainder >= b
rGeB, err := eval.Ge(remainder, b)
if err != nil {
return nil, fmt.Errorf("bit %d compare: %w", i, err)
}
// If remainder >= b, remainder -= b
diff, err := eval.Sub(remainder, b)
if err != nil {
return nil, fmt.Errorf("bit %d subtract: %w", i, err)
}
remainder, err = eval.Select(rGeB, diff, remainder)
if err != nil {
return nil, fmt.Errorf("bit %d select: %w", i, err)
}
}
// If b was zero, return a
return eval.Select(bIsZero, a, remainder)
}
// isZeroRadix checks if a RadixCiphertext is zero
func (eval *IntegerEvaluator) isZeroRadix(a *RadixCiphertext) (*RadixCiphertext, error) {
// Check if all blocks are zero, OR them together
// A value is zero iff all blocks are zero
var result *Ciphertext
for i, block := range a.blocks {
isZero, err := eval.isZeroBlock(block)
if err != nil {
return nil, fmt.Errorf("block %d: %w", i, err)
}
if result == nil {
result = isZero
} else {
// All blocks must be zero: AND the isZero results
result, err = eval.boolEval.AND(result, isZero)
if err != nil {
return nil, err
}
}
}
return eval.boolToRadix(result, FheBool)
}
// maxRadix returns a RadixCiphertext with all blocks at maximum value
func (eval *IntegerEvaluator) maxRadix(t FheUintType) (*RadixCiphertext, error) {
numBlocks := (t.NumBits() + eval.params.blockBits - 1) / eval.params.blockBits
maxBlockVal := (1 << eval.params.blockBits) - 1
blocks := make([]*ShortInt, numBlocks)
for i := 0; i < numBlocks; i++ {
block, err := eval.shortEval.EncryptTrivial(maxBlockVal)
if err != nil {
return nil, err
}
blocks[i] = block
}
return &RadixCiphertext{
blocks: blocks,
blockBits: eval.params.blockBits,
numBlocks: numBlocks,
fheType: t,
}, nil
}
// extractBit extracts a single bit from a ShortInt block
func (eval *IntegerEvaluator) extractBit(block *ShortInt, bitIdx int) (*Ciphertext, error) {
msgSpace := block.msgSpace
scale := rlwe.NewScale(float64(eval.params.fheParams.QBR()) / float64(2*msgSpace))
extractLUT := blindrot.InitTestPolynomial(func(x float64) float64 {
val := int((x + 1) * float64(msgSpace) / 2)
if val >= msgSpace {
val = msgSpace - 1
}
if val < 0 {
val = 0
}
bit := (val >> bitIdx) & 1
if bit == 1 {
return 1.0
}
return -1.0
}, scale, eval.shortEval.ringQBR, -1, 1)
resultCt, err := eval.shortEval.bootstrap(block.ct, &extractLUT)
if err != nil {
return nil, err
}
return &Ciphertext{resultCt}, nil
}
// setLSB sets the LSB of a RadixCiphertext from an encrypted bit
func (eval *IntegerEvaluator) setLSB(r *RadixCiphertext, bit *Ciphertext) error {
// The LSB is in block 0, bit 0
// We need to: (block0 & ~1) | bit
// Simpler: for division, we can clear LSB and OR in the bit