blob: bb64ce0796ce7ce791d46f6ebe9fd72e1b189bdc [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
Werner Lewis99e81782022-09-30 16:28:43 +010043def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010044 """Implement the syntax accepted by mbedtls_test_read_mpi().
45
46 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
47 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010048 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010049 return 0
50 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010051
Gilles Peskinef8a44632022-12-20 19:12:22 +010052def quote_str(val: str) -> str:
Werner Lewis99e81782022-09-30 16:28:43 +010053 return "\"{}\"".format(val)
54
Werner Lewisf86c82e2022-10-19 13:50:10 +010055def bound_mpi(val: int, bits_in_limb: int) -> int:
56 """First number exceeding number of limbs needed for given input value."""
57 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010058
Werner Lewisf86c82e2022-10-19 13:50:10 +010059def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
60 """First number exceeding maximum of given number of limbs."""
61 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010062 return 1 << bits
63
Werner Lewisf86c82e2022-10-19 13:50:10 +010064def limbs_mpi(val: int, bits_in_limb: int) -> int:
65 """Return the number of limbs required to store value."""
66 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010067
68def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010069 """Return all pair combinations from input values."""
70 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010071
Janos Follath0cd89672022-11-09 12:14:14 +000072class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010073 """Common features for bignum binary operations.
74
75 This adds functionality common in binary operation tests.
76
77 Attributes:
78 symbol: Symbol to use for the operation in case description.
79 input_values: List of values to use as test case inputs. These are
80 combined to produce pairs of values.
81 input_cases: List of tuples containing pairs of test case inputs. This
82 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010083 unique_combinations_only: Boolean to select if test case combinations
84 must be unique. If True, only A,B or B,A would be included as a test
85 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000086 input_style: Controls the way how test data is passed to the functions
87 in the generated test cases. "variable" passes them as they are
88 defined in the python source. "arch_split" pads the values with
89 zeroes depending on the architecture/limb size. If this is set,
90 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000091 arity: the number of operands for the operation. Currently supported
92 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010093 """
94 symbol = ""
Janos Follathdac44e62022-11-20 11:58:12 +000095 input_values = INPUTS_DEFAULT # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +000096 input_cases = [] # type: List[Any]
Janos Follathf4579762022-11-20 13:32:54 +000097 unique_combinations_only = False
Janos Follatha36e4302022-11-19 15:55:53 +000098 input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
Janos Follath6fa3f062022-11-17 20:33:51 +000099 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +0000100 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +0000101 arities = [1, 2]
102 arity = 2
Tom Cosgrove61292682022-12-08 09:44:10 +0000103 suffix = False # for arity = 1, symbol can be prefix (default) or suffix
Werner Lewis99e81782022-09-30 16:28:43 +0100104
Janos Follatha36e4302022-11-19 15:55:53 +0000105 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000106 self.val_a = val_a
107 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000108 # Setting the int versions here as opposed to making them @properties
109 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100110 self.int_a = hex_to_int(val_a)
111 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000112 if bits_in_limb not in self.limb_sizes:
113 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000114 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000115 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
116 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100117
Janos Follathb41ab922022-11-17 15:13:02 +0000118 @property
119 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000120 if self.arity == 1:
121 return self.int_a
122 elif self.arity == 2:
123 return max(self.int_a, self.int_b)
124 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000125
126 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000127 def limb_boundary(self) -> int:
128 return bound_mpi(self.boundary, self.bits_in_limb)
129
130 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000131 def limbs(self) -> int:
132 return limbs_mpi(self.boundary, self.bits_in_limb)
133
134 @property
135 def hex_digits(self) -> int:
136 return 2 * (self.limbs * self.bits_in_limb // 8)
137
Gilles Peskinef8a44632022-12-20 19:12:22 +0100138 def format_arg(self, val: str) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000139 if self.input_style not in self.input_styles:
140 raise ValueError("Unknown input style!")
141 if self.input_style == "variable":
142 return val
143 else:
144 return val.zfill(self.hex_digits)
145
Gilles Peskinef8a44632022-12-20 19:12:22 +0100146 def format_result(self, res: int) -> str:
Janos Follath4c59d352022-11-18 16:05:46 +0000147 res_str = '{:x}'.format(res)
148 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000149
150 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000151 def arg_a(self) -> str:
152 return self.format_arg(self.val_a)
153
154 @property
155 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000156 if self.arity == 1:
157 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000158 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000159
Werner Lewis99e81782022-09-30 16:28:43 +0100160 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000161 args = [quote_str(self.arg_a)]
162 if self.arity == 2:
163 args.append(quote_str(self.arg_b))
164 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100165
Janos Follath3aeb60a2022-11-09 13:24:46 +0000166 def description(self) -> str:
167 """Generate a description for the test case.
168
169 If not set, case_description uses the form A `symbol` B, where symbol
170 is used to represent the operation. Descriptions of each value are
171 generated to provide some context to the test case.
172 """
173 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000174 if self.arity == 1:
Tom Cosgrove61292682022-12-08 09:44:10 +0000175 format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}"
176 self.case_description = format_string.format(
Janos Follath8ae7a652022-11-19 15:05:19 +0000177 self.symbol, self.int_a
178 )
179 elif self.arity == 2:
180 self.case_description = "{:x} {} {:x}".format(
181 self.int_a, self.symbol, self.int_b
182 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000183 return super().description()
184
Janos Follath939621f2022-11-18 18:15:24 +0000185 @property
186 def is_valid(self) -> bool:
187 return True
188
Werner Lewis99e81782022-09-30 16:28:43 +0100189 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100190 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100191 """Get the result of the operation.
192
193 This could be calculated during initialization and stored as `_result`
194 and then returned, or calculated when the method is called.
195 """
196 raise NotImplementedError
197
198 @classmethod
199 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
200 """Generator to yield pairs of inputs.
201
202 Combinations are first generated from all input values, and then
203 specific cases provided.
204 """
Janos Follath284672c2022-11-19 14:55:43 +0000205 if cls.arity == 1:
206 yield from ((a, "0") for a in cls.input_values)
207 elif cls.arity == 2:
208 if cls.unique_combinations_only:
209 yield from combination_pairs(cls.input_values)
210 else:
211 yield from (
212 (a, b)
213 for a in cls.input_values
214 for b in cls.input_values
215 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100216 else:
Janos Follath284672c2022-11-19 14:55:43 +0000217 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000218
Janos Follath87df3732022-11-09 12:31:23 +0000219 @classmethod
220 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000221 if cls.input_style not in cls.input_styles:
222 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000223 if cls.arity not in cls.arities:
224 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000225 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000226 test_objects = (cls(a, b, bits_in_limb=bil)
227 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000228 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000229 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
230 for args in cls.input_cases
231 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000232 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000233 test_objects = (cls(a, b)
234 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000235 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000236 yield from (valid_test_object.create_test_case()
237 for valid_test_object in filter(
238 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000239 chain(test_objects, special_cases)
240 )
241 )
242
Janos Follath87df3732022-11-09 12:31:23 +0000243
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100244class ModulusRepresentation(enum.Enum):
245 """Representation selector of a modulus."""
246 # Numerical values aligned with the type mbedtls_mpi_mod_rep_selector
247 INVALID = 0
248 MONTGOMERY = 2
249 OPT_RED = 3
250
251 def symbol(self) -> str:
252 """The C symbol for this representation selector."""
253 return 'MBEDTLS_MPI_MOD_REP_' + self.name
254
255 @classmethod
256 def supported_representations(cls) -> List['ModulusRepresentation']:
257 """Return all representations that are supported in positive test cases."""
258 return [cls.MONTGOMERY, cls.OPT_RED]
259
260
Janos Follath5b1dbb42022-11-17 13:32:43 +0000261class ModOperationCommon(OperationCommon):
262 #pylint: disable=abstract-method
263 """Target for bignum mod_raw test case generation."""
Janos Follathdac44e62022-11-20 11:58:12 +0000264 moduli = MODULI_DEFAULT # type: List[str]
Janos Follath5b1dbb42022-11-17 13:32:43 +0000265
Janos Follath155ad8c2022-11-17 14:42:40 +0000266 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
267 bits_in_limb: int = 64) -> None:
268 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000269 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000270 # Setting the int versions here as opposed to making them @properties
271 # provides earlier/more robust input validation.
272 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000273
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000274 def to_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000275 return (val * self.r) % self.int_n
276
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000277 def from_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000278 return (val * self.r_inv) % self.int_n
279
Gilles Peskine7a708fd2022-12-20 19:19:18 +0100280 def convert_from_canonical(self, canonical: int,
281 rep: ModulusRepresentation) -> int:
282 """Convert values from canonical representation to the given representation."""
283 if rep is ModulusRepresentation.MONTGOMERY:
284 return self.to_montgomery(canonical)
285 elif rep is ModulusRepresentation.OPT_RED:
286 return canonical
287 else:
288 raise ValueError('Modulus representation not supported: {}'
289 .format(rep.name))
290
Janos Follath5b1dbb42022-11-17 13:32:43 +0000291 @property
292 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000293 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000294
295 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000296 def arg_n(self) -> str:
297 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000298
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100299 def format_arg(self, val: str) -> str:
Minos Galanakis3d2aab82022-12-21 17:30:10 +0000300 return super().format_arg(val).zfill(self.hex_digits)
Gilles Peskine5623ecc2022-12-20 19:16:54 +0100301
Janos Follatha36a3d32022-11-18 17:49:13 +0000302 def arguments(self) -> List[str]:
303 return [quote_str(self.arg_n)] + super().arguments()
304
Janos Follath5b1dbb42022-11-17 13:32:43 +0000305 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000306 def r(self) -> int: # pylint: disable=invalid-name
307 l = limbs_mpi(self.int_n, self.bits_in_limb)
308 return bound_mpi_limbs(l, self.bits_in_limb)
309
310 @property
311 def r_inv(self) -> int:
312 return invmod(self.r, self.int_n)
313
314 @property
315 def r2(self) -> int: # pylint: disable=invalid-name
316 return pow(self.r, 2)
317
Janos Follathc4fca5d2022-11-19 10:42:20 +0000318 @property
319 def is_valid(self) -> bool:
320 if self.int_a >= self.int_n:
321 return False
322 if self.arity == 2 and self.int_b >= self.int_n:
323 return False
324 return True
325
Janos Follath8ae7a652022-11-19 15:05:19 +0000326 def description(self) -> str:
327 """Generate a description for the test case.
328
329 It uses the form A `symbol` B mod N, where symbol is used to represent
330 the operation.
331 """
332
333 if not self.case_description:
334 return super().description() + " mod {:x}".format(self.int_n)
335 return super().description()
336
Janos Follathc4fca5d2022-11-19 10:42:20 +0000337 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000338 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
339 if cls.arity == 1:
340 yield from ((n, a, "0") for a, n in cls.input_cases)
341 elif cls.arity == 2:
342 yield from ((n, a, b) for a, b, n in cls.input_cases)
343 else:
344 raise ValueError("Unsupported number of operands!")
345
346 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000347 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
348 if cls.input_style not in cls.input_styles:
349 raise ValueError("Unknown input style!")
350 if cls.arity not in cls.arities:
351 raise ValueError("Unsupported number of operands!")
352 if cls.input_style == "arch_split":
353 test_objects = (cls(n, a, b, bits_in_limb=bil)
354 for n in cls.moduli
355 for a, b in cls.get_value_pairs()
356 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000357 special_cases = (cls(*args, bits_in_limb=bil)
358 for args in cls.input_cases_args()
359 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000360 else:
361 test_objects = (cls(n, a, b)
362 for n in cls.moduli
363 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000364 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000365 yield from (valid_test_object.create_test_case()
366 for valid_test_object in filter(
367 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000368 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000369 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000370
Janos Follathf8b3b722022-11-03 14:46:18 +0000371# BEGIN MERGE SLOT 1
372
373# END MERGE SLOT 1
374
375# BEGIN MERGE SLOT 2
376
377# END MERGE SLOT 2
378
379# BEGIN MERGE SLOT 3
380
381# END MERGE SLOT 3
382
383# BEGIN MERGE SLOT 4
384
385# END MERGE SLOT 4
386
387# BEGIN MERGE SLOT 5
388
389# END MERGE SLOT 5
390
391# BEGIN MERGE SLOT 6
392
393# END MERGE SLOT 6
394
395# BEGIN MERGE SLOT 7
396
397# END MERGE SLOT 7
398
399# BEGIN MERGE SLOT 8
400
401# END MERGE SLOT 8
402
403# BEGIN MERGE SLOT 9
404
405# END MERGE SLOT 9
406
407# BEGIN MERGE SLOT 10
408
409# END MERGE SLOT 10