blob: 9e92b8e61a2e86e08d9ce590a8793ad12e88a462 [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
Janos Follath98edf212022-11-19 12:48:17 +000018from typing import Iterator, List, Tuple, TypeVar, Any
19from itertools import chain
Werner Lewis99e81782022-09-30 16:28:43 +010020
Janos Follath87df3732022-11-09 12:31:23 +000021from . import test_case
Janos Follath0cd89672022-11-09 12:14:14 +000022from . import test_data_generation
23
Werner Lewis99e81782022-09-30 16:28:43 +010024T = TypeVar('T') #pylint: disable=invalid-name
25
Werner Lewisa8503122022-10-04 10:10:40 +010026def invmod(a: int, n: int) -> int:
27 """Return inverse of a to modulo n.
28
29 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
30 to long_invmod() in CPython.
31 """
32 b, c = 1, 0
33 while n:
34 q, r = divmod(a, n)
35 a, b, c, n = n, c, b - q*c, r
36 # at this point a is the gcd of the original inputs
37 if a == 1:
38 return b
39 raise ValueError("Not invertible")
40
Werner Lewis99e81782022-09-30 16:28:43 +010041def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010042 """Implement the syntax accepted by mbedtls_test_read_mpi().
43
44 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
45 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010046 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010047 return 0
48 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010049
50def quote_str(val) -> str:
51 return "\"{}\"".format(val)
52
Werner Lewisf86c82e2022-10-19 13:50:10 +010053def bound_mpi(val: int, bits_in_limb: int) -> int:
54 """First number exceeding number of limbs needed for given input value."""
55 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010056
Werner Lewisf86c82e2022-10-19 13:50:10 +010057def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
58 """First number exceeding maximum of given number of limbs."""
59 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010060 return 1 << bits
61
Werner Lewisf86c82e2022-10-19 13:50:10 +010062def limbs_mpi(val: int, bits_in_limb: int) -> int:
63 """Return the number of limbs required to store value."""
64 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010065
66def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010067 """Return all pair combinations from input values."""
68 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010069
Janos Follath0cd89672022-11-09 12:14:14 +000070class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010071 """Common features for bignum binary operations.
72
73 This adds functionality common in binary operation tests.
74
75 Attributes:
76 symbol: Symbol to use for the operation in case description.
77 input_values: List of values to use as test case inputs. These are
78 combined to produce pairs of values.
79 input_cases: List of tuples containing pairs of test case inputs. This
80 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010081 unique_combinations_only: Boolean to select if test case combinations
82 must be unique. If True, only A,B or B,A would be included as a test
83 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000084 input_style: Controls the way how test data is passed to the functions
85 in the generated test cases. "variable" passes them as they are
86 defined in the python source. "arch_split" pads the values with
87 zeroes depending on the architecture/limb size. If this is set,
88 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000089 arity: the number of operands for the operation. Currently supported
90 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010091 """
92 symbol = ""
93 input_values = [] # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +000094 input_cases = [] # type: List[Any]
Werner Lewisbbf0a322022-10-04 10:07:13 +010095 unique_combinations_only = True
Janos Follath6fa3f062022-11-17 20:33:51 +000096 input_styles = ["variable", "arch_split"] # type: List[str]
97 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +000098 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +000099 arities = [1, 2]
100 arity = 2
Werner Lewis99e81782022-09-30 16:28:43 +0100101
Janos Follatha36a3d32022-11-18 17:49:13 +0000102 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 64) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000103 self.val_a = val_a
104 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000105 # Setting the int versions here as opposed to making them @properties
106 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100107 self.int_a = hex_to_int(val_a)
108 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000109 if bits_in_limb not in self.limb_sizes:
110 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000111 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000112 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
113 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100114
Janos Follathb41ab922022-11-17 15:13:02 +0000115 @property
116 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000117 if self.arity == 1:
118 return self.int_a
119 elif self.arity == 2:
120 return max(self.int_a, self.int_b)
121 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000122
123 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000124 def limb_boundary(self) -> int:
125 return bound_mpi(self.boundary, self.bits_in_limb)
126
127 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000128 def limbs(self) -> int:
129 return limbs_mpi(self.boundary, self.bits_in_limb)
130
131 @property
132 def hex_digits(self) -> int:
133 return 2 * (self.limbs * self.bits_in_limb // 8)
134
Janos Follath4c59d352022-11-18 16:05:46 +0000135 def format_arg(self, val) -> str:
136 if self.input_style not in self.input_styles:
137 raise ValueError("Unknown input style!")
138 if self.input_style == "variable":
139 return val
140 else:
141 return val.zfill(self.hex_digits)
142
143 def format_result(self, res) -> str:
144 res_str = '{:x}'.format(res)
145 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000146
147 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000148 def arg_a(self) -> str:
149 return self.format_arg(self.val_a)
150
151 @property
152 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000153 if self.arity == 1:
154 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000155 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000156
Werner Lewis99e81782022-09-30 16:28:43 +0100157 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000158 args = [quote_str(self.arg_a)]
159 if self.arity == 2:
160 args.append(quote_str(self.arg_b))
161 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100162
Janos Follath3aeb60a2022-11-09 13:24:46 +0000163 def description(self) -> str:
164 """Generate a description for the test case.
165
166 If not set, case_description uses the form A `symbol` B, where symbol
167 is used to represent the operation. Descriptions of each value are
168 generated to provide some context to the test case.
169 """
170 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000171 if self.arity == 1:
172 self.case_description = "{} {:x}".format(
173 self.symbol, self.int_a
174 )
175 elif self.arity == 2:
176 self.case_description = "{:x} {} {:x}".format(
177 self.int_a, self.symbol, self.int_b
178 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000179 return super().description()
180
Janos Follath939621f2022-11-18 18:15:24 +0000181 @property
182 def is_valid(self) -> bool:
183 return True
184
Werner Lewis99e81782022-09-30 16:28:43 +0100185 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100186 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100187 """Get the result of the operation.
188
189 This could be calculated during initialization and stored as `_result`
190 and then returned, or calculated when the method is called.
191 """
192 raise NotImplementedError
193
194 @classmethod
195 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
196 """Generator to yield pairs of inputs.
197
198 Combinations are first generated from all input values, and then
199 specific cases provided.
200 """
Janos Follath284672c2022-11-19 14:55:43 +0000201 if cls.arity == 1:
202 yield from ((a, "0") for a in cls.input_values)
203 elif cls.arity == 2:
204 if cls.unique_combinations_only:
205 yield from combination_pairs(cls.input_values)
206 else:
207 yield from (
208 (a, b)
209 for a in cls.input_values
210 for b in cls.input_values
211 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100212 else:
Janos Follath284672c2022-11-19 14:55:43 +0000213 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000214
Janos Follath87df3732022-11-09 12:31:23 +0000215 @classmethod
216 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000217 if cls.input_style not in cls.input_styles:
218 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000219 if cls.arity not in cls.arities:
220 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000221 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000222 test_objects = (cls(a, b, bits_in_limb=bil)
223 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000224 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000225 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
226 for args in cls.input_cases
227 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000228 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000229 test_objects = (cls(a, b)
230 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000231 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000232 yield from (valid_test_object.create_test_case()
233 for valid_test_object in filter(
234 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000235 chain(test_objects, special_cases)
236 )
237 )
238
Janos Follath87df3732022-11-09 12:31:23 +0000239
Janos Follath5b1dbb42022-11-17 13:32:43 +0000240class ModOperationCommon(OperationCommon):
241 #pylint: disable=abstract-method
242 """Target for bignum mod_raw test case generation."""
Janos Follathc4fca5d2022-11-19 10:42:20 +0000243 moduli = [] # type: List[str]
Janos Follath5b1dbb42022-11-17 13:32:43 +0000244
Janos Follath155ad8c2022-11-17 14:42:40 +0000245 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
246 bits_in_limb: int = 64) -> None:
247 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000248 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000249 # Setting the int versions here as opposed to making them @properties
250 # provides earlier/more robust input validation.
251 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000252
253 @property
254 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000255 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000256
257 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000258 def arg_n(self) -> str:
259 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000260
Janos Follatha36a3d32022-11-18 17:49:13 +0000261 def arguments(self) -> List[str]:
262 return [quote_str(self.arg_n)] + super().arguments()
263
Janos Follath5b1dbb42022-11-17 13:32:43 +0000264 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000265 def r(self) -> int: # pylint: disable=invalid-name
266 l = limbs_mpi(self.int_n, self.bits_in_limb)
267 return bound_mpi_limbs(l, self.bits_in_limb)
268
269 @property
270 def r_inv(self) -> int:
271 return invmod(self.r, self.int_n)
272
273 @property
274 def r2(self) -> int: # pylint: disable=invalid-name
275 return pow(self.r, 2)
276
Janos Follathc4fca5d2022-11-19 10:42:20 +0000277 @property
278 def is_valid(self) -> bool:
279 if self.int_a >= self.int_n:
280 return False
281 if self.arity == 2 and self.int_b >= self.int_n:
282 return False
283 return True
284
Janos Follath8ae7a652022-11-19 15:05:19 +0000285 def description(self) -> str:
286 """Generate a description for the test case.
287
288 It uses the form A `symbol` B mod N, where symbol is used to represent
289 the operation.
290 """
291
292 if not self.case_description:
293 return super().description() + " mod {:x}".format(self.int_n)
294 return super().description()
295
Janos Follathc4fca5d2022-11-19 10:42:20 +0000296 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000297 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
298 if cls.arity == 1:
299 yield from ((n, a, "0") for a, n in cls.input_cases)
300 elif cls.arity == 2:
301 yield from ((n, a, b) for a, b, n in cls.input_cases)
302 else:
303 raise ValueError("Unsupported number of operands!")
304
305 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000306 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
307 if cls.input_style not in cls.input_styles:
308 raise ValueError("Unknown input style!")
309 if cls.arity not in cls.arities:
310 raise ValueError("Unsupported number of operands!")
311 if cls.input_style == "arch_split":
312 test_objects = (cls(n, a, b, bits_in_limb=bil)
313 for n in cls.moduli
314 for a, b in cls.get_value_pairs()
315 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000316 special_cases = (cls(*args, bits_in_limb=bil)
317 for args in cls.input_cases_args()
318 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000319 else:
320 test_objects = (cls(n, a, b)
321 for n in cls.moduli
322 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000323 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000324 yield from (valid_test_object.create_test_case()
325 for valid_test_object in filter(
326 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000327 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000328 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000329
Janos Follathf8b3b722022-11-03 14:46:18 +0000330# BEGIN MERGE SLOT 1
331
332# END MERGE SLOT 1
333
334# BEGIN MERGE SLOT 2
335
336# END MERGE SLOT 2
337
338# BEGIN MERGE SLOT 3
339
340# END MERGE SLOT 3
341
342# BEGIN MERGE SLOT 4
343
344# END MERGE SLOT 4
345
346# BEGIN MERGE SLOT 5
347
348# END MERGE SLOT 5
349
350# BEGIN MERGE SLOT 6
351
352# END MERGE SLOT 6
353
354# BEGIN MERGE SLOT 7
355
356# END MERGE SLOT 7
357
358# BEGIN MERGE SLOT 8
359
360# END MERGE SLOT 8
361
362# BEGIN MERGE SLOT 9
363
364# END MERGE SLOT 9
365
366# BEGIN MERGE SLOT 10
367
368# END MERGE SLOT 10