blob: 51b25a37154d8f84ebcf66c9a79efedd20c891c6 [file] [log] [blame]
Werner Lewis99e81782022-09-30 16:28:43 +01001"""Common features for bignum in test generation framework."""
2# Copyright The Mbed TLS Contributors
3# SPDX-License-Identifier: Apache-2.0
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
Werner Lewis99e81782022-09-30 16:28:43 +010017from abc import abstractmethod
Gilles Peskine7a708fd2022-12-20 19:19:18 +010018import enum
Janos Follath98edf212022-11-19 12:48:17 +000019from typing import Iterator, List, Tuple, TypeVar, Any
Minos Galanakis0a325b62023-04-06 16:33:10 +010020from copy import deepcopy
Janos Follath98edf212022-11-19 12:48:17 +000021from itertools import chain
Werner Lewis99e81782022-09-30 16:28:43 +010022
Janos Follath87df3732022-11-09 12:31:23 +000023from . import test_case
Janos Follath0cd89672022-11-09 12:14:14 +000024from . import test_data_generation
Janos Follathdac44e62022-11-20 11:58:12 +000025from .bignum_data import INPUTS_DEFAULT, MODULI_DEFAULT
Janos Follath0cd89672022-11-09 12:14:14 +000026
Werner Lewis99e81782022-09-30 16:28:43 +010027T = TypeVar('T') #pylint: disable=invalid-name
28
Werner Lewisa8503122022-10-04 10:10:40 +010029def invmod(a: int, n: int) -> int:
30 """Return inverse of a to modulo n.
31
32 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
33 to long_invmod() in CPython.
34 """
35 b, c = 1, 0
36 while n:
37 q, r = divmod(a, n)
38 a, b, c, n = n, c, b - q*c, r
39 # at this point a is the gcd of the original inputs
40 if a == 1:
41 return b
42 raise ValueError("Not invertible")
43
Tom Cosgrove1133d232022-12-16 03:53:17 +000044def invmod_positive(a: int, n: int) -> int:
45 """Return a non-negative inverse of a to modulo n."""
46 inv = invmod(a, n)
47 return inv if inv >= 0 else inv + n
48
Werner Lewis99e81782022-09-30 16:28:43 +010049def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010050 """Implement the syntax accepted by mbedtls_test_read_mpi().
51
52 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
53 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010054 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010055 return 0
56 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010057
Gilles Peskinef8a44632022-12-20 19:12:22 +010058def quote_str(val: str) -> str:
Werner Lewis99e81782022-09-30 16:28:43 +010059 return "\"{}\"".format(val)
60
Werner Lewisf86c82e2022-10-19 13:50:10 +010061def bound_mpi(val: int, bits_in_limb: int) -> int:
62 """First number exceeding number of limbs needed for given input value."""
63 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010064
Werner Lewisf86c82e2022-10-19 13:50:10 +010065def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
66 """First number exceeding maximum of given number of limbs."""
67 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010068 return 1 << bits
69
Werner Lewisf86c82e2022-10-19 13:50:10 +010070def limbs_mpi(val: int, bits_in_limb: int) -> int:
71 """Return the number of limbs required to store value."""
Gabor Mezei5ded38e2023-03-31 16:03:14 +020072 bit_length = max(val.bit_length(), 1)
73 return (bit_length + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010074
75def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010076 """Return all pair combinations from input values."""
77 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010078
Gabor Mezei7c8d7062023-02-14 18:25:23 +010079def hex_digits_for_limb(limbs: int, bits_in_limb: int) -> int:
80 """ Retrun the hex digits need for a number of limbs. """
81 return 2 * (limbs * bits_in_limb // 8)
82
Minos Galanakisc787cf72023-04-25 12:13:25 +010083def hex_digits_max_int(val: str, bits_in_limb: int) -> int:
84 """ Return the first number exceeding maximum the limb space
85 required to store the input hex-string value. This method
86 weights on the input str_len rather than numerical value
87 and works with zero-padded inputs"""
88 n = ((1 << (len(val) * 4)) - 1)
89 l = limbs_mpi(n, bits_in_limb)
90 return bound_mpi_limbs(l, bits_in_limb)
91
92def zfill_match(reference: str, target: str) -> str:
Minos Galanakis013167e2023-05-11 10:54:44 +010093 """ Zero pad target hex-string to match the limb size of
94 the reference input """
Minos Galanakisc787cf72023-04-25 12:13:25 +010095 lt = len(target)
96 lr = len(reference)
Minos Galanakis013167e2023-05-11 10:54:44 +010097 target_len = lr if lt < lr else lt
98 return "{:x}".format(int(target, 16)).zfill(target_len)
Minos Galanakisc787cf72023-04-25 12:13:25 +010099
Janos Follath0cd89672022-11-09 12:14:14 +0000100class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +0100101 """Common features for bignum binary operations.
102
103 This adds functionality common in binary operation tests.
104
105 Attributes:
106 symbol: Symbol to use for the operation in case description.
107 input_values: List of values to use as test case inputs. These are
108 combined to produce pairs of values.
109 input_cases: List of tuples containing pairs of test case inputs. This
110 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +0100111 unique_combinations_only: Boolean to select if test case combinations
112 must be unique. If True, only A,B or B,A would be included as a test
113 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +0000114 input_style: Controls the way how test data is passed to the functions
115 in the generated test cases. "variable" passes them as they are
116 defined in the python source. "arch_split" pads the values with
117 zeroes depending on the architecture/limb size. If this is set,
118 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +0000119 arity: the number of operands for the operation. Currently supported
120 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +0100121 """
122 symbol = ""
Janos Follathdac44e62022-11-20 11:58:12 +0000123 input_values = INPUTS_DEFAULT # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +0000124 input_cases = [] # type: List[Any]
Minos Galanakis0a325b62023-04-06 16:33:10 +0100125 dependencies = [] # type: List[Any]
Janos Follathf4579762022-11-20 13:32:54 +0000126 unique_combinations_only = False
Janos Follatha36e4302022-11-19 15:55:53 +0000127 input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
Janos Follath6fa3f062022-11-17 20:33:51 +0000128 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +0000129 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +0000130 arities = [1, 2]
131 arity = 2
Tom Cosgrove61292682022-12-08 09:44:10 +0000132 suffix = False # for arity = 1, symbol can be prefix (default) or suffix
Werner Lewis99e81782022-09-30 16:28:43 +0100133
Janos Follatha36e4302022-11-19 15:55:53 +0000134 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000135 self.val_a = val_a
136 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000137 # Setting the int versions here as opposed to making them @properties
138 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100139 self.int_a = hex_to_int(val_a)
140 self.int_b = hex_to_int(val_b)
Minos Galanakis0a325b62023-04-06 16:33:10 +0100141 self.dependencies = deepcopy(self.dependencies)
Janos Follath155ad8c2022-11-17 14:42:40 +0000142 if bits_in_limb not in self.limb_sizes:
143 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000144 if self.input_style == "arch_split":
Minos Galanakis0a325b62023-04-06 16:33:10 +0100145 self.dependencies.append("MBEDTLS_HAVE_INT{:d}".format(bits_in_limb))
Janos Follath155ad8c2022-11-17 14:42:40 +0000146 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100147
Janos Follathb41ab922022-11-17 15:13:02 +0000148 @property
149 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000150 if self.arity == 1:
151 return self.int_a
152 elif self.arity == 2:
153 return max(self.int_a, self.int_b)
154 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000155
156 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000157 def limb_boundary(self) -> int:
158 return bound_mpi(self.boundary, self.bits_in_limb)
159
160 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000161 def limbs(self) -> int:
162 return limbs_mpi(self.boundary, self.bits_in_limb)
163
164 @property
165 def hex_digits(self) -> int:
Gabor Mezei7c8d7062023-02-14 18:25:23 +0100166 return hex_digits_for_limb(self.limbs, self.bits_in_limb)
Janos Follathb41ab922022-11-17 15:13:02 +0000167
Gilles Peskinef8a44632022-12-20 19:12:22 +0100168 def format_arg(self, val: str) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000169 if self.input_style not in self.input_styles:
170 raise ValueError("Unknown input style!")
171 if self.input_style == "variable":
172 return val
173 else:
174 return val.zfill(self.hex_digits)
175
Gilles Peskinef8a44632022-12-20 19:12:22 +0100176 def format_result(self, res: int) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000177 res_str = '{:x}'.format(res)
178 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000179
180 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000181 def arg_a(self) -> str:
182 return self.format_arg(self.val_a)
183
184 @property
185 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000186 if self.arity == 1:
187 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000188 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000189
Werner Lewis99e81782022-09-30 16:28:43 +0100190 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000191 args = [quote_str(self.arg_a)]
192 if self.arity == 2:
193 args.append(quote_str(self.arg_b))
194 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100195
Janos Follath3aeb60a2022-11-09 13:24:46 +0000196 def description(self) -> str:
197 """Generate a description for the test case.
198
199 If not set, case_description uses the form A `symbol` B, where symbol
200 is used to represent the operation. Descriptions of each value are
201 generated to provide some context to the test case.
202 """
203 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000204 if self.arity == 1:
Tom Cosgrove61292682022-12-08 09:44:10 +0000205 format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}"
206 self.case_description = format_string.format(
Janos Follath8ae7a652022-11-19 15:05:19 +0000207 self.symbol, self.int_a
208 )
209 elif self.arity == 2:
210 self.case_description = "{:x} {} {:x}".format(
211 self.int_a, self.symbol, self.int_b
212 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000213 return super().description()
214
Janos Follath939621f2022-11-18 18:15:24 +0000215 @property
216 def is_valid(self) -> bool:
217 return True
218
Werner Lewis99e81782022-09-30 16:28:43 +0100219 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100220 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100221 """Get the result of the operation.
222
223 This could be calculated during initialization and stored as `_result`
224 and then returned, or calculated when the method is called.
225 """
226 raise NotImplementedError
227
228 @classmethod
229 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
230 """Generator to yield pairs of inputs.
231
232 Combinations are first generated from all input values, and then
233 specific cases provided.
234 """
Janos Follath284672c2022-11-19 14:55:43 +0000235 if cls.arity == 1:
236 yield from ((a, "0") for a in cls.input_values)
237 elif cls.arity == 2:
238 if cls.unique_combinations_only:
239 yield from combination_pairs(cls.input_values)
240 else:
241 yield from (
242 (a, b)
243 for a in cls.input_values
244 for b in cls.input_values
245 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100246 else:
Janos Follath284672c2022-11-19 14:55:43 +0000247 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000248
Janos Follath87df3732022-11-09 12:31:23 +0000249 @classmethod
250 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000251 if cls.input_style not in cls.input_styles:
252 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000253 if cls.arity not in cls.arities:
254 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000255 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000256 test_objects = (cls(a, b, bits_in_limb=bil)
257 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000258 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000259 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
260 for args in cls.input_cases
261 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000262 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000263 test_objects = (cls(a, b)
264 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000265 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000266 yield from (valid_test_object.create_test_case()
267 for valid_test_object in filter(
268 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000269 chain(test_objects, special_cases)
270 )
271 )
272
Janos Follath87df3732022-11-09 12:31:23 +0000273
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100274class ModulusRepresentation(enum.Enum):
275 """Representation selector of a modulus."""
276 # Numerical values aligned with the type mbedtls_mpi_mod_rep_selector
277 INVALID = 0
278 MONTGOMERY = 2
279 OPT_RED = 3
280
281 def symbol(self) -> str:
282 """The C symbol for this representation selector."""
283 return 'MBEDTLS_MPI_MOD_REP_' + self.name
284
285 @classmethod
286 def supported_representations(cls) -> List['ModulusRepresentation']:
287 """Return all representations that are supported in positive test cases."""
288 return [cls.MONTGOMERY, cls.OPT_RED]
289
290
Janos Follath5b1dbb42022-11-17 13:32:43 +0000291class ModOperationCommon(OperationCommon):
292 #pylint: disable=abstract-method
293 """Target for bignum mod_raw test case generation."""
Janos Follathdac44e62022-11-20 11:58:12 +0000294 moduli = MODULI_DEFAULT # type: List[str]
Tom Cosgrovef7237542022-12-16 16:10:36 +0000295 montgomery_form_a = False
Tom Cosgrove1133d232022-12-16 03:53:17 +0000296 disallow_zero_a = False
Janos Follath5b1dbb42022-11-17 13:32:43 +0000297
Janos Follath155ad8c2022-11-17 14:42:40 +0000298 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
299 bits_in_limb: int = 64) -> None:
300 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000301 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000302 # Setting the int versions here as opposed to making them @properties
303 # provides earlier/more robust input validation.
304 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000305
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000306 def to_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000307 return (val * self.r) % self.int_n
308
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000309 def from_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000310 return (val * self.r_inv) % self.int_n
311
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100312 def convert_from_canonical(self, canonical: int,
313 rep: ModulusRepresentation) -> int:
314 """Convert values from canonical representation to the given representation."""
315 if rep is ModulusRepresentation.MONTGOMERY:
316 return self.to_montgomery(canonical)
317 elif rep is ModulusRepresentation.OPT_RED:
318 return canonical
319 else:
320 raise ValueError('Modulus representation not supported: {}'
321 .format(rep.name))
322
Janos Follath5b1dbb42022-11-17 13:32:43 +0000323 @property
324 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000325 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000326
327 @property
Tom Cosgrove1133d232022-12-16 03:53:17 +0000328 def arg_a(self) -> str:
Tom Cosgrovef7237542022-12-16 16:10:36 +0000329 if self.montgomery_form_a:
Tom Cosgrove1133d232022-12-16 03:53:17 +0000330 value_a = self.to_montgomery(self.int_a)
331 else:
332 value_a = self.int_a
333 return self.format_arg('{:x}'.format(value_a))
334
335 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000336 def arg_n(self) -> str:
337 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000338
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100339 def format_arg(self, val: str) -> str:
Minos Galanakis3d2aab82022-12-21 17:30:10 +0000340 return super().format_arg(val).zfill(self.hex_digits)
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100341
Janos Follatha36a3d32022-11-18 17:49:13 +0000342 def arguments(self) -> List[str]:
343 return [quote_str(self.arg_n)] + super().arguments()
344
Janos Follath5b1dbb42022-11-17 13:32:43 +0000345 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000346 def r(self) -> int: # pylint: disable=invalid-name
347 l = limbs_mpi(self.int_n, self.bits_in_limb)
348 return bound_mpi_limbs(l, self.bits_in_limb)
349
350 @property
351 def r_inv(self) -> int:
352 return invmod(self.r, self.int_n)
353
354 @property
355 def r2(self) -> int: # pylint: disable=invalid-name
356 return pow(self.r, 2)
357
Janos Follathc4fca5d2022-11-19 10:42:20 +0000358 @property
359 def is_valid(self) -> bool:
360 if self.int_a >= self.int_n:
361 return False
Tom Cosgrove1133d232022-12-16 03:53:17 +0000362 if self.disallow_zero_a and self.int_a == 0:
363 return False
Janos Follathc4fca5d2022-11-19 10:42:20 +0000364 if self.arity == 2 and self.int_b >= self.int_n:
365 return False
366 return True
367
Janos Follath8ae7a652022-11-19 15:05:19 +0000368 def description(self) -> str:
369 """Generate a description for the test case.
370
371 It uses the form A `symbol` B mod N, where symbol is used to represent
372 the operation.
373 """
374
375 if not self.case_description:
376 return super().description() + " mod {:x}".format(self.int_n)
377 return super().description()
378
Janos Follathc4fca5d2022-11-19 10:42:20 +0000379 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000380 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
381 if cls.arity == 1:
382 yield from ((n, a, "0") for a, n in cls.input_cases)
383 elif cls.arity == 2:
384 yield from ((n, a, b) for a, b, n in cls.input_cases)
385 else:
386 raise ValueError("Unsupported number of operands!")
387
388 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000389 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
390 if cls.input_style not in cls.input_styles:
391 raise ValueError("Unknown input style!")
392 if cls.arity not in cls.arities:
393 raise ValueError("Unsupported number of operands!")
394 if cls.input_style == "arch_split":
395 test_objects = (cls(n, a, b, bits_in_limb=bil)
396 for n in cls.moduli
397 for a, b in cls.get_value_pairs()
398 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000399 special_cases = (cls(*args, bits_in_limb=bil)
400 for args in cls.input_cases_args()
401 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000402 else:
403 test_objects = (cls(n, a, b)
404 for n in cls.moduli
405 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000406 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000407 yield from (valid_test_object.create_test_case()
408 for valid_test_object in filter(
409 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000410 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000411 ))