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