blob: e03c1c3f8a25efeea45f48996426766a628fee5f [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
Janos Follathdac44e62022-11-20 11:58:12 +000023from .bignum_data import INPUTS_DEFAULT, MODULI_DEFAULT
Janos Follath0cd89672022-11-09 12:14:14 +000024
Werner Lewis99e81782022-09-30 16:28:43 +010025T = TypeVar('T') #pylint: disable=invalid-name
26
Werner Lewisa8503122022-10-04 10:10:40 +010027def invmod(a: int, n: int) -> int:
28 """Return inverse of a to modulo n.
29
30 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
31 to long_invmod() in CPython.
32 """
33 b, c = 1, 0
34 while n:
35 q, r = divmod(a, n)
36 a, b, c, n = n, c, b - q*c, r
37 # at this point a is the gcd of the original inputs
38 if a == 1:
39 return b
40 raise ValueError("Not invertible")
41
Werner Lewis99e81782022-09-30 16:28:43 +010042def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010043 """Implement the syntax accepted by mbedtls_test_read_mpi().
44
45 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
46 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010047 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010048 return 0
49 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010050
51def quote_str(val) -> str:
52 return "\"{}\"".format(val)
53
Werner Lewisf86c82e2022-10-19 13:50:10 +010054def bound_mpi(val: int, bits_in_limb: int) -> int:
55 """First number exceeding number of limbs needed for given input value."""
56 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010057
Werner Lewisf86c82e2022-10-19 13:50:10 +010058def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
59 """First number exceeding maximum of given number of limbs."""
60 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010061 return 1 << bits
62
Werner Lewisf86c82e2022-10-19 13:50:10 +010063def limbs_mpi(val: int, bits_in_limb: int) -> int:
64 """Return the number of limbs required to store value."""
65 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010066
67def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010068 """Return all pair combinations from input values."""
69 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010070
Janos Follath0cd89672022-11-09 12:14:14 +000071class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010072 """Common features for bignum binary operations.
73
74 This adds functionality common in binary operation tests.
75
76 Attributes:
77 symbol: Symbol to use for the operation in case description.
78 input_values: List of values to use as test case inputs. These are
79 combined to produce pairs of values.
80 input_cases: List of tuples containing pairs of test case inputs. This
81 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010082 unique_combinations_only: Boolean to select if test case combinations
83 must be unique. If True, only A,B or B,A would be included as a test
84 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000085 input_style: Controls the way how test data is passed to the functions
86 in the generated test cases. "variable" passes them as they are
87 defined in the python source. "arch_split" pads the values with
88 zeroes depending on the architecture/limb size. If this is set,
89 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000090 arity: the number of operands for the operation. Currently supported
91 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010092 """
93 symbol = ""
Janos Follathdac44e62022-11-20 11:58:12 +000094 input_values = INPUTS_DEFAULT # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +000095 input_cases = [] # type: List[Any]
Werner Lewisbbf0a322022-10-04 10:07:13 +010096 unique_combinations_only = True
Janos Follatha36e4302022-11-19 15:55:53 +000097 input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
Janos Follath6fa3f062022-11-17 20:33:51 +000098 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +000099 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +0000100 arities = [1, 2]
101 arity = 2
Werner Lewis99e81782022-09-30 16:28:43 +0100102
Janos Follatha36e4302022-11-19 15:55:53 +0000103 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000104 self.val_a = val_a
105 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000106 # Setting the int versions here as opposed to making them @properties
107 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100108 self.int_a = hex_to_int(val_a)
109 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000110 if bits_in_limb not in self.limb_sizes:
111 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000112 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000113 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
114 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100115
Janos Follathb41ab922022-11-17 15:13:02 +0000116 @property
117 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000118 if self.arity == 1:
119 return self.int_a
120 elif self.arity == 2:
121 return max(self.int_a, self.int_b)
122 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000123
124 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000125 def limb_boundary(self) -> int:
126 return bound_mpi(self.boundary, self.bits_in_limb)
127
128 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000129 def limbs(self) -> int:
130 return limbs_mpi(self.boundary, self.bits_in_limb)
131
132 @property
133 def hex_digits(self) -> int:
134 return 2 * (self.limbs * self.bits_in_limb // 8)
135
Janos Follath4c59d352022-11-18 16:05:46 +0000136 def format_arg(self, val) -> str:
137 if self.input_style not in self.input_styles:
138 raise ValueError("Unknown input style!")
139 if self.input_style == "variable":
140 return val
141 else:
142 return val.zfill(self.hex_digits)
143
144 def format_result(self, res) -> str:
145 res_str = '{:x}'.format(res)
146 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000147
148 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000149 def arg_a(self) -> str:
150 return self.format_arg(self.val_a)
151
152 @property
153 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000154 if self.arity == 1:
155 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000156 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000157
Werner Lewis99e81782022-09-30 16:28:43 +0100158 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000159 args = [quote_str(self.arg_a)]
160 if self.arity == 2:
161 args.append(quote_str(self.arg_b))
162 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100163
Janos Follath3aeb60a2022-11-09 13:24:46 +0000164 def description(self) -> str:
165 """Generate a description for the test case.
166
167 If not set, case_description uses the form A `symbol` B, where symbol
168 is used to represent the operation. Descriptions of each value are
169 generated to provide some context to the test case.
170 """
171 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000172 if self.arity == 1:
173 self.case_description = "{} {:x}".format(
174 self.symbol, self.int_a
175 )
176 elif self.arity == 2:
177 self.case_description = "{:x} {} {:x}".format(
178 self.int_a, self.symbol, self.int_b
179 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000180 return super().description()
181
Janos Follath939621f2022-11-18 18:15:24 +0000182 @property
183 def is_valid(self) -> bool:
184 return True
185
Werner Lewis99e81782022-09-30 16:28:43 +0100186 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100187 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100188 """Get the result of the operation.
189
190 This could be calculated during initialization and stored as `_result`
191 and then returned, or calculated when the method is called.
192 """
193 raise NotImplementedError
194
195 @classmethod
196 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
197 """Generator to yield pairs of inputs.
198
199 Combinations are first generated from all input values, and then
200 specific cases provided.
201 """
Janos Follath284672c2022-11-19 14:55:43 +0000202 if cls.arity == 1:
203 yield from ((a, "0") for a in cls.input_values)
204 elif cls.arity == 2:
205 if cls.unique_combinations_only:
206 yield from combination_pairs(cls.input_values)
207 else:
208 yield from (
209 (a, b)
210 for a in cls.input_values
211 for b in cls.input_values
212 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100213 else:
Janos Follath284672c2022-11-19 14:55:43 +0000214 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000215
Janos Follath87df3732022-11-09 12:31:23 +0000216 @classmethod
217 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000218 if cls.input_style not in cls.input_styles:
219 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000220 if cls.arity not in cls.arities:
221 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000222 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000223 test_objects = (cls(a, b, bits_in_limb=bil)
224 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000225 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000226 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
227 for args in cls.input_cases
228 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000229 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000230 test_objects = (cls(a, b)
231 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000232 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000233 yield from (valid_test_object.create_test_case()
234 for valid_test_object in filter(
235 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000236 chain(test_objects, special_cases)
237 )
238 )
239
Janos Follath87df3732022-11-09 12:31:23 +0000240
Janos Follath5b1dbb42022-11-17 13:32:43 +0000241class ModOperationCommon(OperationCommon):
242 #pylint: disable=abstract-method
243 """Target for bignum mod_raw test case generation."""
Janos Follathdac44e62022-11-20 11:58:12 +0000244 moduli = MODULI_DEFAULT # type: List[str]
Janos Follath5b1dbb42022-11-17 13:32:43 +0000245
Janos Follath155ad8c2022-11-17 14:42:40 +0000246 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
247 bits_in_limb: int = 64) -> None:
248 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000249 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000250 # Setting the int versions here as opposed to making them @properties
251 # provides earlier/more robust input validation.
252 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000253
254 @property
255 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000256 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000257
258 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000259 def arg_n(self) -> str:
260 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000261
Janos Follatha36a3d32022-11-18 17:49:13 +0000262 def arguments(self) -> List[str]:
263 return [quote_str(self.arg_n)] + super().arguments()
264
Janos Follath5b1dbb42022-11-17 13:32:43 +0000265 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000266 def r(self) -> int: # pylint: disable=invalid-name
267 l = limbs_mpi(self.int_n, self.bits_in_limb)
268 return bound_mpi_limbs(l, self.bits_in_limb)
269
270 @property
271 def r_inv(self) -> int:
272 return invmod(self.r, self.int_n)
273
274 @property
275 def r2(self) -> int: # pylint: disable=invalid-name
276 return pow(self.r, 2)
277
Janos Follathc4fca5d2022-11-19 10:42:20 +0000278 @property
279 def is_valid(self) -> bool:
280 if self.int_a >= self.int_n:
281 return False
282 if self.arity == 2 and self.int_b >= self.int_n:
283 return False
284 return True
285
Janos Follath8ae7a652022-11-19 15:05:19 +0000286 def description(self) -> str:
287 """Generate a description for the test case.
288
289 It uses the form A `symbol` B mod N, where symbol is used to represent
290 the operation.
291 """
292
293 if not self.case_description:
294 return super().description() + " mod {:x}".format(self.int_n)
295 return super().description()
296
Janos Follathc4fca5d2022-11-19 10:42:20 +0000297 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000298 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
299 if cls.arity == 1:
300 yield from ((n, a, "0") for a, n in cls.input_cases)
301 elif cls.arity == 2:
302 yield from ((n, a, b) for a, b, n in cls.input_cases)
303 else:
304 raise ValueError("Unsupported number of operands!")
305
306 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000307 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
308 if cls.input_style not in cls.input_styles:
309 raise ValueError("Unknown input style!")
310 if cls.arity not in cls.arities:
311 raise ValueError("Unsupported number of operands!")
312 if cls.input_style == "arch_split":
313 test_objects = (cls(n, a, b, bits_in_limb=bil)
314 for n in cls.moduli
315 for a, b in cls.get_value_pairs()
316 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000317 special_cases = (cls(*args, bits_in_limb=bil)
318 for args in cls.input_cases_args()
319 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000320 else:
321 test_objects = (cls(n, a, b)
322 for n in cls.moduli
323 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000324 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000325 yield from (valid_test_object.create_test_case()
326 for valid_test_object in filter(
327 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000328 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000329 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000330
Janos Follathf8b3b722022-11-03 14:46:18 +0000331# BEGIN MERGE SLOT 1
332
333# END MERGE SLOT 1
334
335# BEGIN MERGE SLOT 2
336
337# END MERGE SLOT 2
338
339# BEGIN MERGE SLOT 3
340
341# END MERGE SLOT 3
342
343# BEGIN MERGE SLOT 4
344
345# END MERGE SLOT 4
346
347# BEGIN MERGE SLOT 5
348
349# END MERGE SLOT 5
350
351# BEGIN MERGE SLOT 6
352
353# END MERGE SLOT 6
354
355# BEGIN MERGE SLOT 7
356
357# END MERGE SLOT 7
358
359# BEGIN MERGE SLOT 8
360
361# END MERGE SLOT 8
362
363# BEGIN MERGE SLOT 9
364
365# END MERGE SLOT 9
366
367# BEGIN MERGE SLOT 10
368
369# END MERGE SLOT 10