add local copy of lwe-estimator

This commit is contained in:
Ben
2021-05-14 09:22:41 +01:00
parent 8d46ff521c
commit 16a6201a74
24 changed files with 4823 additions and 2 deletions

20
Makefile Normal file
View File

@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
SPHINXPROJ = LWEEstimator
SOURCEDIR = doc
BUILDDIR = doc/_build
# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
.PHONY: help Makefile
# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

View File

@@ -1,2 +0,0 @@
# estimator-issues
Solving some issues in the LWE Estimator

202
README.rst Normal file
View File

@@ -0,0 +1,202 @@
Security Estimates for the Learning with Errors Problem
=======================================================
This `Sage <http://sagemath.org>`__ module provides functions for estimating the concrete security
of `Learning with Errors <https://en.wikipedia.org/wiki/Learning_with_errors>`__ instances.
The main intend of this estimator is to give designers an easy way to choose parameters resisting
known attacks and to enable cryptanalysts to compare their results and ideas with other techniques
known in the literature.
Usage Examples
--------------
::
sage: load("estimator.py")
sage: n, alpha, q = Param.Regev(128)
sage: costs = estimate_lwe(n, alpha, q)
usvp: rop: ≈2^57.3, red: ≈2^57.3, δ_0: 1.009214, β: 101, d: 349, m: 220
dec: rop: ≈2^61.9, m: 229, red: ≈2^61.9, δ_0: 1.009595, β: 93, d: 357, babai: ≈2^46.8, babai_op: ≈2^61.9, repeat: 293, ε: 0.015625
dual: rop: ≈2^81.1, m: 380, red: ≈2^81.1, δ_0: 1.008631, β: 115, d: 380, |v|: 688.951, repeat: ≈2^17.0, ε: 0.007812
Online
------
You can `run the estimator
online <http://aleph.sagemath.org/?z=eJxNjcEKwjAQBe-F_kPoqYXYjZWkKHgQFPyLkOhii6mJyWrx782hiO84MPOcN9e6GohC2gHYkezrckdqfbzBZJwFN-MKE42TIR8hmhnOp8MRfqgNn6opiwdnxoXBcPZke9ZJxZlohRDbXknVSbGMMyXlpi-LhKTfGK1PWK-zr7O1NFHnz_ov2HwBPwsyhw==&lang=sage>`__
using the `Sage Math Cell <http://aleph.sagemath.org/>`__ server.
Coverage
--------
At present the following algorithms are covered by this estimator.
- meet-in-the-middle exhaustive search
- Coded-BKW [C:GuoJohSta15]
- dual-lattice attack and small/sparse secret variant [EC:Albrecht17]
- lattice-reduction + enumeration [RSA:LinPei11]
- primal attack via uSVP [USENIX:ADPS16,ACISP:BaiGal14]
- Arora-Ge algorithm [ICALP:AroGe11] using Gröbner bases
[EPRINT:ACFP14]
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
We note that distributions of the form ``(a,b)`` are assumed to be of fixed Hamming weight, with ``h = round((b-a)/(b-a+1) * n)``.
Above, we use `cryptobib <http://cryptobib.di.ens.fr>`__-style bibtex keys as references.
Documentation
-------------
Documentation for the ``estimator`` is available `here <https://lwe-estimator.readthedocs.io/>`__.
Evolution
---------
This code is evolving, new results are added and bugs are fixed. Hence, estimations from earlier
versions might not match current estimations. This is annoying but unavoidable at present. We
recommend to also state the commit that was used when referencing this project.
We also encourage authors to let us know if their paper uses this code. In particular, we thrive to
tag commits with those cryptobib ePrint references that use it. For example, `this commit
<https://bitbucket.org/malb/lwe-estimator/src/6295aa59048daa5d9598378386cb61887a1fe949/?at=EPRINT_Albrecht17>`__
corresponds to this `ePrint entry <https://ia.cr/2017/047>`__.
Contributions
-------------
Our intent is for this estimator to be maintained by the research community. For example, we
encourage algorithm designers to add their own algorithms to this estimator and we are happy to help
with that process.
More generally, all contributions such as bugfixes, documentation and tests are welcome. Please go
ahead and submit your pull requests. Also, dont forget to add yourself to the list of contributors
below in your pull requests.
At present, this estimator is maintained by Martin Albrecht. Contributors are:
- Benjamin Curtis
- Cedric Lefebvre
- Fernando Virdia
- Florian Göpfert
- James Owen
- Léo Ducas
- Markus Schmidt
- Martin Albrecht
- Rachel Player
- Sam Scott
Please follow `PEP8 <https://www.python.org/dev/peps/pep-0008/>`__ in your submissions. You can use
`flake8 <http://flake8.pycqa.org/en/latest/>`__ to check for compliance. We use the following flake8
configuration (to allow longer line numbers and more complex functions):
::
[flake8]
max-line-length = 120
max-complexity = 16
ignore = E22,E241
Bugs
----
If you run into a bug, please open an `issue on bitbucket
<https://bitbucket.org/malb/lwe-estimator/issues?status=new&status=open>`__. Also, please check
first if the issue has already been reported.
Citing
------
If you use this estimator in your work, please cite
| Martin R. Albrecht, Rachel Player and Sam Scott. *On the concrete hardness of Learning with Errors*.
| Journal of Mathematical Cryptology. Volume 9, Issue 3, Pages 169203, ISSN (Online) 1862-2984,
| ISSN (Print) 1862-2976 DOI: 10.1515/jmc-2015-0016, October 2015
A pre-print is available as
Cryptology ePrint Archive, Report 2015/046, 2015. https://eprint.iacr.org/2015/046
An updated version of the material covered in the above survey is available in
`Rachel Player's PhD thesis <https://pure.royalholloway.ac.uk/portal/files/29983580/2018playerrphd.pdf>`__.
License
-------
The esimator is licensed under the `LGPLv3+ <https://www.gnu.org/licenses/lgpl-3.0.en.html>`__ license.
Parameters from the Literature
------------------------------
The following estimates for various schemes from the literature illustrate the behaviour of the
``estimator``. These estimates do not necessarily correspond to the claimed security levels of the
respective schemes: for several parameter sets below the claimed security level by the designers is
lower than the complexity estimated by the ``estimator``. This is usually because the designers
anticipate potential future improvements to lattice-reduction algorithms and strategies. We
recommend to follow the designers decision. We intend to extend the estimator to cover these more
optimistic (from an attackers point of view) estimates in the future … pull requests welcome, as
always.
`New Hope <http://ia.cr/2015/1092>`__ ::
sage: load("estimator.py")
sage: n = 1024; q = 12289; stddev = sqrt(16/2); alpha = alphaf(sigmaf(stddev), q)
sage: _ = estimate_lwe(n, alpha, q, reduction_cost_model=BKZ.sieve)
usvp: rop: ≈2^313.1, red: ≈2^313.1, δ_0: 1.002094, β: 968, d: 2096, m: 1071
dec: rop: ≈2^410.0, m: 1308, red: ≈2^410.0, δ_0: 1.001763, β: 1213, d: 2332, babai: ≈2^395.5, babai_op: ≈2^410.6, repeat: ≈2^25.2, ε: ≈2^-23.0
dual: rop: ≈2^355.5, m: 1239, red: ≈2^355.5, δ_0: 1.001884, β: 1113, repeat: ≈2^307.0, d: 2263, c: 1
`Frodo <http://ia.cr/2016/659>`__ ::
sage: load("estimator.py")
sage: n = 752; q = 2^15; stddev = sqrt(1.75); alpha = alphaf(sigmaf(stddev), q)
sage: _ = estimate_lwe(n, alpha, q, reduction_cost_model=BKZ.sieve)
usvp: rop: ≈2^173.0, red: ≈2^173.0, δ_0: 1.003453, β: 490, d: 1448, m: 695
dec: rop: ≈2^208.3, m: 829, red: ≈2^208.3, δ_0: 1.003064, β: 579, d: 1581, babai: ≈2^194.5, babai_op: ≈2^209.6, repeat: 588, ε: 0.007812
dual: rop: ≈2^196.2, m: 836, red: ≈2^196.2, δ_0: 1.003104, β: 569, repeat: ≈2^135.0, d: 1588, c: 1
`TESLA <http://ia.cr/2015/755>`__ ::
sage: load("estimator.py")
sage: n = 804; q = 2^31 - 19; alpha = sqrt(2*pi)*57/q; m = 4972
sage: _ = estimate_lwe(n, alpha, q, m=m, reduction_cost_model=BKZ.sieve)
usvp: rop: ≈2^129.3, red: ≈2^129.3, δ_0: 1.004461, β: 339, d: 1937, m: 1132
dec: rop: ≈2^144.9, m: 1237, red: ≈2^144.9, δ_0: 1.004148, β: 378, d: 2041, babai: ≈2^130.9, babai_op: ≈2^146.0, repeat: 17, ε: 0.250000
dual: rop: ≈2^139.4, m: 1231, red: ≈2^139.4, δ_0: 1.004180, β: 373, repeat: ≈2^93.0, d: 2035, c: 1
`SEAL <https://www.microsoft.com/en-us/research/project/simple-encrypted-arithmetic-library/>`__ ::
sage: load("estimator.py")
sage: n = 2048; q = 2^54 - 2^24 + 1; alpha = 8/q; m = 2*n
sage: _ = estimate_lwe(n, alpha, q, secret_distribution=(-1,1), reduction_cost_model=BKZ.sieve, m=m)
Warning: the LWE secret is assumed to have Hamming weight 1365.
usvp: rop: ≈2^129.7, red: ≈2^129.7, δ_0: 1.004479, β: 337, d: 3914, m: 1865, repeat: 1, k: 0, postprocess: 0
dec: rop: ≈2^144.4, m: ≈2^11.1, red: ≈2^144.4, δ_0: 1.004154, β: 377, d: 4272, babai: ≈2^131.2, babai_op: ≈2^146.3, repeat: 7, ε: 0.500000
dual: rop: ≈2^134.2, m: ≈2^11.0, red: ≈2^134.2, δ_0: 1.004353, β: 352, repeat: ≈2^59.6, d: 4091, c: 3.909, k: 32, postprocess: 10
`LightSaber <https://www.esat.kuleuven.be/cosic/pqcrypto/saber/files/SABER_KEM_Round_2.zip>`__ ::
sage: load("estimator.py")
sage: n = 512
sage: q = 8192
sage: alpha_0 = alphaf(sqrt(10/4.0), q, sigma_is_stddev=True) # error
sage: alpha_1 = alphaf(sqrt(21/4.0), q, sigma_is_stddev=True) # secret
sage: primal_usvp(n, alpha_0, q, secret_distribution=alpha_1, m=n, reduction_cost_model=BKZ.ADPS16) # not enough samples
Traceback (most recent call last):
...
NotImplementedError: secret size 0.000701 > error size 0.000484
sage: primal_usvp(n, alpha_1, q, secret_distribution=alpha_0, m=n, reduction_cost_model=BKZ.ADPS16)
rop: 2^118.0
red: 2^118.0
delta_0: 1.003955
beta: 404
d: 1022
m: 509

2
__init__.py Normal file
View File

@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
from estimator import * # noqa

Binary file not shown.

Binary file not shown.

31
bitbucket-pipelines.yml Normal file
View File

@@ -0,0 +1,31 @@
# This is a sample build configuration for Python.
# Check our guides at https://confluence.atlassian.com/x/x4UWN for more examples.
# Only use spaces to indent your .yml configuration.
# -----
# You can specify a custom docker image from Docker Hub as your build environment.
image: sagemath/sagemath
pipelines:
default:
- step:
name: PEP8
script:
- sudo apt-get update && sudo apt-get install -y python3-pip
- pip3 install flake8
- $HOME/.local/bin/flake8 estimator.py
- step:
name: Doctest
script:
- export SAGE_ROOT=`sage -c "import os; print(os.environ['SAGE_ROOT'])" | tail -1`
- export PATH="$SAGE_ROOT/build/bin:$SAGE_ROOT/local/bin:$PATH"
- export SAGE_PYTHON_VERSION=3
- export SAGE_LOCAL="$SAGE_ROOT/local"
- export DOT_SAGE=/home/sage/.sage/
- mkdir stupid_workaround # sage doesn't like world writable but we're not allowed to change that
- chmod 700 stupid_workaround
- cp estimator.py stupid_workaround/
- cp README.rst stupid_workaround/
- cd stupid_workaround
- PYTHONIOENCODING=UTF-8 PYTHONPATH=`pwd` sage-runtests estimator.py
- PYTHONIOENCODING=UTF-8 PYTHONPATH=`pwd` sage-runtests README.rst
- cd ..

315
bkw_legacy.py Normal file
View File

@@ -0,0 +1,315 @@
# -*- coding: utf-8 -*-
"""
BKW legacy code.
.. moduleauthor:: Martin R. Albrecht <martinralbrecht@googlemail.com>
"""
from collections import OrderedDict
from estimator import cost_reorder, stddevf, sigmaf
from estimator import preprocess_params, amplify_sigma, secret_distribution_variance
from sage.functions.log import log
from sage.functions.other import ceil, sqrt
from sage.matrix.all import Matrix
from sage.modules.all import vector
from sage.rings.all import RealField
from sage.rings.all import ZZ
from sage.rings.infinity import PlusInfinity
from sage.structure.element import parent
from sage.symbolic.all import pi
oo = PlusInfinity()
def bkw_decision(n, alpha, q, success_probability=0.99, prec=None):
"""
Estimate the cost of running BKW to solve Decision-LWE following [DCC:ACFFP15]_.
:param n: dimension > 0
:param alpha: fraction of the noise α < 1.0
:param q: modulus > 0
:param success_probability: probability of success < 1.0
:param prec: precision used for floating point computations
:param m: the number of available samples
.. [DCC:ACFFP15] Albrecht, M. R., Cid, C., Jean-Charles Faugère, Fitzpatrick, R., &
Perret, L. (2015). On the complexity of the BKW algorithm on LWE.
Designs, Codes & Cryptography, Volume 74, Issue 2, pp 325-354
"""
n, alpha, q, success_probability = preprocess_params(n, alpha, q, success_probability)
sigma = alpha*q
RR = parent(alpha)
def _run(t):
a = RR(t*log(n, 2)) # target number of adds: a = t*log_2(n)
b = RR(n/a) # window width
sigma_final = RR(n**t).sqrt() * sigma # after n^t adds we get this σ
m = amplify_sigma(success_probability, sigma_final, q)
tmp = a*(a-1)/2 * (n+1) - b*a*(a-1)/4 - b/6 * RR((a-1)**3 + 3/2*(a-1)**2 + (a-1)/2)
stage1a = RR(q**b-1)/2 * tmp
stage1b = m * (a/2 * (n + 2))
stage1 = stage1a + stage1b
nrops = RR(stage1)
nbops = RR(log(q, 2) * nrops)
ncalls = RR(a * ceil(RR(q**b)/RR(2)) + m)
nmem = ceil(RR(q**b)/2) * a * (n + 1 - b * (a-1)/2)
current = OrderedDict([(u"t", t),
(u"bop", nbops),
(u"oracle", ncalls),
(u"m", m),
(u"mem", nmem),
(u"rop", nrops),
(u"a", a),
(u"b", b),
])
current = cost_reorder(current, ("rop", u"oracle", u"t"))
return current
best_runtime = None
t = RR(2*(log(q, 2) - log(sigma, 2))/log(n, 2))
while True:
current = _run(t)
if not best_runtime:
best_runtime = current
else:
if best_runtime["rop"] > current["rop"]:
best_runtime = current
else:
break
t += 0.05
return best_runtime
def bkw_search(n, alpha, q, success_probability=0.99, prec=None):
"""
Estimate the cost of running BKW to solve Search-LWE following [C:DucTraVau15]_.
:param n: dimension > 0
:param alpha: fraction of the noise α < 1.0
:param q: modulus > 0
:param success_probability: probability of success < 1.0
:param prec: precision used for floating point computations
.. [EC:DucTraVau15] Duc, A., Florian Tramèr, & Vaudenay, S. (2015). Better algorithms for
LWE and LWR.
"""
n, alpha, q, success_probability = preprocess_params(n, alpha, q, success_probability)
sigma = stddevf(alpha*q)
eps = success_probability
RR = parent(alpha)
# "To simplify our result, we considered operations over C to have the same
# complexity as operations over Z_q . We also took C_FFT = 1 which is the
# best one can hope to obtain for a FFT."
c_cost = 1
c_mem = 1
c_fft = 1
def _run(t):
a = RR(t*log(n, 2)) # target number of adds: a = t*log_2(n)
b = RR(n/a) # window width
epp = (1- eps)/a
m = lambda j, eps: 8 * b * log(q/eps) * (1 - (2 * pi**2 * sigma**2)/(q**2))**(-2**(a-j)) # noqa
c1 = (q**b-1)/2 * ((a-1)*(a-2)/2 * (n+1) - b/6 * (a*(a-1) * (a-2)))
c2 = sum([m(j, epp) * (a-1-j)/2 * (n+2) for j in range(a)])
c3 = (2*sum([m(j, epp) for j in range(a)]) + c_fft * n * q**b * log(q, 2)) * c_cost
c4 = (a-1)*(a-2) * b * (q**b - 1)/2
nrops = RR(c1 + c2 + c3 + c4)
nbops = RR(log(q, 2) * nrops)
ncalls = (a-1) * (q**b - 1)/2 + m(0, eps)
nmem = ((q**b - 1)/2 * (a-1) * (n + 1 - b*(a-2)/2)) + m(0, eps) + c_mem * q**b
current = OrderedDict([(u"t", t),
(u"bop", nbops),
(u"oracle", ncalls),
(u"m", m(0, eps)),
(u"mem", nmem),
(u"rop", nrops),
(u"a", a),
(u"b", b),
])
current = cost_reorder(current, ("rop", u"oracle", u"t"))
return current
best_runtime = None
best = None
t = RR(2*(log(q, 2) - log(sigma, 2))/log(n, 2))
while True:
current = _run(t)
if not best_runtime:
best_runtime = current
else:
if best_runtime["rop"] > current["rop"]:
best_runtime = current
else:
break
t += 0.05
return best
def bkw_small_secret_variances(q, a, b, kappa, o, RR=None):
"""
Helper function for small secret BKW variant.
:param q:
:param a:
:param b:
:param kappa:
:param o:
:param RR:
:returns:
:rtype:
"""
if RR is None:
RR = RealField()
q = RR(q)
a = RR(a).round()
b = RR(b)
n = a*b
kappa = RR(kappa)
T = RR(2)**(b*kappa)
n = RR(o)/RR(T*(a+1)) + RR(1)
U_Var = lambda x: (x**2 - 1)/12 # noqa
red_var = 2*U_Var(q/(2**kappa))
if o:
c_ = map(RR, [0.0000000000000000,
0.4057993538687922, 0.6924478992819291, 0.7898852691349439,
0.8441959360364506, 0.8549679124679972, 0.8954469872316165,
0.9157093365103325, 0.9567635780119543, 0.9434245442818547,
0.9987153221343770])
M = Matrix(RR, a, a) # rows are tables, columns are entries those tables
for l in range(M.ncols()):
for c in range(l, M.ncols()):
M[l, c] = U_Var(q)
for l in range(1, a):
for i in range(l):
M[l, i] = red_var + sum(M[i+1:l].column(i))
bl = b*l
if round(bl) < len(c_):
c_tau = c_[round(bl)]
else:
c_tau = RR(1)/RR(5)*RR(sqrt(bl)) + RR(1)/RR(3)
f = (c_tau*n**(~bl) + 1 - c_tau)**2
for i in range(l):
M[l, i] = M[l, i]/f
v = vector(RR, a)
for i in range(a):
v[i] = red_var + sum(M[i+1:].column(i))
else:
v = vector(RR, a)
for i in range(a)[::-1]:
v[i] = 2**(a-i-1) * red_var
return v
def bkw_small_secret(n, alpha, q, secret_distribution=True, success_probability=0.99, t=None, o=0, samples=None): # noqa
"""
:param n: number of variables in the LWE instance
:param alpha: standard deviation of the LWE instance
:param q: size of the finite field (default: n^2)
"""
def sigma2f(kappa):
v = bkw_small_secret_variances(q, a, b, kappa, o, RR=RR)
return sigmaf(sum([b * e * secret_variance for e in v], RR(0)).sqrt())
def Tf(kappa):
return min(q**b, ZZ(2)**(b*kappa))/2
def ops_tf(kappa):
T = Tf(kappa)
return T * (a*(a-1)/2 * (n+1) - b*a*(a-1)/4 - b/6 * ((a-1)**3 + 3/2*(a-1)**2 + 1/RR(2)*(a-1)))
def bkwssf(kappa):
ret = OrderedDict()
ret[u"κ"] = kappa
m = amplify_sigma(success_probability, [sigma_final, sigma2f(kappa)], q)
ret["m"] = m
ropsm = (m + o) * (a/2 * (n + 2))
ropst = ops_tf(kappa)
ret["rop"] = ropst + ropsm
T = Tf(kappa)
ret["mem"] = T * a * (n + 1 - b * (a-1)/2)
ret["oracle"] = T * a + ret["m"] + o
return ret
n, alpha, q, success_probability = preprocess_params(n, alpha, q, success_probability, prec=4*n)
RR = alpha.parent()
sigma = alpha*q
if o is None:
best = bkw_small_secret(n, alpha, q, secret_distribution, success_probability, t=t, o=0)
o = best["oracle"]/2
while True:
current = bkw_small_secret(n, alpha, q, secret_distribution, success_probability, t=t, o=o)
if best is None or current["rop"] < best["rop"]:
best = current
if current["rop"] > best["rop"]:
break
o = o/2
return best
if t is None:
t = RR(2*(log(q, 2) - log(sigma, 2))/log(n, 2))
best = None
while True:
current = bkw_small_secret(n, alpha, q, secret_distribution, success_probability, t=t, o=o)
if best is None or current["rop"] < best["rop"]:
best = current
if current["rop"] > best["rop"]:
break
t += 0.01
return best
secret_variance = secret_distribution_variance(secret_distribution)
secret_variance = RR(secret_variance)
a = RR(t*log(n, 2)) # the target number of additions: a = t*log_2(n)
b = n/a # window width b = n/a
sigma_final = RR(n**t).sqrt() * sigma # after n^t additions we get this stddev
transformation_noise = sqrt(n * 1/RR(12) * secret_variance)
kappa = ceil(log(round(q*transformation_noise/stddevf(sigma)), 2.0)) + 1
if kappa > ceil(log(q, 2)):
kappa = ceil(log(q, 2))
best = None
while kappa > 0:
current = bkwssf(kappa)
if best is None or current["rop"] < best["rop"]:
best = current
if current["rop"] > best["rop"]:
break
kappa -= 1
best["o"] = o
best["t"] = t
best["a"] = a
best["b"] = b
best = cost_reorder(best, ["rop", "oracle", "t", "m", "mem"])
return best

225
doc/Makefile Normal file
View File

@@ -0,0 +1,225 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " epub3 to make an epub3"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/LWEEstimator.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/LWEEstimator.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/LWEEstimator"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/LWEEstimator"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: epub3
epub3:
$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
@echo
@echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
.PHONY: dummy
dummy:
$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
@echo
@echo "Build finished. Dummy builder generates no files."

6
doc/_templates/autosummary/base.rst vendored Normal file
View File

@@ -0,0 +1,6 @@
{{ fullname }}
{{ underline }}
.. currentmodule:: {{ module }}
.. auto{{ objtype }}:: {{ objname }}

35
doc/_templates/autosummary/class.rst vendored Normal file
View File

@@ -0,0 +1,35 @@
{{ fullname }}
{{ underline }}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
{% block methods %}
.. automethod:: __init__
{% if methods %}
.. rubric:: Methods
.. autosummary::
:toctree: {{ fullname }}
{% for item in methods %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}
{% block attributes %}
{% if attributes %}
.. rubric:: Attributes
.. autosummary::
:toctree: {{ fullname }}
{% for item in attributes %}
~{{ name }}.{{ item }}
{%- endfor %}
{% endif %}
{% endblock %}

32
doc/_templates/autosummary/module.rst vendored Normal file
View File

@@ -0,0 +1,32 @@
{{ fullname }}
{{ underline }}
.. rubric:: Description
.. automodule:: {{ fullname }}
.. currentmodule:: {{ fullname }}
{% if classes %}
.. rubric:: Classes
.. autosummary::
:toctree: {{ fullname }}
{% for class in classes %}
{% if class in members %}
{{ class }}
{% endif %}
{% endfor %}
{% endif %}
{% if functions %}
.. rubric:: Functions
.. autosummary::
:toctree: {{ fullname }}
{% for function in functions %}
{{ function }}
{% endfor %}
{% endif %}

9
doc/api_doc.rst Normal file
View File

@@ -0,0 +1,9 @@
API Reference
=============
.. rubric:: Modules
.. autosummary::
:toctree: _apidoc
estimator

394
doc/conf.py Normal file
View File

@@ -0,0 +1,394 @@
# -*- coding: utf-8 -*-
#
# LWE Estimator documentation build configuration file, created by
# sphinx-quickstart on Sat May 19 18:04:37 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
try:
from unittest.mock import MagicMock
except ImportError:
from mock import Mock as MagicMock
sys.path.insert(0, os.path.abspath('../'))
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
MOCK_MODULES = [
'sage',
'sage.all',
'sage.arith',
'sage.arith.srange',
'sage.calculus',
'sage.calculus.var',
'sage.functions',
'sage.functions.log',
'sage.functions',
'sage.functions.other',
'sage.interfaces',
'sage.interfaces.magma',
'sage.misc',
'sage.misc.all',
'sage.numerical',
'sage.numerical.optimize',
'sage.rings',
'sage.rings.all',
'sage.rings',
'sage.rings.infinity',
'sage.structure',
'sage.structure.element',
'sage.symbolic',
'sage.symbolic.all',
'scipy',
'scipy.optimize',
'sage.crypto',
'sage.crypto.lwe',
]
sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES)
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
autoclass_content = "both"
#autodoc_default_flags = [
# "members",
# "inherited-members",
# "private-members",
# "show-inheritance"
#]
autosummary_generate = True
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.doctest',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
'sphinx.ext.mathjax',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'LWE Estimator'
copyright = u'2018, Martin R Albrecht'
author = u'Martin R Albrecht'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0'
# The full version, including alpha/beta/rc tags.
release = u'1.0'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
# html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'LWE Estimator v1.0'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'LWEEstimatordoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'LWEEstimator.tex', u'LWE Estimator Documentation',
u'Martin R Albrecht', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'lweestimator', u'LWE Estimator Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'LWEEstimator', u'LWE Estimator Documentation',
author, 'LWEEstimator', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False
# Example configuration for intersphinx: refer to the Python standard library.

View File

@@ -0,0 +1,18 @@
Documentation README
======================
Documentation for the ``estimator`` is available `online <https://lwe-estimator.readthedocs.io/>`__.
This documentation can be generated locally by running the following code in the lwe-estimator directory:
::
pipenv run make html
If documentation was previously generated locally, to ensure a full regeneration use:
::
pipenv run make clean && rm -fr doc/_apidoc

4
doc/genindex.rst Normal file
View File

@@ -0,0 +1,4 @@
.. This file is a placeholder and will be replaced
Index
#####

26
doc/index.rst Normal file
View File

@@ -0,0 +1,26 @@
.. LWE Estimator documentation master file, created by
sphinx-quickstart on Sat May 19 18:04:37 2018.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to LWE Estimator's documentation!
=========================================
.. toctree::
:caption: Introduction
:maxdepth: 2
readme_link
documentationreadme
.. toctree::
:caption: API Reference
:glob:
_apidoc/*
.. toctree::
:caption: Appendix
genindex

7
doc/readme_link.rst Normal file
View File

@@ -0,0 +1,7 @@
Module Overview
===============
.. Ignore the title from the README when importing
as we have written our own one above
.. include:: ../README.rst
:start-line: 3

12
doctest.sh Executable file
View File

@@ -0,0 +1,12 @@
#!/usr/bin/env bash
###############################################################################
# Run Sage doctests
###############################################################################
SAGE_ROOT=$(sage -c "import os; print(os.environ['SAGE_ROOT'])")
export SAGE_ROOT="$SAGE_ROOT"
# shellcheck source=/dev/null
source "$SAGE_ROOT/local/bin/sage-env"
for file in "$@"; do
PYTHONIOENCODING=UTF-8 PYTHONPATH=$(pwd) sage-runtests "$file"
done

3467
estimator.py Normal file

File diff suppressed because it is too large Load Diff

13
fix-doctest.sh Executable file
View File

@@ -0,0 +1,13 @@
#!/usr/bin/env bash
###############################################################################
# Fix-up Doctests
#
# Please don't just blindly call this to make failures go away,
# but review all changes.
###############################################################################
SAGE_ROOT=$(sage -c "import os; print(os.environ['SAGE_ROOT'])")
export SAGE_ROOT="$SAGE_ROOT"
# shellcheck source=/dev/null
source "$SAGE_ROOT/local/bin/sage-env"
PYTHONIOENCODING=UTF-8 PYTHONPATH=$(pwd) sage-fixdoctests "$@"

2
pyproject.toml Normal file
View File

@@ -0,0 +1,2 @@
[tool.black]
line-length = 120

1
readthedocs.yml Normal file
View File

@@ -0,0 +1 @@
DOCKER_IMAGE: sagemath/sagemath

2
requirements.txt Normal file
View File

@@ -0,0 +1,2 @@
flake8
sphinx==1.4.4