blob: 1eb4ca7dfbb5f6372cbdb49ae98e6a46fa9a5818 [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
17import itertools
18import typing
19
20from abc import abstractmethod
21from typing import Iterator, List, Tuple, TypeVar
22
23T = 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 """
45 if val == '' or val == '-':
46 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
69
70class OperationCommon:
71 """Common features for bignum binary operations.
72
73 This adds functionality common in binary operation tests.
74
75 Attributes:
76 symbol: Symbol to use for the operation in case description.
77 input_values: List of values to use as test case inputs. These are
78 combined to produce pairs of values.
79 input_cases: List of tuples containing pairs of test case inputs. This
80 can be used to implement specific pairs of inputs.
Werner Lewisbbf0a322022-10-04 10:07:13 +010081 unique_combinations_only: Boolean to select if test case combinations
82 must be unique. If True, only A,B or B,A would be included as a test
83 case. If False, both A,B and B,A would be included.
Werner Lewis99e81782022-09-30 16:28:43 +010084 """
85 symbol = ""
86 input_values = [] # type: List[str]
87 input_cases = [] # type: List[Tuple[str, str]]
Werner Lewisbbf0a322022-10-04 10:07:13 +010088 unique_combinations_only = True
Werner Lewis99e81782022-09-30 16:28:43 +010089
90 def __init__(self, val_a: str, val_b: str) -> None:
91 self.arg_a = val_a
92 self.arg_b = val_b
93 self.int_a = hex_to_int(val_a)
94 self.int_b = hex_to_int(val_b)
95
96 def arguments(self) -> List[str]:
Werner Lewis1b20e7e2022-10-12 14:53:17 +010097 return [
98 quote_str(self.arg_a), quote_str(self.arg_b)
99 ] + self.result()
Werner Lewis99e81782022-09-30 16:28:43 +0100100
101 @abstractmethod
Werner Lewis1b20e7e2022-10-12 14:53:17 +0100102 def result(self) -> List[str]:
Werner Lewis99e81782022-09-30 16:28:43 +0100103 """Get the result of the operation.
104
105 This could be calculated during initialization and stored as `_result`
106 and then returned, or calculated when the method is called.
107 """
108 raise NotImplementedError
109
110 @classmethod
111 def get_value_pairs(cls) -> Iterator[Tuple[str, str]]:
112 """Generator to yield pairs of inputs.
113
114 Combinations are first generated from all input values, and then
115 specific cases provided.
116 """
Werner Lewisbbf0a322022-10-04 10:07:13 +0100117 if cls.unique_combinations_only:
118 yield from combination_pairs(cls.input_values)
119 else:
120 yield from (
121 (a, b)
122 for a in cls.input_values
123 for b in cls.input_values
124 )
Werner Lewis99e81782022-09-30 16:28:43 +0100125 yield from cls.input_cases
Janos Follathf8b3b722022-11-03 14:46:18 +0000126
127# BEGIN MERGE SLOT 1
128
129# END MERGE SLOT 1
130
131# BEGIN MERGE SLOT 2
132
133# END MERGE SLOT 2
134
135# BEGIN MERGE SLOT 3
136
137# END MERGE SLOT 3
138
139# BEGIN MERGE SLOT 4
140
141# END MERGE SLOT 4
142
143# BEGIN MERGE SLOT 5
144
145# END MERGE SLOT 5
146
147# BEGIN MERGE SLOT 6
148
149# END MERGE SLOT 6
150
151# BEGIN MERGE SLOT 7
152
153# END MERGE SLOT 7
154
155# BEGIN MERGE SLOT 8
156
157# END MERGE SLOT 8
158
159# BEGIN MERGE SLOT 9
160
161# END MERGE SLOT 9
162
163# BEGIN MERGE SLOT 10
164
165# END MERGE SLOT 10