diff options
| author | J08nY | 2021-04-10 21:25:47 +0200 |
|---|---|---|
| committer | J08nY | 2021-04-10 21:25:47 +0200 |
| commit | a2e01e037fcde3e63571633e94156e324a4f2299 (patch) | |
| tree | d8673d569924d3241b49808d4e96c7eb062b891a | |
| parent | b76ec0890e4cf997ce5a0b4494722931094683f7 (diff) | |
| download | pyecsca-a2e01e037fcde3e63571633e94156e324a4f2299.tar.gz pyecsca-a2e01e037fcde3e63571633e94156e324a4f2299.tar.zst pyecsca-a2e01e037fcde3e63571633e94156e324a4f2299.zip | |
Implement fixes from DeepSource.
29 files changed, 145 insertions, 132 deletions
diff --git a/pyecsca/ec/configuration.py b/pyecsca/ec/configuration.py index bf20ec7..d92486d 100644 --- a/pyecsca/ec/configuration.py +++ b/pyecsca/ec/configuration.py @@ -4,7 +4,15 @@ This module provides a way to work with and enumerate implementation configurati from dataclasses import dataclass from enum import Enum from itertools import product -from typing import get_type_hints, Union, get_origin, get_args, Generator, FrozenSet +from typing import ( + get_type_hints, + Union, + get_origin, + get_args, + Generator, + FrozenSet, + Any, +) from public import public @@ -24,11 +32,11 @@ class EnumDefine(Enum): @classmethod def names(cls): - return list(e.name for e in cls) + return [e.name for e in cls] @classmethod def values(cls): - return list(e.value for e in cls) + return [e.value for e in cls] @public @@ -130,7 +138,7 @@ def all_configurations(**kwargs) -> Generator[Configuration, Configuration, None return ( get_origin(arg_type) == Union and len(get_args(arg_type)) == 2 - and get_args(arg_type)[1] == type(None) # noqa + and get_args(arg_type)[1] is type(None) # noqa ) def leaf_subclasses(cls): @@ -216,7 +224,7 @@ def all_configurations(**kwargs) -> Generator[Configuration, Configuration, None if "model" in kwargs: if model != kwargs["model"]: continue - for coords_name, coords in model.coordinates.items(): + for coords in model.coordinates.values(): if "coords" in kwargs: if coords != kwargs["coords"]: continue diff --git a/pyecsca/ec/context.py b/pyecsca/ec/context.py index 5bef891..a5d6633 100644 --- a/pyecsca/ec/context.py +++ b/pyecsca/ec/context.py @@ -145,7 +145,7 @@ class Context(ABC): :param action: The action. """ - ... + raise NotImplementedError @abstractmethod def exit_action(self, action: Action) -> None: @@ -154,7 +154,7 @@ class Context(ABC): :param action: The action. """ - ... + raise NotImplementedError def __str__(self): return self.__class__.__name__ diff --git a/pyecsca/ec/formula.py b/pyecsca/ec/formula.py index c0505e1..e0ce886 100644 --- a/pyecsca/ec/formula.py +++ b/pyecsca/ec/formula.py @@ -77,7 +77,7 @@ class FormulaAction(ResultAction): parents.append(self.intermediates[parent][-1]) elif parent in self.inputs: parents.append(self.inputs[parent]) - li = self.intermediates.setdefault(op.result, list()) + li = self.intermediates.setdefault(op.result, []) li.append(OpResult(op.result, value, op.operator, *parents)) def add_result(self, point: Any, **outputs: Mod): @@ -185,7 +185,7 @@ class Formula(ABC): expr = resolve(expr) poly = Poly(expr, symbols(param), domain=k) roots = poly.ground_roots() - for root in roots.keys(): + for root in roots: params[param] = Mod(int(root), field) break else: @@ -248,25 +248,25 @@ class Formula(ABC): @abstractmethod def input_index(self): """The starting index where this formula reads its inputs.""" - ... + raise NotImplementedError @property @abstractmethod def output_index(self) -> int: """The starting index where this formula stores its outputs.""" - ... + raise NotImplementedError @property @abstractmethod def inputs(self) -> Set[str]: """The input variables of the formula.""" - ... + raise NotImplementedError @property @abstractmethod def outputs(self) -> Set[str]: """The output variables of the formula.""" - ... + raise NotImplementedError @property def num_operations(self) -> int: @@ -302,12 +302,7 @@ class Formula(ABC): def num_addsubs(self) -> int: """Number of additions and subtractions.""" return len( - list( - filter( - lambda op: op.operator == OpType.Add or op.operator == OpType.Sub, - self.code, - ) - ) + list(filter(lambda op: op.operator in (OpType.Add, OpType.Sub), self.code)) ) @@ -361,22 +356,22 @@ class EFDFormula(Formula): @property def inputs(self): - return set( + return { var + str(i) for var, i in product( self.coordinate_model.variables, range(1, 1 + self.num_inputs) ) - ) + } @property def outputs(self): - return set( + return { var + str(i) for var, i in product( self.coordinate_model.variables, range(self.output_index, self.output_index + self.num_outputs), ) - ) + } def __eq__(self, other): if not isinstance(other, EFDFormula): diff --git a/pyecsca/ec/mod.py b/pyecsca/ec/mod.py index 8485cbe..4712de1 100644 --- a/pyecsca/ec/mod.py +++ b/pyecsca/ec/mod.py @@ -8,7 +8,7 @@ dispatches to the implementation chosen by the runtime configuration of the libr import random import secrets from functools import wraps, lru_cache -from typing import Type, Dict, Any +from typing import Type, Dict, Any, Tuple from public import public from sympy import Expr, FF @@ -60,7 +60,7 @@ def extgcd(a, b): @public -def jacobi(x: int, n: int): +def jacobi(x: int, n: int) -> int: """Jacobi symbol.""" if n <= 0: raise ValueError("'n' must be a positive integer.") @@ -72,7 +72,7 @@ def jacobi(x: int, n: int): while x % 2 == 0: x //= 2 nm8 = n % 8 - if nm8 == 3 or nm8 == 5: + if nm8 in (3, 5): r = -r x, n = n, x if x % 4 == 3 and n % 4 == 3: @@ -85,7 +85,7 @@ def jacobi(x: int, n: int): @lru_cache def miller_rabin(n: int, rounds: int = 50) -> bool: """Miller-Rabin probabilistic primality test.""" - if n == 2 or n == 3: + if n in (2, 3): return True if n % 2 == 0: @@ -98,7 +98,7 @@ def miller_rabin(n: int, rounds: int = 50) -> bool: for _ in range(rounds): a = random.randrange(2, n - 1) x = pow(a, s, n) - if x == 1 or x == n - 1: + if x in (1, n - 1): continue for _ in range(r - 1): x = pow(x, 2, n) @@ -160,22 +160,22 @@ class Mod(object): ) @_check - def __add__(self, other): + def __add__(self, other) -> "Mod": return self.__class__((self.x + other.x) % self.n, self.n) @_check - def __radd__(self, other): + def __radd__(self, other) -> "Mod": return self + other @_check - def __sub__(self, other): + def __sub__(self, other) -> "Mod": return self.__class__((self.x - other.x) % self.n, self.n) @_check - def __rsub__(self, other): + def __rsub__(self, other) -> "Mod": return -self + other - def __neg__(self): + def __neg__(self) -> "Mod": return self.__class__(self.n - self.x, self.n) def inverse(self) -> "Mod": @@ -185,14 +185,14 @@ class Mod(object): :return: The inverse. :raises: :py:class:`NonInvertibleError` if the element is not invertible. """ - ... + raise NotImplementedError - def __invert__(self): + def __invert__(self) -> "Mod": return self.inverse() def is_residue(self) -> bool: """Whether this element is a quadratic residue (only implemented for prime modulus).""" - ... + raise NotImplementedError def sqrt(self) -> "Mod": """ @@ -200,45 +200,45 @@ class Mod(object): Uses the `Tonelli-Shanks <https://en.wikipedia.org/wiki/Tonelli–Shanks_algorithm>`_ algorithm. """ - ... + raise NotImplementedError @_check - def __mul__(self, other): + def __mul__(self, other) -> "Mod": return self.__class__((self.x * other.x) % self.n, self.n) @_check - def __rmul__(self, other): + def __rmul__(self, other) -> "Mod": return self * other @_check - def __truediv__(self, other): + def __truediv__(self, other) -> "Mod": return self * ~other @_check - def __rtruediv__(self, other): + def __rtruediv__(self, other) -> "Mod": return ~self * other @_check - def __floordiv__(self, other): + def __floordiv__(self, other) -> "Mod": return self * ~other @_check - def __rfloordiv__(self, other): + def __rfloordiv__(self, other) -> "Mod": return ~self * other @_check - def __divmod__(self, divisor): + def __divmod__(self, divisor) -> Tuple["Mod", "Mod"]: q, r = divmod(self.x, divisor.x) return self.__class__(q, self.n), self.__class__(r, self.n) - def __bytes__(self): - ... + def __bytes__(self) -> bytes: + raise NotImplementedError - def __int__(self): - ... + def __int__(self) -> int: + raise NotImplementedError @classmethod - def random(cls, n: int): + def random(cls, n: int) -> "Mod": """ Generate a random :py:class:`Mod` in ℤₙ. @@ -248,8 +248,8 @@ class Mod(object): with RandomModAction(n) as action: return action.exit(cls(secrets.randbelow(n), n)) - def __pow__(self, n): - ... + def __pow__(self, n) -> "Mod": + raise NotImplementedError def __str__(self): return str(self.x) @@ -269,7 +269,7 @@ class RawMod(Mod): self.x = x % n self.n = n - def inverse(self): + def inverse(self) -> "RawMod": if self.x == 0: raise_non_invertible() x, y, d = extgcd(self.x, self.n) @@ -287,7 +287,7 @@ class RawMod(Mod): legendre_symbol = jacobi(self.x, self.n) return legendre_symbol == 1 - def sqrt(self): + def sqrt(self) -> "RawMod": if not miller_rabin(self.n): raise NotImplementedError if self.x == 0: @@ -346,7 +346,7 @@ class RawMod(Mod): def __hash__(self): return hash(("RawMod", self.x, self.n)) - def __pow__(self, n): + def __pow__(self, n) -> "RawMod": if type(n) is not int: raise TypeError if n == 0: @@ -394,7 +394,7 @@ class Undefined(Mod): def sqrt(self): raise NotImplementedError - def is_residue(self) -> bool: + def is_residue(self): raise NotImplementedError def __invert__(self): @@ -479,61 +479,61 @@ class SymbolicMod(Mod): self.n = n @_symbolic_check - def __add__(self, other): + def __add__(self, other) -> "SymbolicMod": return self.__class__((self.x + other.x), self.n) @_symbolic_check - def __radd__(self, other): + def __radd__(self, other) -> "SymbolicMod": return self + other @_symbolic_check - def __sub__(self, other): + def __sub__(self, other) -> "SymbolicMod": return self.__class__((self.x - other.x), self.n) @_symbolic_check - def __rsub__(self, other): + def __rsub__(self, other) -> "SymbolicMod": return -self + other - def __neg__(self): + def __neg__(self) -> "SymbolicMod": return self.__class__(-self.x, self.n) - def inverse(self): + def inverse(self) -> "SymbolicMod": return self.__class__(self.x ** (-1), self.n) - def sqrt(self): + def sqrt(self) -> "SymbolicMod": raise NotImplementedError - def is_residue(self) -> bool: + def is_residue(self): raise NotImplementedError - def __invert__(self): + def __invert__(self) -> "SymbolicMod": return self.inverse() @_symbolic_check - def __mul__(self, other): + def __mul__(self, other) -> "SymbolicMod": return self.__class__(self.x * other.x, self.n) @_symbolic_check - def __rmul__(self, other): + def __rmul__(self, other) -> "SymbolicMod": return self * other @_symbolic_check - def __truediv__(self, other): + def __truediv__(self, other) -> "SymbolicMod": return self * ~other @_symbolic_check - def __rtruediv__(self, other): + def __rtruediv__(self, other) -> "SymbolicMod": return ~self * other @_symbolic_check - def __floordiv__(self, other): + def __floordiv__(self, other) -> "SymbolicMod": return self * ~other @_symbolic_check - def __rfloordiv__(self, other): + def __rfloordiv__(self, other) -> "SymbolicMod": return ~self * other - def __divmod__(self, divisor): + def __divmod__(self, divisor) -> "SymbolicMod": raise NotImplementedError def __bytes__(self): @@ -558,7 +558,7 @@ class SymbolicMod(Mod): def __hash__(self): return hash(("SymbolicMod", self.x, self.n)) + 1 - def __pow__(self, n): + def __pow__(self, n) -> "SymbolicMod": try: x = pow(self.x, n, self.n) except TypeError: @@ -586,7 +586,7 @@ if has_gmp: self.x = gmpy2.mpz(x % n) self.n = gmpy2.mpz(n) - def inverse(self): + def inverse(self) -> "GMPMod": if self.x == 0: raise_non_invertible() if self.x == 1: @@ -598,7 +598,7 @@ if has_gmp: res = 0 return GMPMod(res, self.n) - def is_residue(self): + def is_residue(self) -> bool: """Whether this element is a quadratic residue (only implemented for prime modulus).""" if not _is_prime(self.n): raise NotImplementedError @@ -608,7 +608,7 @@ if has_gmp: return self.x in (0, 1) return gmpy2.legendre(self.x, self.n) == 1 - def sqrt(self): + def sqrt(self) -> "GMPMod": """ The modular square root of this element (only implemented for prime modulus). @@ -651,7 +651,7 @@ if has_gmp: return r @_check - def __divmod__(self, divisor): + def __divmod__(self, divisor) -> Tuple["GMPMod", "GMPMod"]: q, r = gmpy2.f_divmod(self.x, divisor.x) return GMPMod(q, self.n), GMPMod(r, self.n) @@ -677,7 +677,7 @@ if has_gmp: def __hash__(self): return hash(("GMPMod", self.x, self.n)) - def __pow__(self, n): + def __pow__(self, n) -> "GMPMod": if type(n) not in (int, gmpy2.mpz): raise TypeError if n == 0: diff --git a/pyecsca/ec/mult.py b/pyecsca/ec/mult.py index 7614dd4..5b1d83e 100644 --- a/pyecsca/ec/mult.py +++ b/pyecsca/ec/mult.py @@ -76,11 +76,11 @@ class ScalarMultiplier(ABC): def __init__(self, short_circuit: bool = True, **formulas: Optional[Formula]): if ( len( - set( + { formula.coordinate_model for formula in formulas.values() if formula is not None - ) + } ) != 1 ): @@ -183,7 +183,7 @@ class ScalarMultiplier(ABC): :param scalar: The scalar to use. :return: The resulting multiple. """ - ... + raise NotImplementedError @public diff --git a/pyecsca/ec/params.py b/pyecsca/ec/params.py index 370b8eb..196f7b0 100644 --- a/pyecsca/ec/params.py +++ b/pyecsca/ec/params.py @@ -181,7 +181,7 @@ def _create_params(curve, coords, infty): ) poly = Poly(expr, symbols(param), domain=k) roots = poly.ground_roots() - for root in roots.keys(): + for root in roots: params[param] = Mod(int(root), field) break else: @@ -304,9 +304,9 @@ def get_category( :return: The category. """ listing = resource_listdir(__name__, "std") - categories = list( + categories = [ entry for entry in listing if resource_isdir(__name__, join("std", entry)) - ) + ] if category not in categories: raise ValueError(f"Category {category} not found.") json_path = join("std", category, "curves.json") @@ -330,9 +330,9 @@ def get_params( :return: The curve. """ listing = resource_listdir(__name__, "std") - categories = list( + categories = [ entry for entry in listing if resource_isdir(__name__, join("std", entry)) - ) + ] if category not in categories: raise ValueError(f"Category {category} not found.") json_path = join("std", category, "curves.json") diff --git a/pyecsca/sca/re/rpa.py b/pyecsca/sca/re/rpa.py index ab038e8..b38f389 100644 --- a/pyecsca/sca/re/rpa.py +++ b/pyecsca/sca/re/rpa.py @@ -61,11 +61,11 @@ class MultipleContext(Context): out = action.output_points[0] self.points[out] = -self.points[inp] elif isinstance(action.formula, DifferentialAdditionFormula): - diff, one, other = action.input_points + _, one, other = action.input_points out = action.output_points[0] self.points[out] = self.points[one] + self.points[other] elif isinstance(action.formula, LadderFormula): - diff, one, other = action.input_points + _, one, other = action.input_points dbl, add = action.output_points self.points[add] = self.points[one] + self.points[other] self.points[dbl] = 2 * self.points[one] diff --git a/pyecsca/sca/scope/picoscope_sdk.py b/pyecsca/sca/scope/picoscope_sdk.py index 6237bb8..d94c0fe 100644 --- a/pyecsca/sca/scope/picoscope_sdk.py +++ b/pyecsca/sca/scope/picoscope_sdk.py @@ -166,9 +166,7 @@ class PicoScopeSdk(Scope): # pragma: no cover tb = floor(high_freq / frequency + high_subtract) actual_frequency = high_freq // (tb - high_subtract) else: - tb = floor(log2(low_freq) - log2(frequency)) - if tb > timebase_bound: - tb = timebase_bound + tb = min(floor(log2(low_freq) - log2(frequency)), timebase_bound) actual_frequency = low_freq // 2 ** tb max_samples = ctypes.c_int32() assert_pico_ok( diff --git a/pyecsca/sca/target/ISO7816.py b/pyecsca/sca/target/ISO7816.py index 1a9c8b8..896cb62 100644 --- a/pyecsca/sca/target/ISO7816.py +++ b/pyecsca/sca/target/ISO7816.py @@ -96,7 +96,7 @@ class ISO7816Target(Target, ABC): @abstractmethod def atr(self) -> bytes: """The ATR (Answer To Reset) of the target.""" - ... + raise NotImplementedError @abstractmethod def select(self, aid: bytes) -> bool: @@ -106,7 +106,7 @@ class ISO7816Target(Target, ABC): :param aid: The AID of the applet to select. :return: Whether the selection was successful. """ - ... + raise NotImplementedError @abstractmethod def send_apdu(self, apdu: CommandAPDU) -> ResponseAPDU: @@ -116,7 +116,7 @@ class ISO7816Target(Target, ABC): :param apdu: The APDU to send. :return: The response. """ - ... + raise NotImplementedError @public diff --git a/pyecsca/sca/target/base.py b/pyecsca/sca/target/base.py index 6747c66..6e1758d 100644 --- a/pyecsca/sca/target/base.py +++ b/pyecsca/sca/target/base.py @@ -13,9 +13,9 @@ class Target(ABC): @abstractmethod def connect(self): """Connect to the target device.""" - ... + raise NotImplementedError @abstractmethod def disconnect(self): """Disconnect from the target device.""" - ... + raise NotImplementedError diff --git a/pyecsca/sca/target/ectester.py b/pyecsca/sca/target/ectester.py index f6635c3..08c0e02 100644 --- a/pyecsca/sca/target/ectester.py +++ b/pyecsca/sca/target/ectester.py @@ -556,10 +556,18 @@ class ECTesterTarget(PCSCTarget): # pragma: no cover ) return resp - def select_applet(self, latest_version: bytes = AID_CURRENT_VERSION): - """Select the *ECTester* applet, with a specified version or older.""" + def select_applet( + self, latest_version: bytes = AID_CURRENT_VERSION, count_back: int = 10 + ) -> bool: + """ + Select the *ECTester* applet, with a specified version or older. + + :param latest_version: The latest version to try. + :param count_back: How many versions back to try. + :return: Whether an applet was successfully selected. + """ version_bytes = bytearray(latest_version) - for i in range(10): + for _ in range(count_back): aid_222 = self.AID_PREFIX + version_bytes + self.AID_SUFFIX_222 if self.select(aid_222): break diff --git a/pyecsca/sca/target/flash.py b/pyecsca/sca/target/flash.py index d1fc16a..cc70a9c 100644 --- a/pyecsca/sca/target/flash.py +++ b/pyecsca/sca/target/flash.py @@ -17,4 +17,4 @@ class Flashable(ABC): :param fw_path: The path to the firmware blob. :return: Whether the flashing was successful. """ - ... + raise NotImplementedError diff --git a/pyecsca/sca/target/serial.py b/pyecsca/sca/target/serial.py index d0e276c..a435ca0 100644 --- a/pyecsca/sca/target/serial.py +++ b/pyecsca/sca/target/serial.py @@ -19,7 +19,7 @@ class SerialTarget(Target): :param data: The data to write. """ - ... + raise NotImplementedError @abstractmethod def read(self, num: int = 0, timeout: int = 0) -> bytes: @@ -30,4 +30,4 @@ class SerialTarget(Target): :param timeout: The timeout in milliseconds. :return: The bytes read. """ - ... + raise NotImplementedError diff --git a/pyecsca/sca/trace/align.py b/pyecsca/sca/trace/align.py index d97e358..070ec2f 100644 --- a/pyecsca/sca/trace/align.py +++ b/pyecsca/sca/trace/align.py @@ -229,9 +229,9 @@ def align_dtw_scale( reference_samples = reference.samples for trace in traces: if fast: - dist, path = fastdtw(reference_samples, trace.samples, radius=radius) + _, path = fastdtw(reference_samples, trace.samples, radius=radius) else: - dist, path = dtw(reference_samples, trace.samples) + _, path = dtw(reference_samples, trace.samples) result_samples = np.zeros(len(reference_samples), dtype=trace.samples.dtype) scale = np.zeros(len(reference_samples), dtype=trace.samples.dtype) for x, y in path: @@ -266,9 +266,9 @@ def align_dtw( reference_samples = reference.samples for trace in traces: if fast: - dist, path = fastdtw(reference_samples, trace.samples, radius=radius) + _, path = fastdtw(reference_samples, trace.samples, radius=radius) else: - dist, path = dtw(reference_samples, trace.samples) + _, path = dtw(reference_samples, trace.samples) result_samples = np.zeros( max((len(trace.samples), len(reference_samples))), dtype=trace.samples.dtype ) diff --git a/pyecsca/sca/trace/match.py b/pyecsca/sca/trace/match.py index 50c86bc..e1181e9 100644 --- a/pyecsca/sca/trace/match.py +++ b/pyecsca/sca/trace/match.py @@ -30,7 +30,7 @@ def match_pattern(trace: Trace, pattern: Trace, threshold: float = 0.8) -> List[ pairs = sorted(zip(peaks, props["prominences"]), key=lambda it: it[1], reverse=True) half = len(pattern_samples) // 2 filtered_peaks: List[int] = [] - for peak, prominence in pairs: + for peak, _ in pairs: if not filtered_peaks: filtered_peaks.append(peak - half) else: diff --git a/pyecsca/sca/trace/trace.py b/pyecsca/sca/trace/trace.py index 96f1ec8..68259c2 100644 --- a/pyecsca/sca/trace/trace.py +++ b/pyecsca/sca/trace/trace.py @@ -94,7 +94,7 @@ class Trace(object): def __copy__(self): return Trace(copy(self.samples), copy(self.meta), copy(self.trace_set)) - def __deepcopy__(self, memodict={}): + def __deepcopy__(self, memodict): return Trace( deepcopy(self.samples, memo=memodict), deepcopy(self.meta, memo=memodict), diff --git a/pyecsca/sca/trace_set/chipwhisperer.py b/pyecsca/sca/trace_set/chipwhisperer.py index a56e676..17eb375 100644 --- a/pyecsca/sca/trace_set/chipwhisperer.py +++ b/pyecsca/sca/trace_set/chipwhisperer.py @@ -63,7 +63,7 @@ class ChipWhispererTraceSet(TraceSet): "textout": None, "traces": None, } - for type in types.keys(): + for type in types: type_path = join(path, name + type + ".npy") if exists(type_path) and isfile(type_path): types[type] = np.load(type_path, allow_pickle=True) diff --git a/pyecsca/sca/trace_set/hdf5.py b/pyecsca/sca/trace_set/hdf5.py index f1d34ef..09ad8a9 100644 --- a/pyecsca/sca/trace_set/hdf5.py +++ b/pyecsca/sca/trace_set/hdf5.py @@ -43,7 +43,7 @@ class HDF5Meta(MutableMapping): def __copy__(self): return deepcopy(self) - def __deepcopy__(self, memodict={}): + def __deepcopy__(self, memodict): return dict(self) def __iter__(self): diff --git a/test/ec/test_context.py b/test/ec/test_context.py index 04dbc7d..6691985 100644 --- a/test/ec/test_context.py +++ b/test/ec/test_context.py @@ -10,7 +10,7 @@ from pyecsca.ec.context import ( Tree, PathContext, ) -from pyecsca.ec.key_generation import KeygenAction, KeyGeneration +from pyecsca.ec.key_generation import KeyGeneration from pyecsca.ec.params import get_params from pyecsca.ec.mod import RandomModAction from pyecsca.ec.mult import LTRMultiplier, ScalarMultiplicationAction @@ -83,9 +83,8 @@ class ContextTests(TestCase): self.assertEqual(result, action.result) def test_default_no_enter(self): - with local(DefaultContext()) as default: - with self.assertRaises(ValueError): - default.exit_action(RandomModAction(7)) + with local(DefaultContext()) as default, self.assertRaises(ValueError): + default.exit_action(RandomModAction(7)) def test_path(self): with local(PathContext([0, 1])) as ctx: diff --git a/test/ec/test_mod.py b/test/ec/test_mod.py index 2c45447..864cc2e 100644 --- a/test/ec/test_mod.py +++ b/test/ec/test_mod.py @@ -190,7 +190,7 @@ class ModTests(TestCase): self.assertIsInstance(Mod(5, 7), RawMod) def test_symbolic(self): - x, y = symbols("x y") + x = symbols("x") p = 13 k = FF(p) sx = SymbolicMod(x, p) diff --git a/test/ec/test_op.py b/test/ec/test_op.py index c09914f..77669fb 100644 --- a/test/ec/test_op.py +++ b/test/ec/test_op.py @@ -44,6 +44,7 @@ class OpTests(TestCase): class OpResultTests(TestCase): def test_str(self): - for op, char in zip((ast.Add(), ast.Sub(), ast.Mult(), ast.Div()), "+-*/"): + for op in (OpType.Add, OpType.Sub, OpType.Mult, OpType.Div): res = OpResult("X1", Mod(0, 5), op, Mod(2, 5), Mod(3, 5)) self.assertEqual(str(res), "X1") + self.assertEqual(repr(res), f"X1 = 2{op.op_str}3") diff --git a/test/ec/test_regress.py b/test/ec/test_regress.py index e02cc8e..ad3e096 100644 --- a/test/ec/test_regress.py +++ b/test/ec/test_regress.py @@ -1,7 +1,9 @@ +from typing import cast from unittest import TestCase from pyecsca.ec.coordinates import AffineCoordinateModel from pyecsca.ec.curve import EllipticCurve +from pyecsca.ec.formula import AdditionFormula, DoublingFormula, ScalingFormula from pyecsca.ec.mod import Mod from pyecsca.ec.model import MontgomeryModel, EdwardsModel from pyecsca.ec.params import get_params @@ -14,9 +16,9 @@ class RegressionTests(TestCase): secp128r1 = get_params("secg", "secp128r1", "projective") base = secp128r1.generator coords = secp128r1.curve.coordinate_model - add = coords.formulas["add-1998-cmo"] - dbl = coords.formulas["dbl-1998-cmo"] - scl = coords.formulas["z"] + add = cast(AdditionFormula, coords.formulas["add-1998-cmo"]) + dbl = cast(DoublingFormula, coords.formulas["dbl-1998-cmo"]) + scl = cast(ScalingFormula, coords.formulas["z"]) mult = LTRMultiplier( add, dbl, scl, always=False, complete=False, short_circuit=True ) diff --git a/test/ec/utils.py b/test/ec/utils.py index 84c568d..c702d5b 100644 --- a/test/ec/utils.py +++ b/test/ec/utils.py @@ -47,12 +47,19 @@ class Profiler(object): if self._output_directory is None or self._benchmark_name is None: return git_commit = ( - run(["git", "rev-parse", "--short", "HEAD"], stdout=PIPE, stderr=DEVNULL) + run( + ["git", "rev-parse", "--short", "HEAD"], + stdout=PIPE, + stderr=DEVNULL, + check=False, + ) .stdout.strip() .decode() ) git_dirty = ( - run(["git", "diff", "--quiet"], stdout=DEVNULL, stderr=DEVNULL).returncode + run( + ["git", "diff", "--quiet"], stdout=DEVNULL, stderr=DEVNULL, check=False + ).returncode != 0 ) version = git_commit + ("-dirty" if git_dirty else "") diff --git a/test/sca/test_align.py b/test/sca/test_align.py index 607b297..1db71b3 100644 --- a/test/sca/test_align.py +++ b/test/sca/test_align.py @@ -37,11 +37,14 @@ class AlignTests(Plottable): result[1].samples, np.array([10, 50, 80, 50, 20, 0, 0, 0], dtype=np.dtype("i1")), ) + self.assertEqual(len(offsets), 2) + self.assertEqual(offsets[0], 0) + self.assertEqual(offsets[1], 3) @slow def test_large_align(self): example = InspectorTraceSet.read("test/data/example.trs") - result, offsets = align_correlation( + result, _ = align_correlation( *example, reference_offset=100000, reference_length=20000, max_offset=15000 ) self.assertIsNotNone(result) @@ -61,7 +64,7 @@ class AlignTests(Plottable): ) a = Trace(first_arr) b = Trace(second_arr) - result, offsets = align_peaks( + result, _ = align_peaks( a, b, reference_offset=2, reference_length=5, max_offset=3 ) self.assertEqual(np.argmax(result[0].samples), np.argmax(result[1].samples)) @@ -75,7 +78,7 @@ class AlignTests(Plottable): ) a = Trace(first_arr) b = Trace(second_arr) - result, offsets = align_sad( + result, _ = align_sad( a, b, reference_offset=2, reference_length=5, max_offset=3 ) self.assertEqual(len(result), 2) diff --git a/test/sca/test_filter.py b/test/sca/test_filter.py index 9d63ea3..91f037c 100644 --- a/test/sca/test_filter.py +++ b/test/sca/test_filter.py @@ -1,5 +1,3 @@ -from unittest import TestCase - import numpy as np from pyecsca.sca import ( Trace, diff --git a/test/sca/test_match.py b/test/sca/test_match.py index 9ba81a3..d39e8c3 100644 --- a/test/sca/test_match.py +++ b/test/sca/test_match.py @@ -1,5 +1,3 @@ -from unittest import TestCase - import numpy as np from pyecsca.sca import Trace, match_pattern, match_part, pad diff --git a/test/sca/test_sampling.py b/test/sca/test_sampling.py index 4a54b4d..fcebf2d 100644 --- a/test/sca/test_sampling.py +++ b/test/sca/test_sampling.py @@ -1,5 +1,3 @@ -from unittest import TestCase - import numpy as np from pyecsca.sca import ( Trace, diff --git a/test/sca/test_target.py b/test/sca/test_target.py index 4168152..299e127 100644 --- a/test/sca/test_target.py +++ b/test/sca/test_target.py @@ -10,7 +10,6 @@ from pyecsca.ec.key_generation import KeyGeneration from pyecsca.ec.mod import Mod from pyecsca.ec.mult import LTRMultiplier from pyecsca.ec.params import DomainParameters, get_params -from pyecsca.ec.point import Point from pyecsca.ec.signature import SignatureResult, ECDSA_SHA1 from pyecsca.sca.target import ( BinaryTarget, @@ -340,7 +339,7 @@ class ECTesterTargetTests(TestCase): self.secp256r1_projective.curve.coordinate_model.formulas["dbl-2016-rcb"], ) keygen = KeyGeneration(copy(mult), self.secp256r1_projective) - priv, pubkey_projective = keygen.generate() + _, pubkey_projective = keygen.generate() ecdh_resp = self.target.ecdh_direct( KeypairEnum.KEYPAIR_LOCAL, diff --git a/test/sca/test_traceset.py b/test/sca/test_traceset.py index 515790e..e79e5d2 100644 --- a/test/sca/test_traceset.py +++ b/test/sca/test_traceset.py @@ -1,7 +1,6 @@ import os.path import shutil import tempfile -from copy import deepcopy from unittest import TestCase import numpy as np |
