forked from Alibaba-Gemini-Lab/OpenPEGASUS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlwe_estimator.py
3186 lines (2532 loc) · 106 KB
/
lwe_estimator.py
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
# -*- coding: utf-8 -*-
"""
Cost estimates for solving LWE.
.. moduleauthor:: Martin R. Albrecht <martinralbrecht@googlemail.com>
# Supported Secret Distributions #
The following distributions for the secret are supported:
- ``"normal"`` : normal form instances, i.e. the secret follows the noise distribution (alias: ``True``)
- ``"uniform"`` : uniform mod q (alias: ``False``)
- ``(a,b)`` : uniform in the interval ``[a,…,b]``
- ``((a,b), h)`` : exactly ``h`` components are ``∈ [a,…,b]∖\\{0\\}``, all other components are zero
"""
# Imports
import sage.all
from collections import OrderedDict
from functools import partial
from sage.arith.srange import srange
from sage.calculus.var import var
from sage.functions.log import exp, log
from sage.functions.other import ceil, sqrt, floor, binomial
from sage.all import erf
from sage.interfaces.magma import magma
from sage.misc.all import cached_function
from sage.misc.all import prod
from sage.numerical.optimize import find_root
from sage.rings.all import QQ, RR, ZZ, RealField, PowerSeriesRing, RDF
from sage.rings.infinity import PlusInfinity
from sage.structure.element import parent
from sage.symbolic.all import pi, e
from scipy.optimize import newton
import logging
import sage.crypto.lwe
import math
oo = PlusInfinity()
class Logging:
"""
Control level of detail being printed.
"""
plain_logger = logging.StreamHandler()
plain_logger.setFormatter(logging.Formatter('%(message)s',))
detail_logger = logging.StreamHandler()
detail_logger.setFormatter(logging.Formatter('%(levelname)s:%(name)s: %(message)s',))
logging.getLogger("estimator").handlers = [plain_logger]
logging.getLogger("estimator").setLevel(logging.INFO)
loggers = ("binsearch", "repeat", "guess")
for logger in loggers:
logging.getLogger(logger).handlers = [detail_logger]
logging.getLogger(logger).setLevel(logging.INFO)
CRITICAL = logging.CRITICAL
ERROR = logging.ERROR
WARNING = logging.WARNING
INFO = logging.INFO
DEBUG = logging.DEBUG
NOTSET = logging.NOTSET
@staticmethod
def set_level(lvl, loggers=None):
"""Set logging level
:param lvl: one of `CRITICAL`, `ERROR`, `WARNING`, `INFO`, `DEBUG`, `NOTSET`
:param loggers: one of `Logging.loggers`, if `None` all loggers are used.
"""
if loggers is None:
loggers = Logging.loggers
for logger in loggers:
logging.getLogger(logger).setLevel(lvl)
# Utility Classes #
class OutOfBoundsError(ValueError):
"""
Used to indicate a wrong value, for example delta_0 < 1.
"""
pass
class InsufficientSamplesError(ValueError):
"""
Used to indicate the number of samples given is too small.
"""
pass
# Binary Search #
def binary_search_minimum(f, start, stop, param, extract=lambda x: x, *arg, **kwds):
"""
Return minimum of `f` if `f` is convex.
:param start: start of range to search
:param stop: stop of range to search (exclusive)
:param param: the parameter to modify when calling `f`
:param extract: comparison is performed on ``extract(f(param=?, *args, **kwds))``
"""
return binary_search(f, start, stop, param,
predictate=lambda x, best: extract(x)<=extract(best),
*arg, **kwds)
def binary_search(f, start, stop, param, predicate=lambda x, best: x<=best, *arg, **kwds):
"""
Searches for the best value in the interval [start,stop] depending on the given predicate.
:param start: start of range to search
:param stop: stop of range to search (exclusive)
:param param: the parameter to modify when calling `f`
:param predicate: comparison is performed by evaluating ``predicate(current, best)``
"""
kwds[param] = stop
D = {}
D[stop] = f(*arg, **kwds)
best = D[stop]
b = ceil((start+stop)/2)
direction = 0
while True:
if b not in D:
kwds[param] = b
D[b] = f(*arg, **kwds)
if b == start:
best = D[start]
break
if not predicate(D[b], best):
if direction == 0:
start = b
b = ceil((stop+b)/2)
else:
stop = b
b = floor((start+b)/2)
else:
best = D[b]
logging.getLogger("binsearch").debug(u"%4d, %s"%(b, best))
if b-1 not in D:
kwds[param] = b-1
D[b-1] = f(*arg, **kwds)
if predicate(D[b-1], best):
stop = b
b = floor((b+start)/2)
direction = 0
else:
if b+1 not in D:
kwds[param] = b+1
D[b+1] = f(*arg, **kwds)
if not predicate(D[b+1], best):
break
else:
start = b
b = ceil((stop+b)/2)
direction = 1
return best
class Param:
"""
Namespace for processing LWE parameter sets.
"""
@staticmethod
def Regev(n, m=None, dict=False):
"""
:param n: LWE dimension `n > 0`
:param m: number of LWE samples `m > 0`
:param dict: return a dictionary
"""
if dict:
return Param.dict(sage.crypto.lwe.Regev(n=n, m=m))
else:
return Param.tuple(sage.crypto.lwe.Regev(n=n, m=m))
@staticmethod
def LindnerPeikert(n, m=None, dict=False):
"""
:param n: LWE dimension `n > 0`
:param m: number of LWE samples `m > 0`
:param dict: return a dictionary
"""
if dict:
return Param.dict(sage.crypto.lwe.LindnerPeikert(n=n, m=m))
else:
return Param.tuple(sage.crypto.lwe.LindnerPeikert(n=n, m=m))
@staticmethod
def tuple(lwe):
"""
Return (n, α, q) given an LWE instance object.
:param lwe: LWE object
:returns: (n, α, q)
"""
n = lwe.n
q = lwe.K.order()
try:
alpha = alphaf(sigmaf(lwe.D.sigma), q)
except AttributeError:
# older versions of Sage use stddev, not sigma
alpha = alphaf(sigmaf(lwe.D.stddev), q)
return n, alpha, q
@staticmethod
def dict(lwe):
"""
Return dictionary consisting of n, α, q and samples given an LWE instance object.
:param lwe: LWE object
:returns: "n": n, "alpha": α, "q": q, "samples": samples
:rtype: dictionary
"""
n, alpha, q = Param.tuple(lwe)
m = lwe.m if lwe.m else oo
return {"n": n, "alpha": alpha, "q": q, "m": m}
@staticmethod
def preprocess(n, alpha, q, success_probability=None, prec=None, m=oo):
"""
Check if parameters n, α, q are sound and return correct types.
Also, if given, the soundness of the success probability and the
number of samples is ensured.
"""
if n < 1:
raise ValueError("LWE dimension must be greater than 0.")
if alpha <= 0:
raise ValueError("Fraction of noise must be > 0.")
if q < 1:
raise ValueError("LWE modulus must be greater than 0.")
if m is not None and m < 1:
raise InsufficientSamplesError(u"m=%d < 1"%m)
if prec is None:
try:
prec = alpha.prec()
except AttributeError:
pass
try:
prec = max(success_probability.prec(), prec)
except AttributeError:
pass
if prec < 128:
prec = 128
RR = RealField(prec)
n, alpha, q = ZZ(n), RR(alpha), ZZ(q),
if m is not oo:
m = ZZ(m)
if success_probability is not None:
if success_probability >= 1 or success_probability <= 0:
raise ValueError("success_probability must be between 0 and 1.")
return n, alpha, q, RR(success_probability)
else:
return n, alpha, q
# Error Parameter Conversions
def stddevf(sigma):
"""
Gaussian width parameter σ → standard deviation
:param sigma: Gaussian width parameter σ
EXAMPLE::
sage: from estimator import stddevf
sage: stddevf(64.0)
25.532...
sage: stddevf(64)
25.532...
sage: stddevf(RealField(256)(64)).prec()
256
"""
try:
prec = parent(sigma).prec()
except AttributeError:
prec = 0
if prec > 0:
FF = parent(sigma)
else:
FF = RR
return FF(sigma)/FF(sqrt(2*pi))
def sigmaf(stddev):
"""
standard deviation → Gaussian width parameter σ
:param sigma: standard deviation
EXAMPLE::
sage: from estimator import stddevf, sigmaf
sage: n = 64.0
sage: sigmaf(stddevf(n))
64.000...
"""
RR = parent(stddev)
return RR(sqrt(2*pi))*stddev
def alphaf(sigma, q, sigma_is_stddev=False):
"""
Gaussian width σ, modulus q → noise rate α
:param sigma: Gaussian width parameter (or standard deviation if ``sigma_is_stddev`` is set)
:param q: modulus `0 < q`
:param sigma_is_stddev: if set then `sigma` is interpreted as the standard deviation
:returns: α = σ/q or σ·sqrt(2π)/q depending on `sigma_is_stddev`
"""
if sigma_is_stddev is False:
return RR(sigma/q)
else:
return RR(sigmaf(sigma)/q)
class Cost:
"""
Algorithms costs.
"""
def __init__(self, data=None, **kwds):
"""
:param data: we call ``OrderedDict(data)``
"""
if data is None:
self.data = OrderedDict()
else:
self.data = OrderedDict(data)
for k, v in kwds.items():
self.data[k] = v
def str(self, keyword_width=None, newline=None, round_bound=2048, compact=False, unicode=True):
"""
:param keyword_width: keys are printed with this width
:param newline: insert a newline
:param round_bound: values beyond this bound are represented as powers of two
:param compact: do not add extra whitespace to align entries
:param unicode: use unicode to shorten representation
EXAMPLE::
sage: from estimator import Cost
sage: s = Cost({"delta_0":5, "bar":2})
sage: print(s)
bar: 2, delta_0: 5
sage: s = Cost([(u"delta_0", 5), ("bar",2)])
sage: print(s)
delta_0: 5, bar: 2
"""
if unicode:
unicode_replacements = {"delta_0": u"δ_0", "beta": u"β", "epsilon": u"ε"}
else:
unicode_replacements = {}
format_strings = {u"beta": u"%s: %4d", u"d": u"%s: %4d",
"b": "%s: %3d", "t1": "%s: %3d", "t2": "%s: %3d",
"l": "%s: %3d", "ncod": "%s: %3d", "ntop": "%s: %3d", "ntest": "%s: %3d"}
d = self.data
s = []
for k in d:
v = d[k]
kk = unicode_replacements.get(k, k)
if keyword_width:
fmt = u"%%%ds" % keyword_width
kk = fmt % kk
if not newline and k in format_strings:
s.append(format_strings[k]%(kk, v))
elif ZZ(1)/round_bound < v < round_bound or v == 0 or ZZ(-1)/round_bound > v > -round_bound:
try:
if compact:
s.append(u"%s: %d" % (kk, ZZ(v)))
else:
s.append(u"%s: %8d" % (kk, ZZ(v)))
except TypeError:
if v < 2.0 and v >= 0.0:
if compact:
s.append(u"%s: %.6f" % (kk, v))
else:
s.append(u"%s: %8.6f" % (kk, v))
else:
if compact:
s.append(u"%s: %.3f" % (kk, v))
else:
s.append(u"%s: %8.3f" % (kk, v))
else:
t = u"%s"%(u"≈" if unicode else "") + u"%s2^%.1f" % ("-" if v < 0 else "", log(abs(v), 2).n())
if compact:
s.append(u"%s: %s" % (kk, t))
else:
s.append(u"%s: %8s" % (kk, t))
if not newline:
if compact:
return u", ".join(s)
else:
return u", ".join(s)
else:
return u"\n".join(s)
def reorder(self, first):
"""
Return a new ordered dict from the key:value pairs in dictinonary but reordered such that the
``first`` keys come first.
:param dictionary: input dictionary
:param first: keys which should come first (in order)
EXAMPLE::
sage: from estimator import Cost
sage: d = Cost([("a",1),("b",2),("c",3)]); d
a: 1
b: 2
c: 3
sage: d.reorder( ["b","c","a"])
b: 2
c: 3
a: 1
"""
keys = list(self.data)
for key in first:
keys.pop(keys.index(key))
keys = list(first) + keys
r = OrderedDict()
for key in keys:
r[key] = self.data[key]
return Cost(r)
def filter(self, keys):
"""
Return new ordered dictinonary from dictionary restricted to the keys.
:param dictionary: input dictionary
:param keys: keys which should be copied (ordered)
"""
r = OrderedDict()
for key in keys:
r[key] = self.data[key]
return Cost(r)
def repeat(self, times, select=None, lll=None):
u"""
Return a report with all costs multiplied by `times`.
:param d: a cost estimate
:param times: the number of times it should be run
:param select: toggle which fields ought to be repeated and which shouldn't
:param lll: if set amplify lattice reduction times assuming the LLL algorithm suffices and costs ``lll``
:returns: a new cost estimate
We maintain a local dictionary which decides if an entry is multiplied by `times` or not.
For example, δ would not be multiplied but "#bop" would be. This check is strict such that
unknown entries raise an error. This is to enforce a decision on whether an entry should be
multiplied by `times` if the function `report` reports on is called `times` often.
EXAMPLE::
sage: from estimator import Param, dual
sage: n, alpha, q = Param.Regev(128)
sage: dual(n, alpha, q).repeat(2^10)
rop: 2^91.4
m: 2^18.6
red: 2^91.4
delta_0: 1.008810
beta: 111
d: 376
|v|: 736.521
repeat: 2^29.0
epsilon: 0.003906
sage: dual(n, alpha, q).repeat(1)
rop: 2^81.4
m: 376
red: 2^81.4
delta_0: 1.008810
beta: 111
d: 376
|v|: 736.521
repeat: 2^19.0
epsilon: 0.003906
"""
# TODO review this list
do_repeat = {
u"rop": True,
u"red": True,
u"babai": True,
u"babai_op": True,
u"epsilon": False,
u"mem": False,
u"delta_0": False,
u"beta": False,
u"k": False,
u"D_reg": False,
u"t": False,
u"m": True,
u"d": False,
u"|v|": False,
u"amplify": False,
u"repeat": False, # we deal with it below
u"c": False,
}
if lll and self["red"] != self["rop"]:
raise ValueError("Amplification via LLL was requested but 'red' != 'rop'")
if select is not None:
for key in select:
do_repeat[key] = select[key]
ret = OrderedDict()
for key in self.data:
try:
if do_repeat[key]:
if lll and key in ("red", "rop"):
ret[key] = self[key] + times * lll
else:
ret[key] = times * self[key]
else:
ret[key] = self.data[key]
except KeyError:
raise NotImplementedError(u"You found a bug, this function does not know about '%s' but should."%key)
ret[u"repeat"] = times * ret.get("repeat", 1)
return Cost(ret)
def __rmul__(self, times):
return self.repeat(times)
def combine(self, right, base=None):
"""Combine ``left`` and ``right``.
:param left: cost dictionary
:param right: cost dictionary
:param base: add entries to ``base``
"""
if base is None:
cost = Cost()
else:
cost = base
for key in self.data:
cost[key] = self.data[key]
for key in right:
cost[key] = right.data[key]
return Cost(cost)
def __add__(self, other):
return self.combine(self, other)
def __getitem__(self, key):
return self.data[key]
def __setitem__(self, key, value):
self.data[key] = value
def __iter__(self):
return iter(self.data)
def values(self):
return self.data.values()
def __str__(self):
return self.str(unicode=False, compact=True)
def __repr__(self):
return self.str(unicode=False, newline=True, keyword_width=12)
def __unicode__(self):
return self.str(unicode=True)
class SDis:
"""
Distributions of Secrets.
"""
@staticmethod
def is_sparse(secret_distribution):
"""Return true if the secret distribution is sparse
:param secret_distribution: distribution of secret, see module level documentation for details
EXAMPLES::
sage: from estimator import SDis
sage: SDis.is_sparse(True)
False
sage: SDis.is_sparse(((-1, 1), 64))
True
sage: SDis.is_sparse(((-3, 3), 64))
True
sage: SDis.is_sparse((-3, 3))
False
"""
try:
(a, b), h = secret_distribution
# TODO we could check h against n but then this function would have to depend on n
return True
except (TypeError, ValueError):
return False
@staticmethod
def is_small(secret_distribution):
"""Return true if the secret distribution is small
:param secret_distribution: distribution of secret, see module level documentation for details
EXAMPLES::
sage: from estimator import SDis
sage: SDis.is_small(False)
False
sage: SDis.is_small(True)
True
sage: SDis.is_small(((-1, 1), 64))
True
sage: SDis.is_small(((-3, 3), 64))
True
sage: SDis.is_small((-3, 3))
True
"""
if secret_distribution == "normal" or secret_distribution is True:
return True
try:
(a, b), h = secret_distribution
return True
except (TypeError, ValueError):
try:
(a, b) = secret_distribution
return True
except (TypeError, ValueError):
return False
@staticmethod
def bounds(secret_distribution):
"""Return bounds of secret distribution
:param secret_distribution: distribution of secret, see module level documentation for details
EXAMPLES::
sage: from estimator import SDis
sage: SDis.bounds(False)
Traceback (most recent call last):
...
ValueError: Cannot extract bounds for secret.
sage: SDis.bounds(True)
Traceback (most recent call last):
...
ValueError: Cannot extract bounds for secret.
sage: SDis.bounds(((-1, 1), 64))
(-1, 1)
sage: SDis.bounds(((-3, 3), 64))
(-3, 3)
sage: SDis.bounds((-3, 3))
(-3, 3)
"""
try:
(a, b) = secret_distribution
try:
(a, b), _ = (a, b) # noqa
except (TypeError, ValueError):
pass
return a, b
except (TypeError, ValueError):
raise ValueError("Cannot extract bounds for secret.")
@staticmethod
def is_bounded_uniform(secret_distribution):
"""Return true if the secret is bounded uniform (sparse or not).
:param secret_distribution: distribution of secret, see module level documentation for
details
EXAMPLES::
sage: from estimator import SDis
sage: SDis.is_bounded_uniform(False)
False
sage: SDis.is_bounded_uniform(True)
False
sage: SDis.is_bounded_uniform(((-1, 1), 64))
True
sage: SDis.is_bounded_uniform(((-3, 3), 64))
True
sage: SDis.is_bounded_uniform((-3, 3))
True
.. note :: This function requires the bounds to be of opposite sign, as scaling code does
not handle the other case.
"""
try:
# next will fail if not bounded_uniform
a, b = SDis.bounds(secret_distribution)
# check bounds are around 0, otherwise not implemented
if a <= 0 and 0 <= b:
return True
except (TypeError, ValueError):
pass
return False
@staticmethod
def is_ternary(secret_distribution):
"""Return true if the secret is ternary (sparse or not)
:param secret_distribution: distribution of secret, see module level documentation for details
EXAMPLES::
sage: from estimator import SDis
sage: SDis.is_ternary(False)
False
sage: SDis.is_ternary(True)
False
sage: SDis.is_ternary(((-1, 1), 64))
True
sage: SDis.is_ternary((-1, 1))
True
sage: SDis.is_ternary(((-3, 3), 64))
False
sage: SDis.is_ternary((-3, 3))
False
"""
if SDis.is_bounded_uniform(secret_distribution):
a, b = SDis.bounds(secret_distribution)
if a == -1 and b == 1:
return True
return False
@staticmethod
def nonzero(secret_distribution, n):
"""Return number of non-zero elements or ``None``
:param secret_distribution: distribution of secret, see module level documentation for details
:param n: LWE dimension `n > 0`
"""
try:
(a, b) = secret_distribution
try:
(a, b), h = (a, b) # noqa
return h
except (TypeError, ValueError):
if n is None:
raise ValueError("Parameter n is required for sparse secrets.")
B = ZZ(b - a + 1)
h = ceil((B-1)/B * n)
return h
except (TypeError, ValueError):
raise ValueError("Cannot extract `h`.")
@staticmethod
def mean(secret_distribution, q=None, n=None):
"""
Mean of the secret per component.
:param secret_distribution: distribution of secret, see module level documentation for details
:param n: only used for sparse secrets
EXAMPLE::
sage: from estimator import SDis
sage: SDis.mean(True)
0
sage: SDis.mean(False, q=10)
0
sage: SDis.mean(((-3,3)))
0
sage: SDis.mean(((-3,3),64), n=256)
0
sage: SDis.mean(((-3,2)))
-1/2
sage: SDis.mean(((-3,2),64), n=256)
-3/20
"""
if not SDis.is_small(secret_distribution):
# uniform distribution variance
if q is None:
raise ValueError("Parameter q is required for uniform secret.")
a = -floor(q/2)
b = floor(q/2)
return (a + b)/ZZ(2)
else:
try:
a, b = SDis.bounds(secret_distribution)
try:
(a, b), h = secret_distribution
if n is None:
raise ValueError("Parameter n is required for sparse secrets.")
return h/ZZ(n) * (b*(b+1)-a*(a-1))/(2*(b-a))
except (TypeError, ValueError):
return (a + b)/ZZ(2)
except ValueError:
# small with no bounds, it's normal
return ZZ(0)
@staticmethod
def variance(secret_distribution, alpha=None, q=None, n=None):
"""
Variance of the secret per component.
:param secret_distribution: distribution of secret, see module level documentation for details
:param alpha: only used for normal form LWE
:param q: only used for normal form LWE
:param n: only used for sparse secrets
EXAMPLE::
sage: from estimator import SDis
sage: SDis.variance(True, 8./2^15, 2^15).sqrt().n()
3.19...
sage: SDis.variance((-3,3), 8./2^15, 2^15)
4
sage: SDis.variance(((-3,3),64), 8./2^15, 2^15, n=256)
7/6
sage: SDis.variance((-3,2))
35/12
sage: SDis.variance(((-3,2),64), n=256)
371/400
sage: SDis.variance((-1,1), 8./2^15, 2^15)
2/3
sage: SDis.variance(((-1,1),64), 8./2^15, 2^15, n=256)
1/4
.. note :: This function assumes that the bounds are of opposite sign, and that the
distribution is centred around zero.
"""
if not SDis.is_small(secret_distribution):
# uniform distribution variance
a = -floor(q/2)
b = floor(q/2)
n = b - a + 1
return (n**2 - 1)/ZZ(12)
else:
try:
a, b = SDis.bounds(secret_distribution)
except ValueError:
# small with no bounds, it's normal
return stddevf(alpha*q)**2
try:
(a, b), h = secret_distribution
except (TypeError, ValueError):
return ((b - a + 1)**2 - 1)/ZZ(12)
if n is None:
raise ValueError("Parameter n is required for sparse secrets.")
if not (a <= 0 and 0 <= b):
raise ValueError("a <= 0 and 0 <= b is required for uniform bounded secrets.")
# E(x^2), using https://en.wikipedia.org/wiki/Square_pyramidal_number
tt = (h/ZZ(n))*(2*b**3 + 3*b**2 + b - 2*a**3 + 3*a**2 - a)/(ZZ(6)*(b-a))
# Var(x) = E(x^2) - E(x)^2
return tt-SDis.mean(secret_distribution, n=n)**2
def switch_modulus(f, n, alpha, q, secret_distribution, *args, **kwds):
"""
:param f: run f
:param n: LWE dimension `n > 0`
:param alpha: noise rate `0 ≤ α < 1`, noise will have standard deviation `αq/\\sqrt{2π}`
:param q: modulus `0 < q`
:param secret_distribution: distribution of secret, see module level documentation for details
"""
length = SDis.nonzero(secret_distribution, n)
s_var = SDis.variance(secret_distribution, alpha, q, n=n)
p = RR(ceil(sqrt(2*pi*s_var*length/ZZ(12)) / alpha))
if p < 32: # some random point
# we can't pretend everything is uniform any more, p is too small
p = RR(ceil(sqrt(2*pi*s_var*length*2/ZZ(12)) / alpha))
beta = RR(sqrt(2)*alpha)
return f(n, beta, p, secret_distribution, *args, **kwds)
# Repetition
def amplify(target_success_probability, success_probability, majority=False):
"""
Return the number of trials needed to amplify current `success_probability` to
`target_success_probability`
:param target_success_probability: targeted success probability < 1
:param success_probability: targeted success probability < 1
:param majority: if `True` amplify a deicsional problem, not a computational one
if `False` then we assume that we can check solutions, so one success suffices
:returns: number of required trials to amplify
"""
if target_success_probability < success_probability:
return ZZ(1)
if success_probability == 0.0:
return oo
prec = max(53,
2*ceil(abs(log(success_probability, 2))),
2*ceil(abs(log(1-success_probability, 2))),
2*ceil(abs(log(target_success_probability, 2))),
2*ceil(abs(log(1-target_success_probability, 2))))
prec = min(prec, 2048)
RR = RealField(prec)
success_probability = RR(success_probability)
target_success_probability = RR(target_success_probability)
try:
if majority:
eps = success_probability/2
return ceil(2*log(2 - 2*target_success_probability)/log(1 - 4*eps**2))
else:
# target_success_probability = 1 - (1-success_probability)^trials
return ceil(log(1-target_success_probability)/log(1 -success_probability))
except ValueError:
return oo
def amplify_sigma(target_advantage, sigma, q):
"""
Amplify distinguishing advantage for a given σ and q