blob: 7ab788be0a3fd16990eefcdaaf3b94c4f63879c0 [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.
Werner Lewis99e81782022-09-30 16:28:43 +010083 """
84 symbol = ""
85 input_values = [] # type: List[str]
86 input_cases = [] # type: List[Tuple[str, str]]
Werner Lewisbbf0a322022-10-04 10:07:13 +010087 unique_combinations_only = True
Werner Lewis99e81782022-09-30 16:28:43 +010088
89 def __init__(self, val_a: str, val_b: str) -> None:
90 self.arg_a = val_a
91 self.arg_b = val_b
92 self.int_a = hex_to_int(val_a)
93 self.int_b = hex_to_int(val_b)
94
95 def arguments(self) -> List[str]:
Werner Lewis1b20e7e2022-10-12 14:53:17 +010096 return [
97 quote_str(self.arg_a), quote_str(self.arg_b)
98 ] + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +010099
Janos Follath3aeb60a2022-11-09 13:24:46 +0000100 def description(self) -> str:
101 """Generate a description for the test case.
102
103 If not set, case_description uses the form A `symbol` B, where symbol
104 is used to represent the operation. Descriptions of each value are
105 generated to provide some context to the test case.
106 """
107 if not self.case_description:
108 self.case_description = "{:x} {} {:x}".format(
109 self.int_a, self.symbol, self.int_b
110 )
111 return super().description()
112
Werner Lewis99e81782022-09-30 16:28:43 +0100113 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100114 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100115 """Get the result of the operation.
116
117 This could be calculated during initialization and stored as `_result`
118 and then returned, or calculated when the method is called.
119 """
120 raise NotImplementedError
121
122 @classmethod
123 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
124 """Generator to yield pairs of inputs.
125
126 Combinations are first generated from all input values, and then
127 specific cases provided.
128 """
Werner Lewisbbf0a322022-10-04 10:07:13 +0100129 if cls.unique_combinations_only:
130 yield from combination_pairs(cls.input_values)
131 else:
132 yield from (
133 (a, b)
134 for a in cls.input_values
135 for b in cls.input_values
136 )
Werner Lewis99e81782022-09-30 16:28:43 +0100137 yield from cls.input_cases
Janos Follathf8b3b722022-11-03 14:46:18 +0000138
Janos Follath87df3732022-11-09 12:31:23 +0000139 @classmethod
140 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
141 for a_value, b_value in cls.get_value_pairs():
142 yield cls(a_value, b_value).create_test_case()
143
Janos Follath3aeb60a2022-11-09 13:24:46 +0000144
145class OperationCommonArchSplit(OperationCommon):
146 #pylint: disable=abstract-method
147 """Common features for operations where the result depends on
148 the limb size."""
149
150 def __init__(self, val_a: str, val_b: str, bits_in_limb: int) -> None:
151 super().__init__(val_a, val_b)
152 bound_val = max(self.int_a, self.int_b)
153 self.bits_in_limb = bits_in_limb
154 self.bound = bound_mpi(bound_val, self.bits_in_limb)
155 limbs = limbs_mpi(bound_val, self.bits_in_limb)
156 byte_len = limbs * self.bits_in_limb // 8
157 self.hex_digits = 2 * byte_len
158 if self.bits_in_limb == 32:
159 self.dependencies = ["MBEDTLS_HAVE_INT32"]
160 elif self.bits_in_limb == 64:
161 self.dependencies = ["MBEDTLS_HAVE_INT64"]
162 else:
163 raise ValueError("Invalid number of bits in limb!")
164 self.arg_a = self.arg_a.zfill(self.hex_digits)
165 self.arg_b = self.arg_b.zfill(self.hex_digits)
166
167 def pad_to_limbs(self, val) -> str:
168 return "{:x}".format(val).zfill(self.hex_digits)
169
170 @classmethod
171 def generate_function_tests(cls) -> Iterator[test_case.TestCase]:
172 for a_value, b_value in cls.get_value_pairs():
173 yield cls(a_value, b_value, 32).create_test_case()
174 yield cls(a_value, b_value, 64).create_test_case()
175
176
Janos Follathf8b3b722022-11-03 14:46:18 +0000177# BEGIN MERGE SLOT 1
178
179# END MERGE SLOT 1
180
181# BEGIN MERGE SLOT 2
182
183# END MERGE SLOT 2
184
185# BEGIN MERGE SLOT 3
186
187# END MERGE SLOT 3
188
189# BEGIN MERGE SLOT 4
190
191# END MERGE SLOT 4
192
193# BEGIN MERGE SLOT 5
194
195# END MERGE SLOT 5
196
197# BEGIN MERGE SLOT 6
198
199# END MERGE SLOT 6
200
201# BEGIN MERGE SLOT 7
202
203# END MERGE SLOT 7
204
205# BEGIN MERGE SLOT 8
206
207# END MERGE SLOT 8
208
209# BEGIN MERGE SLOT 9
210
211# END MERGE SLOT 9
212
213# BEGIN MERGE SLOT 10
214
215# END MERGE SLOT 10