aboutsummaryrefslogtreecommitdiff
path: root/pyecsca/ec/error.py
blob: 003292ee352bb812d0a56f0f0fb86cf63f99b07a (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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""Contains exceptions and warnings used in the library."""

import warnings
from public import public
from pyecsca.misc.cfg import getconfig


@public
class NonInvertibleError(ArithmeticError):
    """Non-invertible element was inverted."""

    pass


@public
class NonInvertibleWarning(UserWarning):
    """Non-invertible element was inverted."""

    pass


def raise_non_invertible():
    """
    Raise either :py:class:`NonInvertibleError` or :py:class:`NonInvertiblerWarning` or ignore.

    Depends on the current config value of :py:attr:`Config.ec.no_inverse_action`.
    """
    cfg = getconfig()
    if cfg.ec.no_inverse_action == "error":
        raise NonInvertibleError("Element not invertible.")
    elif cfg.ec.no_inverse_action == "warning":
        warnings.warn(NonInvertibleWarning("Element not invertible."))


@public
class NonResidueError(ArithmeticError):
    """Non-residue element was square-rooted."""

    pass


@public
class NonResidueWarning(UserWarning):
    """Non-residue element was square-rooted."""

    pass


def raise_non_residue():
    """
    Raise either :py:class:`NonResidueError` or :py:class:`NonResidueWarning` or ignore.

    Depends on the current config value of :py:attr:`Config.ec.non_residue_action`.
    """
    cfg = getconfig()
    if cfg.ec.non_residue_action == "error":
        raise NonResidueError("No square root exists.")
    elif cfg.ec.non_residue_action == "warning":
        warnings.warn(NonResidueWarning("No square root exists."))


@public
class UnsatisfiedAssumptionError(ValueError):
    """Unsatisfied assumption was hit."""

    pass


@public
class UnsatisfiedAssumptionWarning(UserWarning):
    """Unsatisfied assumption was hit."""

    pass


def raise_unsatisified_assumption(action: str, msg: str):
    """
    Raise either :py:class:`UnsatisfiedAssumptionError` or :py:class:`UnsatisfiedAssumptionWarning` or ignore.

    Depends on the value of :paramref:`~.raise_unsatisified_assumption.action`.
    """
    if action == "error":
        raise UnsatisfiedAssumptionError(msg)
    elif action == "warning":
        warnings.warn(UnsatisfiedAssumptionWarning(msg))