aboutsummaryrefslogtreecommitdiff
path: root/pyecsca/sca/re/epa.py
blob: 32abb45207da98c614c159d6377acc705631f747 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
Provides functionality inspired by the Exceptional Procedure Attack [EPA]_.
"""

from typing import Callable, Literal, Union

from public import public

from pyecsca.ec.point import Point
from pyecsca.sca.re.rpa import MultipleContext


@public
def errors_out(
    ctx: MultipleContext,
    out: Point,
    check_funcs: dict[str, Callable],
    check_condition: Union[Literal["all"], Literal["necessary"]],
    precomp_to_affine: bool,
) -> bool:
    """

    :param ctx: The context containing the points and formulas.
    :param out: The output point to check.
    :param check_funcs:
    :param check_condition:
    :param precomp_to_affine:
    :return:

    .. note::
        The scalar multiplier must not short-circuit.
    """
    affine_points = {out, *ctx.precomp.values()} if precomp_to_affine else {out}
    if check_condition == "all":
        points = set(ctx.points.keys())
    elif check_condition == "necessary":
        points = set(affine_points)
        queue = set(affine_points)
        while queue:
            point = queue.pop()
            for parent in ctx.parents[point]:
                points.add(parent)
                queue.add(parent)
    else:
        raise ValueError("check_condition must be 'all' or 'necessary'")

    # Special case the "to affine" transform and checks
    # This actually passes the multiple itself to the check, not the inputs(parents)
    for point in affine_points:
        if "affine" in check_funcs:
            func = check_funcs["affine"]
            if func(ctx.points[point]):
                return True
    # Now handle the regular checks
    for point in points:
        formula = ctx.formulas[point]
        if formula in check_funcs:
            func = check_funcs[formula]
            inputs = list(map(lambda pt: ctx.points[pt], ctx.parents[point]))
            if func(*inputs):
                return True
    return False