forked from Election-Tech-Initiative/electionguard-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiscrete_log.py
More file actions
194 lines (145 loc) · 6.13 KB
/
discrete_log.py
File metadata and controls
194 lines (145 loc) · 6.13 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
# pylint: disable=global-statement
# support for computing discrete logs, with a cache so they're never recomputed
import asyncio
from typing import Dict, Tuple
from .constants import get_generator
from .singleton import Singleton
from .group import BaseElement, ElementModP, ONE_MOD_P, mult_p
DiscreteLogCache = Dict[ElementModP, int]
_DLOG_MAX_EXPONENT = 100_000_000
"""The max exponent to calculate. This value is used to stop a race condition."""
_INITIAL_CACHE = {ONE_MOD_P: 0}
class DiscreteLogExponentError(ValueError):
"""Raised when the max exponent is larger than the system allows."""
def __init__(self, exponent: int, max_exponent: int = _DLOG_MAX_EXPONENT) -> None:
super().__init__(
f"Discrete log exponent of {exponent} exceeds maximum of {max_exponent}."
)
class DiscreteLogNotFoundError(ValueError):
"""Raised when the discrete value could not be found in cache."""
def __init__(self, element: BaseElement) -> None:
super().__init__(f"Discrete log of {element} could not be found in cache.")
def compute_discrete_log(
element: ElementModP,
cache: DiscreteLogCache,
max_exponent: int = _DLOG_MAX_EXPONENT,
lazy_evaluation: bool = True,
) -> Tuple[int, DiscreteLogCache]:
"""
Computes the discrete log (base g, mod p) of the given element,
with internal caching of results. Should run efficiently when called
multiple times when the exponent is at most in the single-digit millions.
Performance will degrade if it's much larger.
For the best possible performance,
pre-compute the discrete log of a number you expect to have the biggest
exponent you'll ever see. After that, the cache will be fully loaded,
and every call will be nothing more than a dictionary lookup.
"""
if element in cache:
return (cache[element], cache)
if not lazy_evaluation:
raise DiscreteLogNotFoundError(element)
_cache = compute_discrete_log_cache(element, cache, max_exponent)
return (_cache[element], _cache)
async def compute_discrete_log_async(
element: ElementModP,
cache: DiscreteLogCache,
mutex: asyncio.Lock = asyncio.Lock(),
max_exponent: int = _DLOG_MAX_EXPONENT,
lazy_evaluation: bool = True,
) -> Tuple[int, DiscreteLogCache]:
"""
Computes the discrete log (base g, mod p) of the given element,
with internal caching of results. Should run efficiently when called
multiple times when the exponent is at most in the single-digit millions.
Performance will degrade if it's much larger.
Note: *this function is thread-safe*. For the best possible performance,
pre-compute the discrete log of a number you expect to have the biggest
exponent you'll ever see. After that, the cache will be fully loaded,
and every call will be nothing more than a dictionary lookup.
"""
if element in cache:
return (cache[element], cache)
async with mutex:
if element in cache:
return (cache[element], cache)
if not lazy_evaluation:
raise DiscreteLogNotFoundError(element)
_cache = compute_discrete_log_cache(element, cache, max_exponent)
return (_cache[element], _cache)
def precompute_discrete_log_cache(
max_exponent: int, cache: DiscreteLogCache = None
) -> DiscreteLogCache:
"""
Precompute the discrete log by the max exponent.
"""
if max_exponent > _DLOG_MAX_EXPONENT:
raise DiscreteLogExponentError(max_exponent)
if not cache:
cache = _INITIAL_CACHE
current_element = list(cache)[-1]
prev_exponent = cache[current_element]
if prev_exponent >= max_exponent:
return cache
g = ElementModP(get_generator(), False)
for exponent in range(prev_exponent + 1, max_exponent + 1):
current_element = mult_p(g, current_element)
cache[current_element] = exponent
return cache
def compute_discrete_log_cache(
element: ElementModP,
cache: DiscreteLogCache,
max_exponent: int = _DLOG_MAX_EXPONENT,
) -> DiscreteLogCache:
"""
Compute or lazy evaluation a discrete log cache up to the specified element.
"""
if max_exponent > _DLOG_MAX_EXPONENT:
raise DiscreteLogExponentError(max_exponent)
if not cache:
cache = _INITIAL_CACHE
max_element = list(cache)[-1]
exponent = cache[max_element]
if exponent > max_exponent:
raise DiscreteLogExponentError(exponent, max_exponent)
g = ElementModP(get_generator(), False)
while element != max_element:
exponent = exponent + 1
if exponent > max_exponent:
raise DiscreteLogExponentError(exponent, max_exponent)
max_element = mult_p(g, max_element)
cache[max_element] = exponent
return cache
class DiscreteLog(Singleton):
"""
A class instance of the discrete log that includes a cache.
"""
_cache: DiscreteLogCache = {ONE_MOD_P: 0}
_mutex = asyncio.Lock()
_max_exponent: int = _DLOG_MAX_EXPONENT
_lazy_evaluation: bool = True
def get_cache(self) -> DiscreteLogCache:
return self._cache
def set_max_exponent(self, max_exponent: int) -> None:
self._max_exponent = max_exponent
def set_lazy_evaluation(self, lazy_evaluation: bool) -> None:
self._lazy_evaluation = lazy_evaluation
def precompute_cache(self, exponent: int) -> None:
if exponent > self._max_exponent:
exponent = self._max_exponent
precompute_discrete_log_cache(exponent, self._cache)
async def precompute_cache_async(self, exponent: int) -> None:
if exponent > self._max_exponent:
exponent = self._max_exponent
async with self._mutex:
precompute_discrete_log_cache(exponent)
def discrete_log(self, element: ElementModP) -> int:
(result, _cache) = compute_discrete_log(
element, self._cache, self._max_exponent, self._lazy_evaluation
)
return result
async def discrete_log_async(self, element: ElementModP) -> int:
(result, _cache) = await compute_discrete_log_async(
element, self._cache, self._mutex, self._max_exponent, self._lazy_evaluation
)
return result