blob: 24221755415f3f467870e4a815bcf4631f3dbbc9 [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
20from itertools import chain
Werner Lewis99e81782022-09-30 16:28:43 +010021
Janos Follath87df3732022-11-09 12:31:23 +000022from . import test_case
Janos Follath0cd89672022-11-09 12:14:14 +000023from . import test_data_generation
Janos Follathdac44e62022-11-20 11:58:12 +000024from .bignum_data import INPUTS_DEFAULT, MODULI_DEFAULT
Janos Follath0cd89672022-11-09 12:14:14 +000025
Werner Lewis99e81782022-09-30 16:28:43 +010026T = TypeVar('T') #pylint: disable=invalid-name
27
Werner Lewisa8503122022-10-04 10:10:40 +010028def invmod(a: int, n: int) -> int:
29 """Return inverse of a to modulo n.
30
31 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
32 to long_invmod() in CPython.
33 """
34 b, c = 1, 0
35 while n:
36 q, r = divmod(a, n)
37 a, b, c, n = n, c, b - q*c, r
38 # at this point a is the gcd of the original inputs
39 if a == 1:
40 return b
41 raise ValueError("Not invertible")
42
Tom Cosgrove1133d232022-12-16 03:53:17 +000043def invmod_positive(a: int, n: int) -> int:
44 """Return a non-negative inverse of a to modulo n."""
45 inv = invmod(a, n)
46 return inv if inv >= 0 else inv + n
47
Werner Lewis99e81782022-09-30 16:28:43 +010048def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010049 """Implement the syntax accepted by mbedtls_test_read_mpi().
50
51 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
52 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010053 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010054 return 0
55 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010056
Gilles Peskinef8a44632022-12-20 19:12:22 +010057def quote_str(val: str) -> str:
Werner Lewis99e81782022-09-30 16:28:43 +010058 return "\"{}\"".format(val)
59
Werner Lewisf86c82e2022-10-19 13:50:10 +010060def bound_mpi(val: int, bits_in_limb: int) -> int:
61 """First number exceeding number of limbs needed for given input value."""
62 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010063
Werner Lewisf86c82e2022-10-19 13:50:10 +010064def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
65 """First number exceeding maximum of given number of limbs."""
66 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010067 return 1 << bits
68
Werner Lewisf86c82e2022-10-19 13:50:10 +010069def limbs_mpi(val: int, bits_in_limb: int) -> int:
70 """Return the number of limbs required to store value."""
71 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010072
73def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010074 """Return all pair combinations from input values."""
75 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010076
Janos Follath0cd89672022-11-09 12:14:14 +000077class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010078 """Common features for bignum binary operations.
79
80 This adds functionality common in binary operation tests.
81
82 Attributes:
83 symbol: Symbol to use for the operation in case description.
84 input_values: List of values to use as test case inputs. These are
85 combined to produce pairs of values.
86 input_cases: List of tuples containing pairs of test case inputs. This
87 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010088 unique_combinations_only: Boolean to select if test case combinations
89 must be unique. If True, only A,B or B,A would be included as a test
90 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000091 input_style: Controls the way how test data is passed to the functions
92 in the generated test cases. "variable" passes them as they are
93 defined in the python source. "arch_split" pads the values with
94 zeroes depending on the architecture/limb size. If this is set,
95 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000096 arity: the number of operands for the operation. Currently supported
97 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010098 """
99 symbol = ""
Janos Follathdac44e62022-11-20 11:58:12 +0000100 input_values = INPUTS_DEFAULT # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +0000101 input_cases = [] # type: List[Any]
Janos Follathf4579762022-11-20 13:32:54 +0000102 unique_combinations_only = False
Janos Follatha36e4302022-11-19 15:55:53 +0000103 input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
Janos Follath6fa3f062022-11-17 20:33:51 +0000104 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +0000105 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +0000106 arities = [1, 2]
107 arity = 2
Tom Cosgrove61292682022-12-08 09:44:10 +0000108 suffix = False # for arity = 1, symbol can be prefix (default) or suffix
Werner Lewis99e81782022-09-30 16:28:43 +0100109
Janos Follatha36e4302022-11-19 15:55:53 +0000110 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000111 self.val_a = val_a
112 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000113 # Setting the int versions here as opposed to making them @properties
114 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100115 self.int_a = hex_to_int(val_a)
116 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000117 if bits_in_limb not in self.limb_sizes:
118 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000119 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000120 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
121 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100122
Janos Follathb41ab922022-11-17 15:13:02 +0000123 @property
124 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000125 if self.arity == 1:
126 return self.int_a
127 elif self.arity == 2:
128 return max(self.int_a, self.int_b)
129 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000130
131 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000132 def limb_boundary(self) -> int:
133 return bound_mpi(self.boundary, self.bits_in_limb)
134
135 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000136 def limbs(self) -> int:
137 return limbs_mpi(self.boundary, self.bits_in_limb)
138
139 @property
140 def hex_digits(self) -> int:
141 return 2 * (self.limbs * self.bits_in_limb // 8)
142
Gilles Peskinef8a44632022-12-20 19:12:22 +0100143 def format_arg(self, val: str) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000144 if self.input_style not in self.input_styles:
145 raise ValueError("Unknown input style!")
146 if self.input_style == "variable":
147 return val
148 else:
149 return val.zfill(self.hex_digits)
150
Gilles Peskinef8a44632022-12-20 19:12:22 +0100151 def format_result(self, res: int) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000152 res_str = '{:x}'.format(res)
153 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000154
155 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000156 def arg_a(self) -> str:
157 return self.format_arg(self.val_a)
158
159 @property
160 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000161 if self.arity == 1:
162 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000163 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000164
Werner Lewis99e81782022-09-30 16:28:43 +0100165 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000166 args = [quote_str(self.arg_a)]
167 if self.arity == 2:
168 args.append(quote_str(self.arg_b))
169 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100170
Janos Follath3aeb60a2022-11-09 13:24:46 +0000171 def description(self) -> str:
172 """Generate a description for the test case.
173
174 If not set, case_description uses the form A `symbol` B, where symbol
175 is used to represent the operation. Descriptions of each value are
176 generated to provide some context to the test case.
177 """
178 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000179 if self.arity == 1:
Tom Cosgrove61292682022-12-08 09:44:10 +0000180 format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}"
181 self.case_description = format_string.format(
Janos Follath8ae7a652022-11-19 15:05:19 +0000182 self.symbol, self.int_a
183 )
184 elif self.arity == 2:
185 self.case_description = "{:x} {} {:x}".format(
186 self.int_a, self.symbol, self.int_b
187 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000188 return super().description()
189
Janos Follath939621f2022-11-18 18:15:24 +0000190 @property
191 def is_valid(self) -> bool:
192 return True
193
Werner Lewis99e81782022-09-30 16:28:43 +0100194 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100195 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100196 """Get the result of the operation.
197
198 This could be calculated during initialization and stored as `_result`
199 and then returned, or calculated when the method is called.
200 """
201 raise NotImplementedError
202
203 @classmethod
204 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
205 """Generator to yield pairs of inputs.
206
207 Combinations are first generated from all input values, and then
208 specific cases provided.
209 """
Janos Follath284672c2022-11-19 14:55:43 +0000210 if cls.arity == 1:
211 yield from ((a, "0") for a in cls.input_values)
212 elif cls.arity == 2:
213 if cls.unique_combinations_only:
214 yield from combination_pairs(cls.input_values)
215 else:
216 yield from (
217 (a, b)
218 for a in cls.input_values
219 for b in cls.input_values
220 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100221 else:
Janos Follath284672c2022-11-19 14:55:43 +0000222 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000223
Janos Follath87df3732022-11-09 12:31:23 +0000224 @classmethod
225 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000226 if cls.input_style not in cls.input_styles:
227 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000228 if cls.arity not in cls.arities:
229 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000230 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000231 test_objects = (cls(a, b, bits_in_limb=bil)
232 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000233 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000234 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
235 for args in cls.input_cases
236 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000237 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000238 test_objects = (cls(a, b)
239 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000240 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000241 yield from (valid_test_object.create_test_case()
242 for valid_test_object in filter(
243 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000244 chain(test_objects, special_cases)
245 )
246 )
247
Janos Follath87df3732022-11-09 12:31:23 +0000248
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100249class ModulusRepresentation(enum.Enum):
250 """Representation selector of a modulus."""
251 # Numerical values aligned with the type mbedtls_mpi_mod_rep_selector
252 INVALID = 0
253 MONTGOMERY = 2
254 OPT_RED = 3
255
256 def symbol(self) -> str:
257 """The C symbol for this representation selector."""
258 return 'MBEDTLS_MPI_MOD_REP_' + self.name
259
260 @classmethod
261 def supported_representations(cls) -> List['ModulusRepresentation']:
262 """Return all representations that are supported in positive test cases."""
263 return [cls.MONTGOMERY, cls.OPT_RED]
264
265
Janos Follath5b1dbb42022-11-17 13:32:43 +0000266class ModOperationCommon(OperationCommon):
267 #pylint: disable=abstract-method
268 """Target for bignum mod_raw test case generation."""
Janos Follathdac44e62022-11-20 11:58:12 +0000269 moduli = MODULI_DEFAULT # type: List[str]
Tom Cosgrovef7237542022-12-16 16:10:36 +0000270 montgomery_form_a = False
Tom Cosgrove1133d232022-12-16 03:53:17 +0000271 disallow_zero_a = False
Janos Follath5b1dbb42022-11-17 13:32:43 +0000272
Janos Follath155ad8c2022-11-17 14:42:40 +0000273 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
274 bits_in_limb: int = 64) -> None:
275 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000276 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000277 # Setting the int versions here as opposed to making them @properties
278 # provides earlier/more robust input validation.
279 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000280
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000281 def to_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000282 return (val * self.r) % self.int_n
283
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000284 def from_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000285 return (val * self.r_inv) % self.int_n
286
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100287 def convert_from_canonical(self, canonical: int,
288 rep: ModulusRepresentation) -> int:
289 """Convert values from canonical representation to the given representation."""
290 if rep is ModulusRepresentation.MONTGOMERY:
291 return self.to_montgomery(canonical)
292 elif rep is ModulusRepresentation.OPT_RED:
293 return canonical
294 else:
295 raise ValueError('Modulus representation not supported: {}'
296 .format(rep.name))
297
Janos Follath5b1dbb42022-11-17 13:32:43 +0000298 @property
299 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000300 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000301
302 @property
Tom Cosgrove1133d232022-12-16 03:53:17 +0000303 def arg_a(self) -> str:
Tom Cosgrovef7237542022-12-16 16:10:36 +0000304 if self.montgomery_form_a:
Tom Cosgrove1133d232022-12-16 03:53:17 +0000305 value_a = self.to_montgomery(self.int_a)
306 else:
307 value_a = self.int_a
308 return self.format_arg('{:x}'.format(value_a))
309
310 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000311 def arg_n(self) -> str:
312 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000313
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100314 def format_arg(self, val: str) -> str:
Minos Galanakis3d2aab82022-12-21 17:30:10 +0000315 return super().format_arg(val).zfill(self.hex_digits)
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100316
Janos Follatha36a3d32022-11-18 17:49:13 +0000317 def arguments(self) -> List[str]:
318 return [quote_str(self.arg_n)] + super().arguments()
319
Janos Follath5b1dbb42022-11-17 13:32:43 +0000320 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000321 def r(self) -> int: # pylint: disable=invalid-name
322 l = limbs_mpi(self.int_n, self.bits_in_limb)
323 return bound_mpi_limbs(l, self.bits_in_limb)
324
325 @property
326 def r_inv(self) -> int:
327 return invmod(self.r, self.int_n)
328
329 @property
330 def r2(self) -> int: # pylint: disable=invalid-name
331 return pow(self.r, 2)
332
Janos Follathc4fca5d2022-11-19 10:42:20 +0000333 @property
334 def is_valid(self) -> bool:
335 if self.int_a >= self.int_n:
336 return False
Tom Cosgrove1133d232022-12-16 03:53:17 +0000337 if self.disallow_zero_a and self.int_a == 0:
338 return False
Janos Follathc4fca5d2022-11-19 10:42:20 +0000339 if self.arity == 2 and self.int_b >= self.int_n:
340 return False
341 return True
342
Janos Follath8ae7a652022-11-19 15:05:19 +0000343 def description(self) -> str:
344 """Generate a description for the test case.
345
346 It uses the form A `symbol` B mod N, where symbol is used to represent
347 the operation.
348 """
349
350 if not self.case_description:
351 return super().description() + " mod {:x}".format(self.int_n)
352 return super().description()
353
Janos Follathc4fca5d2022-11-19 10:42:20 +0000354 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000355 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
356 if cls.arity == 1:
357 yield from ((n, a, "0") for a, n in cls.input_cases)
358 elif cls.arity == 2:
359 yield from ((n, a, b) for a, b, n in cls.input_cases)
360 else:
361 raise ValueError("Unsupported number of operands!")
362
363 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000364 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
365 if cls.input_style not in cls.input_styles:
366 raise ValueError("Unknown input style!")
367 if cls.arity not in cls.arities:
368 raise ValueError("Unsupported number of operands!")
369 if cls.input_style == "arch_split":
370 test_objects = (cls(n, a, b, bits_in_limb=bil)
371 for n in cls.moduli
372 for a, b in cls.get_value_pairs()
373 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000374 special_cases = (cls(*args, bits_in_limb=bil)
375 for args in cls.input_cases_args()
376 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000377 else:
378 test_objects = (cls(n, a, b)
379 for n in cls.moduli
380 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000381 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000382 yield from (valid_test_object.create_test_case()
383 for valid_test_object in filter(
384 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000385 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000386 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000387
Janos Follathf8b3b722022-11-03 14:46:18 +0000388# BEGIN MERGE SLOT 1
389
390# END MERGE SLOT 1
391
392# BEGIN MERGE SLOT 2
393
394# END MERGE SLOT 2
395
396# BEGIN MERGE SLOT 3
397
398# END MERGE SLOT 3
399
400# BEGIN MERGE SLOT 4
401
402# END MERGE SLOT 4
403
404# BEGIN MERGE SLOT 5
405
406# END MERGE SLOT 5
407
408# BEGIN MERGE SLOT 6
409
410# END MERGE SLOT 6
411
412# BEGIN MERGE SLOT 7
413
414# END MERGE SLOT 7
415
416# BEGIN MERGE SLOT 8
417
418# END MERGE SLOT 8
419
420# BEGIN MERGE SLOT 9
421
422# END MERGE SLOT 9
423
424# BEGIN MERGE SLOT 10
425
426# END MERGE SLOT 10