blob: ba30be40ee772430f2fd16e55568d4984ee9eb76 [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 Follath0cd89672022-11-09 12:14:14 +000020from . import test_data_generation
21
Werner Lewis99e81782022-09-30 16:28:43 +010022T = TypeVar('T') #pylint: disable=invalid-name
23
Werner Lewisa8503122022-10-04 10:10:40 +010024def invmod(a: int, n: int) -> int:
25 """Return inverse of a to modulo n.
26
27 Equivalent to pow(a, -1, n) in Python 3.8+. Implementation is equivalent
28 to long_invmod() in CPython.
29 """
30 b, c = 1, 0
31 while n:
32 q, r = divmod(a, n)
33 a, b, c, n = n, c, b - q*c, r
34 # at this point a is the gcd of the original inputs
35 if a == 1:
36 return b
37 raise ValueError("Not invertible")
38
Werner Lewis99e81782022-09-30 16:28:43 +010039def hex_to_int(val: str) -> int:
Gilles Peskine35af0212022-11-15 20:43:33 +010040 """Implement the syntax accepted by mbedtls_test_read_mpi().
41
42 This is a superset of what is accepted by mbedtls_test_read_mpi_core().
43 """
Gilles Peskineb9b90262022-11-10 09:15:21 +010044 if val in ['', '-']:
Gilles Peskine35af0212022-11-15 20:43:33 +010045 return 0
46 return int(val, 16)
Werner Lewis99e81782022-09-30 16:28:43 +010047
48def quote_str(val) -> str:
49 return "\"{}\"".format(val)
50
Werner Lewisf86c82e2022-10-19 13:50:10 +010051def bound_mpi(val: int, bits_in_limb: int) -> int:
52 """First number exceeding number of limbs needed for given input value."""
53 return bound_mpi_limbs(limbs_mpi(val, bits_in_limb), bits_in_limb)
Werner Lewis99e81782022-09-30 16:28:43 +010054
Werner Lewisf86c82e2022-10-19 13:50:10 +010055def bound_mpi_limbs(limbs: int, bits_in_limb: int) -> int:
56 """First number exceeding maximum of given number of limbs."""
57 bits = bits_in_limb * limbs
Werner Lewis99e81782022-09-30 16:28:43 +010058 return 1 << bits
59
Werner Lewisf86c82e2022-10-19 13:50:10 +010060def limbs_mpi(val: int, bits_in_limb: int) -> int:
61 """Return the number of limbs required to store value."""
62 return (val.bit_length() + bits_in_limb - 1) // bits_in_limb
Werner Lewis99e81782022-09-30 16:28:43 +010063
64def combination_pairs(values: List[T]) -> List[Tuple[T, T]]:
Gilles Peskine4cbbfd82022-11-09 21:57:52 +010065 """Return all pair combinations from input values."""
66 return [(x, y) for x in values for y in values]
Werner Lewis99e81782022-09-30 16:28:43 +010067
Janos Follath0cd89672022-11-09 12:14:14 +000068class OperationCommon(test_data_generation.BaseTest):
Werner Lewis99e81782022-09-30 16:28:43 +010069 """Common features for bignum binary operations.
70
71 This adds functionality common in binary operation tests.
72
73 Attributes:
74 symbol: Symbol to use for the operation in case description.
75 input_values: List of values to use as test case inputs. These are
76 combined to produce pairs of values.
77 input_cases: List of tuples containing pairs of test case inputs. This
78 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010079 unique_combinations_only: Boolean to select if test case combinations
80 must be unique. If True, only A,B or B,A would be included as a test
81 case. If False, both A,B and B,A would be included.
Werner Lewis99e81782022-09-30 16:28:43 +010082 """
83 symbol = ""
84 input_values = [] # type: List[str]
85 input_cases = [] # type: List[Tuple[str, str]]
Werner Lewisbbf0a322022-10-04 10:07:13 +010086 unique_combinations_only = True
Werner Lewis99e81782022-09-30 16:28:43 +010087
88 def __init__(self, val_a: str, val_b: str) -> None:
89 self.arg_a = val_a
90 self.arg_b = val_b
91 self.int_a = hex_to_int(val_a)
92 self.int_b = hex_to_int(val_b)
93
94 def arguments(self) -> List[str]:
Werner Lewis1b20e7e2022-10-12 14:53:17 +010095 return [
96 quote_str(self.arg_a), quote_str(self.arg_b)
97 ] + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +010098
99 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100100 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100101 """Get the result of the operation.
102
103 This could be calculated during initialization and stored as `_result`
104 and then returned, or calculated when the method is called.
105 """
106 raise NotImplementedError
107
108 @classmethod
109 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
110 """Generator to yield pairs of inputs.
111
112 Combinations are first generated from all input values, and then
113 specific cases provided.
114 """
Werner Lewisbbf0a322022-10-04 10:07:13 +0100115 if cls.unique_combinations_only:
116 yield from combination_pairs(cls.input_values)
117 else:
118 yield from (
119 (a, b)
120 for a in cls.input_values
121 for b in cls.input_values
122 )
Werner Lewis99e81782022-09-30 16:28:43 +0100123 yield from cls.input_cases
Janos Follathf8b3b722022-11-03 14:46:18 +0000124
125# BEGIN MERGE SLOT 1
126
127# END MERGE SLOT 1
128
129# BEGIN MERGE SLOT 2
130
131# END MERGE SLOT 2
132
133# BEGIN MERGE SLOT 3
134
135# END MERGE SLOT 3
136
137# BEGIN MERGE SLOT 4
138
139# END MERGE SLOT 4
140
141# BEGIN MERGE SLOT 5
142
143# END MERGE SLOT 5
144
145# BEGIN MERGE SLOT 6
146
147# END MERGE SLOT 6
148
149# BEGIN MERGE SLOT 7
150
151# END MERGE SLOT 7
152
153# BEGIN MERGE SLOT 8
154
155# END MERGE SLOT 8
156
157# BEGIN MERGE SLOT 9
158
159# END MERGE SLOT 9
160
161# BEGIN MERGE SLOT 10
162
163# END MERGE SLOT 10