blob: 7d7170d170f532e972c3575fa109aa26e57462b4 [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
18from typing import Iterator, List, Tuple, TypeVar
19
Janos Follath87df3732022-11-09 12:31:23 +000020from . import test_case
Janos Follath0cd89672022-11-09 12:14:14 +000021from . import test_data_generation
22
Werner Lewis99e81782022-09-30 16:28:43 +010023T = TypeVar('T') #pylint: disable=invalid-name
24
Werner Lewisa8503122022-10-04 10:10:40 +010025def invmod(a: int, n: int) -> int:
26 """Return inverse of a to modulo n.
27
28 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
29 to long_invmod() in CPython.
30 """
31 b, c = 1, 0
32 while n:
33 q, r = divmod(a, n)
34 a, b, c, n = n, c, b - q*c, r
35 # at this point a is the gcd of the original inputs
36 if a == 1:
37 return b
38 raise ValueError("Not invertible")
39
Werner Lewis99e81782022-09-30 16:28:43 +010040def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010041 """Implement the syntax accepted by mbedtls_test_read_mpi().
42
43 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
44 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010045 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010046 return 0
47 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010048
49def quote_str(val) -> str:
50 return "\"{}\"".format(val)
51
Werner Lewisf86c82e2022-10-19 13:50:10 +010052def bound_mpi(val: int, bits_in_limb: int) -> int:
53 """First number exceeding number of limbs needed for given input value."""
54 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010055
Werner Lewisf86c82e2022-10-19 13:50:10 +010056def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
57 """First number exceeding maximum of given number of limbs."""
58 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010059 return 1 << bits
60
Werner Lewisf86c82e2022-10-19 13:50:10 +010061def limbs_mpi(val: int, bits_in_limb: int) -> int:
62 """Return the number of limbs required to store value."""
63 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010064
65def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010066 """Return all pair combinations from input values."""
67 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010068
Janos Follath0cd89672022-11-09 12:14:14 +000069class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010070 """Common features for bignum binary operations.
71
72 This adds functionality common in binary operation tests.
73
74 Attributes:
75 symbol: Symbol to use for the operation in case description.
76 input_values: List of values to use as test case inputs. These are
77 combined to produce pairs of values.
78 input_cases: List of tuples containing pairs of test case inputs. This
79 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010080 unique_combinations_only: Boolean to select if test case combinations
81 must be unique. If True, only A,B or B,A would be included as a test
82 case. If False, both A,B and B,A would be included.
Janos Follath6fa3f062022-11-17 20:33:51 +000083 input_style: Controls the way how test data is passed to the functions
84 in the generated test cases. "variable" passes them as they are
85 defined in the python source. "arch_split" pads the values with
86 zeroes depending on the architecture/limb size. If this is set,
87 test cases are generated for all architectures.
Janos Follatha36a3d32022-11-18 17:49:13 +000088 arity: the number of operands for the operation. Currently supported
89 values are 1 and 2.
Werner Lewis99e81782022-09-30 16:28:43 +010090 """
91 symbol = ""
92 input_values = [] # type: List[str]
93 input_cases = [] # type: List[Tuple[str, str]]
Werner Lewisbbf0a322022-10-04 10:07:13 +010094 unique_combinations_only = True
Janos Follath6fa3f062022-11-17 20:33:51 +000095 input_styles = ["variable", "arch_split"] # type: List[str]
96 input_style = "variable" # type: str
Janos Follath155ad8c2022-11-17 14:42:40 +000097 limb_sizes = [32, 64] # type: List[int]
Janos Follatha36a3d32022-11-18 17:49:13 +000098 arities = [1, 2]
99 arity = 2
Werner Lewis99e81782022-09-30 16:28:43 +0100100
Janos Follatha36a3d32022-11-18 17:49:13 +0000101 def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 64) -> None:
Janos Follath4c59d352022-11-18 16:05:46 +0000102 self.val_a = val_a
103 self.val_b = val_b
Janos Follathabfca8f2022-11-18 16:48:45 +0000104 # Setting the int versions here as opposed to making them @properties
105 # provides earlier/more robust input validation.
Werner Lewis99e81782022-09-30 16:28:43 +0100106 self.int_a = hex_to_int(val_a)
107 self.int_b = hex_to_int(val_b)
Janos Follath155ad8c2022-11-17 14:42:40 +0000108 if bits_in_limb not in self.limb_sizes:
109 raise ValueError("Invalid number of bits in limb!")
Janos Follath6fa3f062022-11-17 20:33:51 +0000110 if self.input_style == "arch_split":
Janos Follath155ad8c2022-11-17 14:42:40 +0000111 self.dependencies = ["MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)]
112 self.bits_in_limb = bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +0100113
Janos Follathb41ab922022-11-17 15:13:02 +0000114 @property
115 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000116 if self.arity == 1:
117 return self.int_a
118 elif self.arity == 2:
119 return max(self.int_a, self.int_b)
120 raise ValueError("Unsupported number of operands!")
Janos Follathb41ab922022-11-17 15:13:02 +0000121
122 @property
Janos Follath6fa3f062022-11-17 20:33:51 +0000123 def limb_boundary(self) -> int:
124 return bound_mpi(self.boundary, self.bits_in_limb)
125
126 @property
Janos Follathb41ab922022-11-17 15:13:02 +0000127 def limbs(self) -> int:
128 return limbs_mpi(self.boundary, self.bits_in_limb)
129
130 @property
131 def hex_digits(self) -> int:
132 return 2 * (self.limbs * self.bits_in_limb // 8)
133
Janos Follath4c59d352022-11-18 16:05:46 +0000134 def format_arg(self, val) -> str:
135 if self.input_style not in self.input_styles:
136 raise ValueError("Unknown input style!")
137 if self.input_style == "variable":
138 return val
139 else:
140 return val.zfill(self.hex_digits)
141
142 def format_result(self, res) -> str:
143 res_str = '{:x}'.format(res)
144 return quote_str(self.format_arg(res_str))
Janos Follathb41ab922022-11-17 15:13:02 +0000145
146 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000147 def arg_a(self) -> str:
148 return self.format_arg(self.val_a)
149
150 @property
151 def arg_b(self) -> str:
Janos Follatha36a3d32022-11-18 17:49:13 +0000152 if self.arity == 1:
153 raise AttributeError("Operation is unary and doesn't have arg_b!")
Janos Follath4c59d352022-11-18 16:05:46 +0000154 return self.format_arg(self.val_b)
Janos Follathb41ab922022-11-17 15:13:02 +0000155
Werner Lewis99e81782022-09-30 16:28:43 +0100156 def arguments(self) -> List[str]:
Janos Follatha36a3d32022-11-18 17:49:13 +0000157 args = [quote_str(self.arg_a)]
158 if self.arity == 2:
159 args.append(quote_str(self.arg_b))
160 return args + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100161
Janos Follath3aeb60a2022-11-09 13:24:46 +0000162 def description(self) -> str:
163 """Generate a description for the test case.
164
165 If not set, case_description uses the form A `symbol` B, where symbol
166 is used to represent the operation. Descriptions of each value are
167 generated to provide some context to the test case.
168 """
169 if not self.case_description:
170 self.case_description = "{:x} {} {:x}".format(
171 self.int_a, self.symbol, self.int_b
172 )
173 return super().description()
174
Janos Follath939621f2022-11-18 18:15:24 +0000175 @property
176 def is_valid(self) -> bool:
177 return True
178
Werner Lewis99e81782022-09-30 16:28:43 +0100179 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100180 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100181 """Get the result of the operation.
182
183 This could be calculated during initialization and stored as `_result`
184 and then returned, or calculated when the method is called.
185 """
186 raise NotImplementedError
187
188 @classmethod
189 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
190 """Generator to yield pairs of inputs.
191
192 Combinations are first generated from all input values, and then
193 specific cases provided.
194 """
Werner Lewisbbf0a322022-10-04 10:07:13 +0100195 if cls.unique_combinations_only:
196 yield from combination_pairs(cls.input_values)
197 else:
198 yield from (
199 (a, b)
200 for a in cls.input_values
201 for b in cls.input_values
202 )
Werner Lewis99e81782022-09-30 16:28:43 +0100203 yield from cls.input_cases
Janos Follathf8b3b722022-11-03 14:46:18 +0000204
Janos Follath87df3732022-11-09 12:31:23 +0000205 @classmethod
206 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
Janos Follath6fa3f062022-11-17 20:33:51 +0000207 if cls.input_style not in cls.input_styles:
208 raise ValueError("Unknown input style!")
Janos Follatha36a3d32022-11-18 17:49:13 +0000209 if cls.arity not in cls.arities:
210 raise ValueError("Unsupported number of operands!")
Janos Follath939621f2022-11-18 18:15:24 +0000211 if cls.input_style == "arch_split":
Janos Follathc4fca5d2022-11-19 10:42:20 +0000212 test_objects = (cls(a, b, bits_in_limb=bil)
213 for a, b in cls.get_value_pairs()
Janos Follath939621f2022-11-18 18:15:24 +0000214 for bil in cls.limb_sizes)
215 else:
Janos Follathc4fca5d2022-11-19 10:42:20 +0000216 test_objects = (cls(a, b)
217 for a, b in cls.get_value_pairs())
Janos Follath939621f2022-11-18 18:15:24 +0000218 yield from (valid_test_object.create_test_case()
219 for valid_test_object in filter(
220 lambda test_object: test_object.is_valid,
221 test_objects
222 ))
Janos Follath87df3732022-11-09 12:31:23 +0000223
Janos Follath3aeb60a2022-11-09 13:24:46 +0000224
Janos Follath5b1dbb42022-11-17 13:32:43 +0000225class ModOperationCommon(OperationCommon):
226 #pylint: disable=abstract-method
227 """Target for bignum mod_raw test case generation."""
Janos Follathc4fca5d2022-11-19 10:42:20 +0000228 moduli = [] # type: List[str]
Janos Follath5b1dbb42022-11-17 13:32:43 +0000229
Janos Follath155ad8c2022-11-17 14:42:40 +0000230 def __init__(self, val_n: str, val_a: str, val_b: str = "0",
231 bits_in_limb: int = 64) -> None:
232 super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000233 self.val_n = val_n
Janos Follathabfca8f2022-11-18 16:48:45 +0000234 # Setting the int versions here as opposed to making them @properties
235 # provides earlier/more robust input validation.
236 self.int_n = hex_to_int(val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000237
238 @property
239 def boundary(self) -> int:
Janos Follatha36a3d32022-11-18 17:49:13 +0000240 return self.int_n
Janos Follath5b1dbb42022-11-17 13:32:43 +0000241
242 @property
Janos Follath4c59d352022-11-18 16:05:46 +0000243 def arg_n(self) -> str:
244 return self.format_arg(self.val_n)
Janos Follath5b1dbb42022-11-17 13:32:43 +0000245
Janos Follatha36a3d32022-11-18 17:49:13 +0000246 def arguments(self) -> List[str]:
247 return [quote_str(self.arg_n)] + super().arguments()
248
Janos Follath5b1dbb42022-11-17 13:32:43 +0000249 @property
Janos Follath5b1dbb42022-11-17 13:32:43 +0000250 def r(self) -> int: # pylint: disable=invalid-name
251 l = limbs_mpi(self.int_n, self.bits_in_limb)
252 return bound_mpi_limbs(l, self.bits_in_limb)
253
254 @property
255 def r_inv(self) -> int:
256 return invmod(self.r, self.int_n)
257
258 @property
259 def r2(self) -> int: # pylint: disable=invalid-name
260 return pow(self.r, 2)
261
Janos Follathc4fca5d2022-11-19 10:42:20 +0000262 @property
263 def is_valid(self) -> bool:
264 if self.int_a >= self.int_n:
265 return False
266 if self.arity == 2 and self.int_b >= self.int_n:
267 return False
268 return True
269
270 @classmethod
271 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
272 if cls.input_style not in cls.input_styles:
273 raise ValueError("Unknown input style!")
274 if cls.arity not in cls.arities:
275 raise ValueError("Unsupported number of operands!")
276 if cls.input_style == "arch_split":
277 test_objects = (cls(n, a, b, bits_in_limb=bil)
278 for n in cls.moduli
279 for a, b in cls.get_value_pairs()
280 for bil in cls.limb_sizes)
281 else:
282 test_objects = (cls(n, a, b)
283 for n in cls.moduli
284 for a, b in cls.get_value_pairs())
285 yield from (valid_test_object.create_test_case()
286 for valid_test_object in filter(
287 lambda test_object: test_object.is_valid,
288 test_objects
289 ))
Janos Follath5b1dbb42022-11-17 13:32:43 +0000290
Janos Follathf8b3b722022-11-03 14:46:18 +0000291# BEGIN MERGE SLOT 1
292
293# END MERGE SLOT 1
294
295# BEGIN MERGE SLOT 2
296
297# END MERGE SLOT 2
298
299# BEGIN MERGE SLOT 3
300
301# END MERGE SLOT 3
302
303# BEGIN MERGE SLOT 4
304
305# END MERGE SLOT 4
306
307# BEGIN MERGE SLOT 5
308
309# END MERGE SLOT 5
310
311# BEGIN MERGE SLOT 6
312
313# END MERGE SLOT 6
314
315# BEGIN MERGE SLOT 7
316
317# END MERGE SLOT 7
318
319# BEGIN MERGE SLOT 8
320
321# END MERGE SLOT 8
322
323# BEGIN MERGE SLOT 9
324
325# END MERGE SLOT 9
326
327# BEGIN MERGE SLOT 10
328
329# END MERGE SLOT 10