Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 1 | """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 Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 17 | from abc import abstractmethod |
Gilles Peskine | 7a708fd | 2022-12-20 19:19:18 +0100 | [diff] [blame] | 18 | import enum |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 19 | from typing import Iterator, List, Tuple, TypeVar, Any |
Minos Galanakis | 0a325b6 | 2023-04-06 16:33:10 +0100 | [diff] [blame] | 20 | from copy import deepcopy |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 21 | from itertools import chain |
Minos Galanakis | 80c4ae8 | 2023-06-27 16:34:59 +0100 | [diff] [blame] | 22 | from math import ceil |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 23 | |
Janos Follath | 87df373 | 2022-11-09 12:31:23 +0000 | [diff] [blame] | 24 | from . import test_case |
Janos Follath | 0cd8967 | 2022-11-09 12:14:14 +0000 | [diff] [blame] | 25 | from . import test_data_generation |
Janos Follath | dac44e6 | 2022-11-20 11:58:12 +0000 | [diff] [blame] | 26 | from .bignum_data import INPUTS_DEFAULT, MODULI_DEFAULT |
Janos Follath | 0cd8967 | 2022-11-09 12:14:14 +0000 | [diff] [blame] | 27 | |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 28 | T = TypeVar('T') #pylint: disable=invalid-name |
| 29 | |
Werner Lewis | a850312 | 2022-10-04 10:10:40 +0100 | [diff] [blame] | 30 | def invmod(a: int, n: int) -> int: |
| 31 | """Return inverse of a to modulo n. |
| 32 | |
| 33 | Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent |
| 34 | to long_invmod() in CPython. |
| 35 | """ |
| 36 | b, c = 1, 0 |
| 37 | while n: |
| 38 | q, r = divmod(a, n) |
| 39 | a, b, c, n = n, c, b - q*c, r |
| 40 | # at this point a is the gcd of the original inputs |
| 41 | if a == 1: |
| 42 | return b |
| 43 | raise ValueError("Not invertible") |
| 44 | |
Tom Cosgrove | 1133d23 | 2022-12-16 03:53:17 +0000 | [diff] [blame] | 45 | def invmod_positive(a: int, n: int) -> int: |
| 46 | """Return a non-negative inverse of a to modulo n.""" |
| 47 | inv = invmod(a, n) |
| 48 | return inv if inv >= 0 else inv + n |
| 49 | |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 50 | def hex_to_int(val: str) -> int: |
Gilles Peskine | 35af021 | 2022-11-15 20:43:33 +0100 | [diff] [blame] | 51 | """Implement the syntax accepted by mbedtls_test_read_mpi(). |
| 52 | |
| 53 | This is a superset of what is accepted by mbedtls_test_read_mpi_core(). |
| 54 | """ |
Gilles Peskine | b9b9026 | 2022-11-10 09:15:21 +0100 | [diff] [blame] | 55 | if val in ['', '-']: |
Gilles Peskine | 35af021 | 2022-11-15 20:43:33 +0100 | [diff] [blame] | 56 | return 0 |
| 57 | return int(val, 16) |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 58 | |
Gilles Peskine | f8a4463 | 2022-12-20 19:12:22 +0100 | [diff] [blame] | 59 | def quote_str(val: str) -> str: |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 60 | return "\"{}\"".format(val) |
| 61 | |
Werner Lewis | f86c82e | 2022-10-19 13:50:10 +0100 | [diff] [blame] | 62 | def bound_mpi(val: int, bits_in_limb: int) -> int: |
| 63 | """First number exceeding number of limbs needed for given input value.""" |
| 64 | return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb) |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 65 | |
Werner Lewis | f86c82e | 2022-10-19 13:50:10 +0100 | [diff] [blame] | 66 | def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int: |
| 67 | """First number exceeding maximum of given number of limbs.""" |
| 68 | bits = bits_in_limb * limbs |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 69 | return 1 << bits |
| 70 | |
Werner Lewis | f86c82e | 2022-10-19 13:50:10 +0100 | [diff] [blame] | 71 | def limbs_mpi(val: int, bits_in_limb: int) -> int: |
| 72 | """Return the number of limbs required to store value.""" |
Gabor Mezei | 5ded38e | 2023-03-31 16:03:14 +0200 | [diff] [blame] | 73 | bit_length = max(val.bit_length(), 1) |
| 74 | return (bit_length + bits_in_limb - 1) // bits_in_limb |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 75 | |
| 76 | def combination_pairs(values: List[T]) -> List[Tuple[T, T]]: |
Gilles Peskine | 4cbbfd8 | 2022-11-09 21:57:52 +0100 | [diff] [blame] | 77 | """Return all pair combinations from input values.""" |
| 78 | return [(x, y) for x in values for y in values] |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 79 | |
Minos Galanakis | 80c4ae8 | 2023-06-27 16:34:59 +0100 | [diff] [blame] | 80 | def bits_to_limbs(bits: int, bits_in_limb: int) -> int: |
| 81 | """ Return the appropriate ammount of limbs needed to store |
| 82 | a number contained in input bits""" |
| 83 | return ceil(bits / bits_in_limb) |
| 84 | |
Gabor Mezei | 7c8d706 | 2023-02-14 18:25:23 +0100 | [diff] [blame] | 85 | def hex_digits_for_limb(limbs: int, bits_in_limb: int) -> int: |
Minos Galanakis | 80c4ae8 | 2023-06-27 16:34:59 +0100 | [diff] [blame] | 86 | """ Return the hex digits need for a number of limbs. """ |
| 87 | return 2 * ((limbs * bits_in_limb) // 8) |
Gabor Mezei | 7c8d706 | 2023-02-14 18:25:23 +0100 | [diff] [blame] | 88 | |
Minos Galanakis | c787cf7 | 2023-04-25 12:13:25 +0100 | [diff] [blame] | 89 | def hex_digits_max_int(val: str, bits_in_limb: int) -> int: |
| 90 | """ Return the first number exceeding maximum the limb space |
| 91 | required to store the input hex-string value. This method |
| 92 | weights on the input str_len rather than numerical value |
| 93 | and works with zero-padded inputs""" |
| 94 | n = ((1 << (len(val) * 4)) - 1) |
| 95 | l = limbs_mpi(n, bits_in_limb) |
| 96 | return bound_mpi_limbs(l, bits_in_limb) |
| 97 | |
| 98 | def zfill_match(reference: str, target: str) -> str: |
Minos Galanakis | 013167e | 2023-05-11 10:54:44 +0100 | [diff] [blame] | 99 | """ Zero pad target hex-string to match the limb size of |
| 100 | the reference input """ |
Minos Galanakis | c787cf7 | 2023-04-25 12:13:25 +0100 | [diff] [blame] | 101 | lt = len(target) |
| 102 | lr = len(reference) |
Minos Galanakis | 013167e | 2023-05-11 10:54:44 +0100 | [diff] [blame] | 103 | target_len = lr if lt < lr else lt |
| 104 | return "{:x}".format(int(target, 16)).zfill(target_len) |
Minos Galanakis | c787cf7 | 2023-04-25 12:13:25 +0100 | [diff] [blame] | 105 | |
Janos Follath | 0cd8967 | 2022-11-09 12:14:14 +0000 | [diff] [blame] | 106 | class OperationCommon(test_data_generation.BaseTest): |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 107 | """Common features for bignum binary operations. |
| 108 | |
| 109 | This adds functionality common in binary operation tests. |
| 110 | |
| 111 | Attributes: |
| 112 | symbol: Symbol to use for the operation in case description. |
| 113 | input_values: List of values to use as test case inputs. These are |
| 114 | combined to produce pairs of values. |
| 115 | input_cases: List of tuples containing pairs of test case inputs. This |
| 116 | can be used to implement specific pairs of inputs. |
Werner Lewis | bbf0a32 | 2022-10-04 10:07:13 +0100 | [diff] [blame] | 117 | unique_combinations_only: Boolean to select if test case combinations |
| 118 | must be unique. If True, only A,B or B,A would be included as a test |
| 119 | case. If False, both A,B and B,A would be included. |
Janos Follath | 6fa3f06 | 2022-11-17 20:33:51 +0000 | [diff] [blame] | 120 | input_style: Controls the way how test data is passed to the functions |
| 121 | in the generated test cases. "variable" passes them as they are |
| 122 | defined in the python source. "arch_split" pads the values with |
| 123 | zeroes depending on the architecture/limb size. If this is set, |
| 124 | test cases are generated for all architectures. |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 125 | arity: the number of operands for the operation. Currently supported |
| 126 | values are 1 and 2. |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 127 | """ |
| 128 | symbol = "" |
Janos Follath | dac44e6 | 2022-11-20 11:58:12 +0000 | [diff] [blame] | 129 | input_values = INPUTS_DEFAULT # type: List[str] |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 130 | input_cases = [] # type: List[Any] |
Minos Galanakis | 0a325b6 | 2023-04-06 16:33:10 +0100 | [diff] [blame] | 131 | dependencies = [] # type: List[Any] |
Janos Follath | f457976 | 2022-11-20 13:32:54 +0000 | [diff] [blame] | 132 | unique_combinations_only = False |
Janos Follath | a36e430 | 2022-11-19 15:55:53 +0000 | [diff] [blame] | 133 | input_styles = ["variable", "fixed", "arch_split"] # type: List[str] |
Janos Follath | 6fa3f06 | 2022-11-17 20:33:51 +0000 | [diff] [blame] | 134 | input_style = "variable" # type: str |
Janos Follath | 155ad8c | 2022-11-17 14:42:40 +0000 | [diff] [blame] | 135 | limb_sizes = [32, 64] # type: List[int] |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 136 | arities = [1, 2] |
| 137 | arity = 2 |
Tom Cosgrove | 6129268 | 2022-12-08 09:44:10 +0000 | [diff] [blame] | 138 | suffix = False # for arity = 1, symbol can be prefix (default) or suffix |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 139 | |
Janos Follath | a36e430 | 2022-11-19 15:55:53 +0000 | [diff] [blame] | 140 | def __init__(self, val_a: str, val_b: str = "0", bits_in_limb: int = 32) -> None: |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 141 | self.val_a = val_a |
| 142 | self.val_b = val_b |
Janos Follath | abfca8f | 2022-11-18 16:48:45 +0000 | [diff] [blame] | 143 | # Setting the int versions here as opposed to making them @properties |
| 144 | # provides earlier/more robust input validation. |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 145 | self.int_a = hex_to_int(val_a) |
| 146 | self.int_b = hex_to_int(val_b) |
Minos Galanakis | 0a325b6 | 2023-04-06 16:33:10 +0100 | [diff] [blame] | 147 | self.dependencies = deepcopy(self.dependencies) |
Janos Follath | 155ad8c | 2022-11-17 14:42:40 +0000 | [diff] [blame] | 148 | if bits_in_limb not in self.limb_sizes: |
| 149 | raise ValueError("Invalid number of bits in limb!") |
Janos Follath | 6fa3f06 | 2022-11-17 20:33:51 +0000 | [diff] [blame] | 150 | if self.input_style == "arch_split": |
Minos Galanakis | 0a325b6 | 2023-04-06 16:33:10 +0100 | [diff] [blame] | 151 | self.dependencies.append("MBEDTLS_HAVE_INT{:d}".format(bits_in_limb)) |
Janos Follath | 155ad8c | 2022-11-17 14:42:40 +0000 | [diff] [blame] | 152 | self.bits_in_limb = bits_in_limb |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 153 | |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 154 | @property |
| 155 | def boundary(self) -> int: |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 156 | if self.arity == 1: |
| 157 | return self.int_a |
| 158 | elif self.arity == 2: |
| 159 | return max(self.int_a, self.int_b) |
| 160 | raise ValueError("Unsupported number of operands!") |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 161 | |
| 162 | @property |
Janos Follath | 6fa3f06 | 2022-11-17 20:33:51 +0000 | [diff] [blame] | 163 | def limb_boundary(self) -> int: |
| 164 | return bound_mpi(self.boundary, self.bits_in_limb) |
| 165 | |
| 166 | @property |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 167 | def limbs(self) -> int: |
| 168 | return limbs_mpi(self.boundary, self.bits_in_limb) |
| 169 | |
| 170 | @property |
| 171 | def hex_digits(self) -> int: |
Gabor Mezei | 7c8d706 | 2023-02-14 18:25:23 +0100 | [diff] [blame] | 172 | return hex_digits_for_limb(self.limbs, self.bits_in_limb) |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 173 | |
Gilles Peskine | f8a4463 | 2022-12-20 19:12:22 +0100 | [diff] [blame] | 174 | def format_arg(self, val: str) -> str: |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 175 | if self.input_style not in self.input_styles: |
| 176 | raise ValueError("Unknown input style!") |
| 177 | if self.input_style == "variable": |
| 178 | return val |
| 179 | else: |
| 180 | return val.zfill(self.hex_digits) |
| 181 | |
Gilles Peskine | f8a4463 | 2022-12-20 19:12:22 +0100 | [diff] [blame] | 182 | def format_result(self, res: int) -> str: |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 183 | res_str = '{:x}'.format(res) |
| 184 | return quote_str(self.format_arg(res_str)) |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 185 | |
| 186 | @property |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 187 | def arg_a(self) -> str: |
| 188 | return self.format_arg(self.val_a) |
| 189 | |
| 190 | @property |
| 191 | def arg_b(self) -> str: |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 192 | if self.arity == 1: |
| 193 | raise AttributeError("Operation is unary and doesn't have arg_b!") |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 194 | return self.format_arg(self.val_b) |
Janos Follath | b41ab92 | 2022-11-17 15:13:02 +0000 | [diff] [blame] | 195 | |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 196 | def arguments(self) -> List[str]: |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 197 | args = [quote_str(self.arg_a)] |
| 198 | if self.arity == 2: |
| 199 | args.append(quote_str(self.arg_b)) |
| 200 | return args + self.result() |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 201 | |
Janos Follath | 3aeb60a | 2022-11-09 13:24:46 +0000 | [diff] [blame] | 202 | def description(self) -> str: |
| 203 | """Generate a description for the test case. |
| 204 | |
| 205 | If not set, case_description uses the form A `symbol` B, where symbol |
| 206 | is used to represent the operation. Descriptions of each value are |
| 207 | generated to provide some context to the test case. |
| 208 | """ |
| 209 | if not self.case_description: |
Janos Follath | 8ae7a65 | 2022-11-19 15:05:19 +0000 | [diff] [blame] | 210 | if self.arity == 1: |
Tom Cosgrove | 6129268 | 2022-12-08 09:44:10 +0000 | [diff] [blame] | 211 | format_string = "{1:x} {0}" if self.suffix else "{0} {1:x}" |
| 212 | self.case_description = format_string.format( |
Janos Follath | 8ae7a65 | 2022-11-19 15:05:19 +0000 | [diff] [blame] | 213 | self.symbol, self.int_a |
| 214 | ) |
| 215 | elif self.arity == 2: |
| 216 | self.case_description = "{:x} {} {:x}".format( |
| 217 | self.int_a, self.symbol, self.int_b |
| 218 | ) |
Janos Follath | 3aeb60a | 2022-11-09 13:24:46 +0000 | [diff] [blame] | 219 | return super().description() |
| 220 | |
Janos Follath | 939621f | 2022-11-18 18:15:24 +0000 | [diff] [blame] | 221 | @property |
| 222 | def is_valid(self) -> bool: |
| 223 | return True |
| 224 | |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 225 | @abstractmethod |
Werner Lewis | 1b20e7e | 2022-10-12 14:53:17 +0100 | [diff] [blame] | 226 | def result(self) -> List[str]: |
Werner Lewis | 99e8178 | 2022-09-30 16:28:43 +0100 | [diff] [blame] | 227 | """Get the result of the operation. |
| 228 | |
| 229 | This could be calculated during initialization and stored as `_result` |
| 230 | and then returned, or calculated when the method is called. |
| 231 | """ |
| 232 | raise NotImplementedError |
| 233 | |
| 234 | @classmethod |
| 235 | def get_value_pairs(cls) -> Iterator[Tuple[str, str]]: |
| 236 | """Generator to yield pairs of inputs. |
| 237 | |
| 238 | Combinations are first generated from all input values, and then |
| 239 | specific cases provided. |
| 240 | """ |
Janos Follath | 284672c | 2022-11-19 14:55:43 +0000 | [diff] [blame] | 241 | if cls.arity == 1: |
| 242 | yield from ((a, "0") for a in cls.input_values) |
| 243 | elif cls.arity == 2: |
| 244 | if cls.unique_combinations_only: |
| 245 | yield from combination_pairs(cls.input_values) |
| 246 | else: |
| 247 | yield from ( |
| 248 | (a, b) |
| 249 | for a in cls.input_values |
| 250 | for b in cls.input_values |
| 251 | ) |
Werner Lewis | bbf0a32 | 2022-10-04 10:07:13 +0100 | [diff] [blame] | 252 | else: |
Janos Follath | 284672c | 2022-11-19 14:55:43 +0000 | [diff] [blame] | 253 | raise ValueError("Unsupported number of operands!") |
Janos Follath | f8b3b72 | 2022-11-03 14:46:18 +0000 | [diff] [blame] | 254 | |
Janos Follath | 87df373 | 2022-11-09 12:31:23 +0000 | [diff] [blame] | 255 | @classmethod |
| 256 | def generate_function_tests(cls) -> Iterator[test_case.TestCase]: |
Janos Follath | 6fa3f06 | 2022-11-17 20:33:51 +0000 | [diff] [blame] | 257 | if cls.input_style not in cls.input_styles: |
| 258 | raise ValueError("Unknown input style!") |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 259 | if cls.arity not in cls.arities: |
| 260 | raise ValueError("Unsupported number of operands!") |
Janos Follath | 939621f | 2022-11-18 18:15:24 +0000 | [diff] [blame] | 261 | if cls.input_style == "arch_split": |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 262 | test_objects = (cls(a, b, bits_in_limb=bil) |
| 263 | for a, b in cls.get_value_pairs() |
Janos Follath | 939621f | 2022-11-18 18:15:24 +0000 | [diff] [blame] | 264 | for bil in cls.limb_sizes) |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 265 | special_cases = (cls(*args, bits_in_limb=bil) # type: ignore |
| 266 | for args in cls.input_cases |
| 267 | for bil in cls.limb_sizes) |
Janos Follath | 939621f | 2022-11-18 18:15:24 +0000 | [diff] [blame] | 268 | else: |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 269 | test_objects = (cls(a, b) |
| 270 | for a, b in cls.get_value_pairs()) |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 271 | special_cases = (cls(*args) for args in cls.input_cases) |
Janos Follath | 939621f | 2022-11-18 18:15:24 +0000 | [diff] [blame] | 272 | yield from (valid_test_object.create_test_case() |
| 273 | for valid_test_object in filter( |
| 274 | lambda test_object: test_object.is_valid, |
Janos Follath | 98edf21 | 2022-11-19 12:48:17 +0000 | [diff] [blame] | 275 | chain(test_objects, special_cases) |
| 276 | ) |
| 277 | ) |
| 278 | |
Janos Follath | 87df373 | 2022-11-09 12:31:23 +0000 | [diff] [blame] | 279 | |
Gilles Peskine | 7a708fd | 2022-12-20 19:19:18 +0100 | [diff] [blame] | 280 | class ModulusRepresentation(enum.Enum): |
| 281 | """Representation selector of a modulus.""" |
| 282 | # Numerical values aligned with the type mbedtls_mpi_mod_rep_selector |
| 283 | INVALID = 0 |
| 284 | MONTGOMERY = 2 |
| 285 | OPT_RED = 3 |
| 286 | |
| 287 | def symbol(self) -> str: |
| 288 | """The C symbol for this representation selector.""" |
| 289 | return 'MBEDTLS_MPI_MOD_REP_' + self.name |
| 290 | |
| 291 | @classmethod |
| 292 | def supported_representations(cls) -> List['ModulusRepresentation']: |
| 293 | """Return all representations that are supported in positive test cases.""" |
| 294 | return [cls.MONTGOMERY, cls.OPT_RED] |
| 295 | |
| 296 | |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 297 | class ModOperationCommon(OperationCommon): |
| 298 | #pylint: disable=abstract-method |
| 299 | """Target for bignum mod_raw test case generation.""" |
Janos Follath | dac44e6 | 2022-11-20 11:58:12 +0000 | [diff] [blame] | 300 | moduli = MODULI_DEFAULT # type: List[str] |
Tom Cosgrove | f723754 | 2022-12-16 16:10:36 +0000 | [diff] [blame] | 301 | montgomery_form_a = False |
Tom Cosgrove | 1133d23 | 2022-12-16 03:53:17 +0000 | [diff] [blame] | 302 | disallow_zero_a = False |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 303 | |
Janos Follath | 155ad8c | 2022-11-17 14:42:40 +0000 | [diff] [blame] | 304 | def __init__(self, val_n: str, val_a: str, val_b: str = "0", |
| 305 | bits_in_limb: int = 64) -> None: |
| 306 | super().__init__(val_a=val_a, val_b=val_b, bits_in_limb=bits_in_limb) |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 307 | self.val_n = val_n |
Janos Follath | abfca8f | 2022-11-18 16:48:45 +0000 | [diff] [blame] | 308 | # Setting the int versions here as opposed to making them @properties |
| 309 | # provides earlier/more robust input validation. |
| 310 | self.int_n = hex_to_int(val_n) |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 311 | |
Tom Cosgrove | 21d459d | 2022-12-06 12:36:00 +0000 | [diff] [blame] | 312 | def to_montgomery(self, val: int) -> int: |
Tom Cosgrove | c240600 | 2022-12-06 12:20:43 +0000 | [diff] [blame] | 313 | return (val * self.r) % self.int_n |
| 314 | |
Tom Cosgrove | 21d459d | 2022-12-06 12:36:00 +0000 | [diff] [blame] | 315 | def from_montgomery(self, val: int) -> int: |
Tom Cosgrove | c240600 | 2022-12-06 12:20:43 +0000 | [diff] [blame] | 316 | return (val * self.r_inv) % self.int_n |
| 317 | |
Gilles Peskine | 7a708fd | 2022-12-20 19:19:18 +0100 | [diff] [blame] | 318 | def convert_from_canonical(self, canonical: int, |
| 319 | rep: ModulusRepresentation) -> int: |
| 320 | """Convert values from canonical representation to the given representation.""" |
| 321 | if rep is ModulusRepresentation.MONTGOMERY: |
| 322 | return self.to_montgomery(canonical) |
| 323 | elif rep is ModulusRepresentation.OPT_RED: |
| 324 | return canonical |
| 325 | else: |
| 326 | raise ValueError('Modulus representation not supported: {}' |
| 327 | .format(rep.name)) |
| 328 | |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 329 | @property |
| 330 | def boundary(self) -> int: |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 331 | return self.int_n |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 332 | |
| 333 | @property |
Tom Cosgrove | 1133d23 | 2022-12-16 03:53:17 +0000 | [diff] [blame] | 334 | def arg_a(self) -> str: |
Tom Cosgrove | f723754 | 2022-12-16 16:10:36 +0000 | [diff] [blame] | 335 | if self.montgomery_form_a: |
Tom Cosgrove | 1133d23 | 2022-12-16 03:53:17 +0000 | [diff] [blame] | 336 | value_a = self.to_montgomery(self.int_a) |
| 337 | else: |
| 338 | value_a = self.int_a |
| 339 | return self.format_arg('{:x}'.format(value_a)) |
| 340 | |
| 341 | @property |
Janos Follath | 4c59d35 | 2022-11-18 16:05:46 +0000 | [diff] [blame] | 342 | def arg_n(self) -> str: |
| 343 | return self.format_arg(self.val_n) |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 344 | |
Gilles Peskine | 5623ecc | 2022-12-20 19:16:54 +0100 | [diff] [blame] | 345 | def format_arg(self, val: str) -> str: |
Minos Galanakis | 3d2aab8 | 2022-12-21 17:30:10 +0000 | [diff] [blame] | 346 | return super().format_arg(val).zfill(self.hex_digits) |
Gilles Peskine | 5623ecc | 2022-12-20 19:16:54 +0100 | [diff] [blame] | 347 | |
Janos Follath | a36a3d3 | 2022-11-18 17:49:13 +0000 | [diff] [blame] | 348 | def arguments(self) -> List[str]: |
| 349 | return [quote_str(self.arg_n)] + super().arguments() |
| 350 | |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 351 | @property |
Janos Follath | 5b1dbb4 | 2022-11-17 13:32:43 +0000 | [diff] [blame] | 352 | def r(self) -> int: # pylint: disable=invalid-name |
| 353 | l = limbs_mpi(self.int_n, self.bits_in_limb) |
| 354 | return bound_mpi_limbs(l, self.bits_in_limb) |
| 355 | |
| 356 | @property |
| 357 | def r_inv(self) -> int: |
| 358 | return invmod(self.r, self.int_n) |
| 359 | |
| 360 | @property |
| 361 | def r2(self) -> int: # pylint: disable=invalid-name |
| 362 | return pow(self.r, 2) |
| 363 | |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 364 | @property |
| 365 | def is_valid(self) -> bool: |
| 366 | if self.int_a >= self.int_n: |
| 367 | return False |
Tom Cosgrove | 1133d23 | 2022-12-16 03:53:17 +0000 | [diff] [blame] | 368 | if self.disallow_zero_a and self.int_a == 0: |
| 369 | return False |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 370 | if self.arity == 2 and self.int_b >= self.int_n: |
| 371 | return False |
| 372 | return True |
| 373 | |
Janos Follath | 8ae7a65 | 2022-11-19 15:05:19 +0000 | [diff] [blame] | 374 | def description(self) -> str: |
| 375 | """Generate a description for the test case. |
| 376 | |
| 377 | It uses the form A `symbol` B mod N, where symbol is used to represent |
| 378 | the operation. |
| 379 | """ |
| 380 | |
| 381 | if not self.case_description: |
| 382 | return super().description() + " mod {:x}".format(self.int_n) |
| 383 | return super().description() |
| 384 | |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 385 | @classmethod |
Janos Follath | 435b305 | 2022-11-19 14:18:02 +0000 | [diff] [blame] | 386 | def input_cases_args(cls) -> Iterator[Tuple[Any, Any, Any]]: |
| 387 | if cls.arity == 1: |
| 388 | yield from ((n, a, "0") for a, n in cls.input_cases) |
| 389 | elif cls.arity == 2: |
| 390 | yield from ((n, a, b) for a, b, n in cls.input_cases) |
| 391 | else: |
| 392 | raise ValueError("Unsupported number of operands!") |
| 393 | |
| 394 | @classmethod |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 395 | def generate_function_tests(cls) -> Iterator[test_case.TestCase]: |
| 396 | if cls.input_style not in cls.input_styles: |
| 397 | raise ValueError("Unknown input style!") |
| 398 | if cls.arity not in cls.arities: |
| 399 | raise ValueError("Unsupported number of operands!") |
| 400 | if cls.input_style == "arch_split": |
| 401 | test_objects = (cls(n, a, b, bits_in_limb=bil) |
| 402 | for n in cls.moduli |
| 403 | for a, b in cls.get_value_pairs() |
| 404 | for bil in cls.limb_sizes) |
Janos Follath | 435b305 | 2022-11-19 14:18:02 +0000 | [diff] [blame] | 405 | special_cases = (cls(*args, bits_in_limb=bil) |
| 406 | for args in cls.input_cases_args() |
| 407 | for bil in cls.limb_sizes) |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 408 | else: |
| 409 | test_objects = (cls(n, a, b) |
| 410 | for n in cls.moduli |
| 411 | for a, b in cls.get_value_pairs()) |
Janos Follath | 435b305 | 2022-11-19 14:18:02 +0000 | [diff] [blame] | 412 | special_cases = (cls(*args) for args in cls.input_cases_args()) |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 413 | yield from (valid_test_object.create_test_case() |
| 414 | for valid_test_object in filter( |
| 415 | lambda test_object: test_object.is_valid, |
Janos Follath | 435b305 | 2022-11-19 14:18:02 +0000 | [diff] [blame] | 416 | chain(test_objects, special_cases) |
Janos Follath | c4fca5d | 2022-11-19 10:42:20 +0000 | [diff] [blame] | 417 | )) |