blob: dd4fc3684092df85b4eac61934a480ba383cd578 [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
Tom Cosgrove1133d232022-12-16 03:53:17 +000042def invmod_positive(a: int, n: int) -> int:
43 """Return a non-negative inverse of a to modulo n."""
44 inv = invmod(a, n)
45 return inv if inv >= 0 else inv + n
46
Werner Lewis99e81782022-09-30 16:28:43 +010047def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010048 """Implement the syntax accepted by mbedtls_test_read_mpi().
49
50 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
51 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010052 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010053 return 0
54 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010055
56def quote_str(val) -> str:
57 return "\"{}\"".format(val)
58
Werner Lewisf86c82e2022-10-19 13:50:10 +010059def bound_mpi(val: int, bits_in_limb: int) -> int:
60 """First number exceeding number of limbs needed for given input value."""
61 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010062
Werner Lewisf86c82e2022-10-19 13:50:10 +010063def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
64 """First number exceeding maximum of given number of limbs."""
65 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010066 return 1 << bits
67
Werner Lewisf86c82e2022-10-19 13:50:10 +010068def limbs_mpi(val: int, bits_in_limb: int) -> int:
69 """Return the number of limbs required to store value."""
70 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010071
72def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010073 """Return all pair combinations from input values."""
74 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010075
Janos Follath0cd89672022-11-09 12:14:14 +000076class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010077 """Common features for bignum binary operations.
78
79 This adds functionality common in binary operation tests.
80
81 Attributes:
82 symbol: Symbol to use for the operation in case description.
83 input_values: List of values to use as test case inputs. These are
84 combined to produce pairs of values.
85 input_cases: List of tuples containing pairs of test case inputs. This
86 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010087 unique_combinations_only: Boolean to select if test case combinations
88 must be unique. If True, only A,B or B,A would be included as a test
89 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000090 input_style: Controls the way how test data is passed to the functions
91 in the generated test cases. "variable" passes them as they are
92 defined in the python source. "arch_split" pads the values with
93 zeroes depending on the architecture/limb size. If this is set,
94 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000095 arity: the number of operands for the operation. Currently supported
96 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010097 """
98 symbol = ""
Janos Follathdac44e62022-11-20 11:58:12 +000099 input_values = INPUTS_DEFAULT # type: List[str]
Janos Follath98edf212022-11-19 12:48:17 +0000100 input_cases = [] # type: List[Any]
Janos Follathf4579762022-11-20 13:32:54 +0000101 unique_combinations_only = False
Janos Follatha36e4302022-11-19 15:55:53 +0000102 input_styles = ["variable", "fixed", "arch_split"] # type: List[str]
Janos Follath6fa3f062022-11-17 20:33:51 +0000103 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +0000104 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +0000105 arities = [1, 2]
106 arity = 2
Tom Cosgrove61292682022-12-08 09:44:10 +0000107 suffix = False # for arity = 1, symbol can be prefix (default) or suffix
Werner Lewis99e81782022-09-30 16:28:43 +0100108
Janos Follatha36e4302022-11-19 15:55:53 +0000109 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000110 self.val_a = val_a
111 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000112 # Setting the int versions here as opposed to making them @properties
113 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100114 self.int_a = hex_to_int(val_a)
115 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000116 if bits_in_limb not in self.limb_sizes:
117 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000118 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000119 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
120 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100121
Janos Follathb41ab922022-11-17 15:13:02 +0000122 @property
123 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000124 if self.arity == 1:
125 return self.int_a
126 elif self.arity == 2:
127 return max(self.int_a, self.int_b)
128 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000129
130 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000131 def limb_boundary(self) -> int:
132 return bound_mpi(self.boundary, self.bits_in_limb)
133
134 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000135 def limbs(self) -> int:
136 return limbs_mpi(self.boundary, self.bits_in_limb)
137
138 @property
139 def hex_digits(self) -> int:
140 return 2 * (self.limbs * self.bits_in_limb // 8)
141
Janos Follath4c59d352022-11-18 16:05:46 +0000142 def format_arg(self, val) -> str:
143 if self.input_style not in self.input_styles:
144 raise ValueError("Unknown input style!")
145 if self.input_style == "variable":
146 return val
147 else:
148 return val.zfill(self.hex_digits)
149
150 def format_result(self, res) -> str:
151 res_str = '{:x}'.format(res)
152 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000153
154 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000155 def arg_a(self) -> str:
156 return self.format_arg(self.val_a)
157
158 @property
159 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000160 if self.arity == 1:
161 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000162 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000163
Werner Lewis99e81782022-09-30 16:28:43 +0100164 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000165 args = [quote_str(self.arg_a)]
166 if self.arity == 2:
167 args.append(quote_str(self.arg_b))
168 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100169
Janos Follath3aeb60a2022-11-09 13:24:46 +0000170 def description(self) -> str:
171 """Generate a description for the test case.
172
173 If not set, case_description uses the form A `symbol` B, where symbol
174 is used to represent the operation. Descriptions of each value are
175 generated to provide some context to the test case.
176 """
177 if not self.case_description:
Janos Follath8ae7a652022-11-19 15:05:19 +0000178 if self.arity == 1:
Tom Cosgrove61292682022-12-08 09:44:10 +0000179 format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}"
180 self.case_description = format_string.format(
Janos Follath8ae7a652022-11-19 15:05:19 +0000181 self.symbol, self.int_a
182 )
183 elif self.arity == 2:
184 self.case_description = "{:x} {} {:x}".format(
185 self.int_a, self.symbol, self.int_b
186 )
Janos Follath3aeb60a2022-11-09 13:24:46 +0000187 return super().description()
188
Janos Follath939621f2022-11-18 18:15:24 +0000189 @property
190 def is_valid(self) -> bool:
191 return True
192
Werner Lewis99e81782022-09-30 16:28:43 +0100193 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100194 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100195 """Get the result of the operation.
196
197 This could be calculated during initialization and stored as `_result`
198 and then returned, or calculated when the method is called.
199 """
200 raise NotImplementedError
201
202 @classmethod
203 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
204 """Generator to yield pairs of inputs.
205
206 Combinations are first generated from all input values, and then
207 specific cases provided.
208 """
Janos Follath284672c2022-11-19 14:55:43 +0000209 if cls.arity == 1:
210 yield from ((a, "0") for a in cls.input_values)
211 elif cls.arity == 2:
212 if cls.unique_combinations_only:
213 yield from combination_pairs(cls.input_values)
214 else:
215 yield from (
216 (a, b)
217 for a in cls.input_values
218 for b in cls.input_values
219 )
Werner Lewisbbf0a322022-10-04 10:07:13 +0100220 else:
Janos Follath284672c2022-11-19 14:55:43 +0000221 raise ValueError("Unsupported number of operands!")
Janos Follathf8b3b722022-11-03 14:46:18 +0000222
Janos Follath87df3732022-11-09 12:31:23 +0000223 @classmethod
224 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000225 if cls.input_style not in cls.input_styles:
226 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000227 if cls.arity not in cls.arities:
228 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000229 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000230 test_objects = (cls(a, b, bits_in_limb=bil)
231 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000232 for bil in cls.limb_sizes)
Janos Follath98edf212022-11-19 12:48:17 +0000233 special_cases = (cls(*args, bits_in_limb=bil) # type: ignore
234 for args in cls.input_cases
235 for bil in cls.limb_sizes)
Janos Follath939621f2022-11-18 18:15:24 +0000236 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000237 test_objects = (cls(a, b)
238 for a, b in cls.get_value_pairs())
Janos Follath98edf212022-11-19 12:48:17 +0000239 special_cases = (cls(*args) for args in cls.input_cases)
Janos Follath939621f2022-11-18 18:15:24 +0000240 yield from (valid_test_object.create_test_case()
241 for valid_test_object in filter(
242 lambda test_object: test_object.is_valid,
Janos Follath98edf212022-11-19 12:48:17 +0000243 chain(test_objects, special_cases)
244 )
245 )
246
Janos Follath87df3732022-11-09 12:31:23 +0000247
Janos Follath5b1dbb42022-11-17 13:32:43 +0000248class ModOperationCommon(OperationCommon):
249 #pylint: disable=abstract-method
250 """Target for bignum mod_raw test case generation."""
Janos Follathdac44e62022-11-20 11:58:12 +0000251 moduli = MODULI_DEFAULT # type: List[str]
Tom Cosgrove1133d232022-12-16 03:53:17 +0000252 mongtomgery_form_a = False
253 disallow_zero_a = False
Janos Follath5b1dbb42022-11-17 13:32:43 +0000254
Janos Follath155ad8c2022-11-17 14:42:40 +0000255 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
256 bits_in_limb: int = 64) -> None:
257 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000258 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000259 # Setting the int versions here as opposed to making them @properties
260 # provides earlier/more robust input validation.
261 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000262
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000263 def to_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000264 return (val * self.r) % self.int_n
265
Tom Cosgrove21d459d2022-12-06 12:36:00 +0000266 def from_montgomery(self, val: int) -> int:
Tom Cosgrovec2406002022-12-06 12:20:43 +0000267 return (val * self.r_inv) % self.int_n
268
Janos Follath5b1dbb42022-11-17 13:32:43 +0000269 @property
270 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000271 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000272
273 @property
Tom Cosgrove1133d232022-12-16 03:53:17 +0000274 def arg_a(self) -> str:
275 if self.mongtomgery_form_a:
276 value_a = self.to_montgomery(self.int_a)
277 else:
278 value_a = self.int_a
279 return self.format_arg('{:x}'.format(value_a))
280
281 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000282 def arg_n(self) -> str:
283 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000284
Janos Follatha36a3d32022-11-18 17:49:13 +0000285 def arguments(self) -> List[str]:
286 return [quote_str(self.arg_n)] + super().arguments()
287
Janos Follath5b1dbb42022-11-17 13:32:43 +0000288 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000289 def r(self) -> int: # pylint: disable=invalid-name
290 l = limbs_mpi(self.int_n, self.bits_in_limb)
291 return bound_mpi_limbs(l, self.bits_in_limb)
292
293 @property
294 def r_inv(self) -> int:
295 return invmod(self.r, self.int_n)
296
297 @property
298 def r2(self) -> int: # pylint: disable=invalid-name
299 return pow(self.r, 2)
300
Janos Follathc4fca5d2022-11-19 10:42:20 +0000301 @property
302 def is_valid(self) -> bool:
303 if self.int_a >= self.int_n:
304 return False
Tom Cosgrove1133d232022-12-16 03:53:17 +0000305 if self.disallow_zero_a and self.int_a == 0:
306 return False
Janos Follathc4fca5d2022-11-19 10:42:20 +0000307 if self.arity == 2 and self.int_b >= self.int_n:
308 return False
309 return True
310
Janos Follath8ae7a652022-11-19 15:05:19 +0000311 def description(self) -> str:
312 """Generate a description for the test case.
313
314 It uses the form A `symbol` B mod N, where symbol is used to represent
315 the operation.
316 """
317
318 if not self.case_description:
319 return super().description() + " mod {:x}".format(self.int_n)
320 return super().description()
321
Janos Follathc4fca5d2022-11-19 10:42:20 +0000322 @classmethod
Janos Follath435b3052022-11-19 14:18:02 +0000323 def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]:
324 if cls.arity == 1:
325 yield from ((n, a, "0") for a, n in cls.input_cases)
326 elif cls.arity == 2:
327 yield from ((n, a, b) for a, b, n in cls.input_cases)
328 else:
329 raise ValueError("Unsupported number of operands!")
330
331 @classmethod
Janos Follathc4fca5d2022-11-19 10:42:20 +0000332 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
333 if cls.input_style not in cls.input_styles:
334 raise ValueError("Unknown input style!")
335 if cls.arity not in cls.arities:
336 raise ValueError("Unsupported number of operands!")
337 if cls.input_style == "arch_split":
338 test_objects = (cls(n, a, b, bits_in_limb=bil)
339 for n in cls.moduli
340 for a, b in cls.get_value_pairs()
341 for bil in cls.limb_sizes)
Janos Follath435b3052022-11-19 14:18:02 +0000342 special_cases = (cls(*args, bits_in_limb=bil)
343 for args in cls.input_cases_args()
344 for bil in cls.limb_sizes)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000345 else:
346 test_objects = (cls(n, a, b)
347 for n in cls.moduli
348 for a, b in cls.get_value_pairs())
Janos Follath435b3052022-11-19 14:18:02 +0000349 special_cases = (cls(*args) for args in cls.input_cases_args())
Janos Follathc4fca5d2022-11-19 10:42:20 +0000350 yield from (valid_test_object.create_test_case()
351 for valid_test_object in filter(
352 lambda test_object: test_object.is_valid,
Janos Follath435b3052022-11-19 14:18:02 +0000353 chain(test_objects, special_cases)
Janos Follathc4fca5d2022-11-19 10:42:20 +0000354 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000355
Janos Follathf8b3b722022-11-03 14:46:18 +0000356# BEGIN MERGE SLOT 1
357
358# END MERGE SLOT 1
359
360# BEGIN MERGE SLOT 2
361
362# END MERGE SLOT 2
363
364# BEGIN MERGE SLOT 3
365
366# END MERGE SLOT 3
367
368# BEGIN MERGE SLOT 4
369
370# END MERGE SLOT 4
371
372# BEGIN MERGE SLOT 5
373
374# END MERGE SLOT 5
375
376# BEGIN MERGE SLOT 6
377
378# END MERGE SLOT 6
379
380# BEGIN MERGE SLOT 7
381
382# END MERGE SLOT 7
383
384# BEGIN MERGE SLOT 8
385
386# END MERGE SLOT 8
387
388# BEGIN MERGE SLOT 9
389
390# END MERGE SLOT 9
391
392# BEGIN MERGE SLOT 10
393
394# END MERGE SLOT 10