1# Copyright 2013 Donald Stufft and individual contributors
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15
16# We create a clone of various builtin Exception types which additionally
17# inherit from CryptoError. Below, we refer to the parent types via the
18# `builtins` namespace, so mypy can distinguish between (e.g.)
19# `nacl.exceptions.RuntimeError` and `builtins.RuntimeError`.
20from __future__ import annotations
21
22import builtins
23
24
25class CryptoError(Exception):
26 """
27 Base exception for all nacl related errors
28 """
29
30
31class BadSignatureError(CryptoError):
32 """
33 Raised when the signature was forged or otherwise corrupt.
34 """
35
36
37class RuntimeError(builtins.RuntimeError, CryptoError):
38 pass
39
40
41class AssertionError(builtins.AssertionError, CryptoError):
42 pass
43
44
45class TypeError(builtins.TypeError, CryptoError):
46 pass
47
48
49class ValueError(builtins.ValueError, CryptoError):
50 pass
51
52
53class InvalidkeyError(CryptoError):
54 pass
55
56
57class CryptPrefixError(InvalidkeyError):
58 pass
59
60
61class UnavailableError(RuntimeError):
62 """
63 is a subclass of :class:`~nacl.exceptions.RuntimeError`, raised when
64 trying to call functions not available in a minimal build of
65 libsodium or due to hardware limitations.
66 """
67
68
69def ensure(cond: bool, *args: object, **kwds: type[Exception]) -> None:
70 """
71 Return if a condition is true, otherwise raise a caller-configurable
72 :py:class:`Exception`
73 :param bool cond: the condition to be checked
74 :param sequence args: the arguments to be passed to the exception's
75 constructor
76 The only accepted named parameter is `raising` used to configure the
77 exception to be raised if `cond` is not `True`
78 """
79 _CHK_UNEXP = "check_condition() got an unexpected keyword argument {0}"
80
81 raising = kwds.pop("raising", AssertionError)
82 if kwds:
83 raise TypeError(_CHK_UNEXP.format(repr(kwds.popitem()[0])))
84
85 if cond is True:
86 return
87 raise raising(*args)