|
| 1 | +import hashlib |
| 2 | +import hmac |
| 3 | +import json |
| 4 | +from datetime import datetime |
| 5 | +from enum import IntEnum |
| 6 | +from typing import TYPE_CHECKING, Any, List, Optional |
| 7 | + |
| 8 | +import requests |
| 9 | + |
| 10 | +from bfxapi._utils.json_decoder import JSONDecoder |
| 11 | +from bfxapi._utils.json_encoder import JSONEncoder |
| 12 | +from bfxapi.exceptions import InvalidCredentialError |
| 13 | +from bfxapi.rest.exceptions import RequestParametersError, UnknownGenericError |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from requests.sessions import _Params |
| 17 | + |
| 18 | + |
| 19 | +class _Error(IntEnum): |
| 20 | + ERR_UNK = 10000 |
| 21 | + ERR_GENERIC = 10001 |
| 22 | + ERR_PARAMS = 10020 |
| 23 | + ERR_AUTH_FAIL = 10100 |
| 24 | + |
| 25 | + |
| 26 | +class Middleware: |
| 27 | + __TIMEOUT = 30 |
| 28 | + |
| 29 | + def __init__( |
| 30 | + self, host: str, api_key: Optional[str] = None, api_secret: Optional[str] = None |
| 31 | + ): |
| 32 | + self.__host = host |
| 33 | + |
| 34 | + self.__api_key = api_key |
| 35 | + |
| 36 | + self.__api_secret = api_secret |
| 37 | + |
| 38 | + def get(self, endpoint: str, params: Optional["_Params"] = None) -> Any: |
| 39 | + headers = {"Accept": "application/json"} |
| 40 | + |
| 41 | + if self.__api_key and self.__api_secret: |
| 42 | + headers = {**headers, **self.__get_authentication_headers(endpoint)} |
| 43 | + |
| 44 | + request = requests.get( |
| 45 | + url=f"{self.__host}/{endpoint}", |
| 46 | + params=params, |
| 47 | + headers=headers, |
| 48 | + timeout=Middleware.__TIMEOUT, |
| 49 | + ) |
| 50 | + |
| 51 | + data = request.json(cls=JSONDecoder) |
| 52 | + |
| 53 | + if isinstance(data, list) and len(data) > 0 and data[0] == "error": |
| 54 | + self.__handle_error(data) |
| 55 | + |
| 56 | + return data |
| 57 | + |
| 58 | + def post( |
| 59 | + self, |
| 60 | + endpoint: str, |
| 61 | + body: Optional[Any] = None, |
| 62 | + params: Optional["_Params"] = None, |
| 63 | + ) -> Any: |
| 64 | + _body = body and json.dumps(body, cls=JSONEncoder) or None |
| 65 | + |
| 66 | + headers = {"Accept": "application/json", "Content-Type": "application/json"} |
| 67 | + |
| 68 | + if self.__api_key and self.__api_secret: |
| 69 | + headers = { |
| 70 | + **headers, |
| 71 | + **self.__get_authentication_headers(endpoint, _body), |
| 72 | + } |
| 73 | + |
| 74 | + request = requests.post( |
| 75 | + url=f"{self.__host}/{endpoint}", |
| 76 | + data=_body, |
| 77 | + params=params, |
| 78 | + headers=headers, |
| 79 | + timeout=Middleware.__TIMEOUT, |
| 80 | + ) |
| 81 | + |
| 82 | + data = request.json(cls=JSONDecoder) |
| 83 | + |
| 84 | + if isinstance(data, list) and len(data) > 0 and data[0] == "error": |
| 85 | + self.__handle_error(data) |
| 86 | + |
| 87 | + return data |
| 88 | + |
| 89 | + def __handle_error(self, error: List[Any]) -> None: |
| 90 | + if error[1] == _Error.ERR_PARAMS: |
| 91 | + raise RequestParametersError( |
| 92 | + "The request was rejected with the following parameter" |
| 93 | + f"error: <{error[2]}>" |
| 94 | + ) |
| 95 | + |
| 96 | + if error[1] == _Error.ERR_AUTH_FAIL: |
| 97 | + raise InvalidCredentialError( |
| 98 | + "Cannot authenticate with given API-KEY and API-SECRET." |
| 99 | + ) |
| 100 | + |
| 101 | + if not error[1] or error[1] == _Error.ERR_UNK or error[1] == _Error.ERR_GENERIC: |
| 102 | + raise UnknownGenericError( |
| 103 | + "The server replied to the request with a generic error with " |
| 104 | + f"the following message: <{error[2]}>." |
| 105 | + ) |
| 106 | + |
| 107 | + def __get_authentication_headers(self, endpoint: str, data: Optional[str] = None): |
| 108 | + assert ( |
| 109 | + self.__api_key and self.__api_secret |
| 110 | + ), "API-KEY and API-SECRET must be strings." |
| 111 | + |
| 112 | + nonce = str(round(datetime.now().timestamp() * 1_000_000)) |
| 113 | + |
| 114 | + if not data: |
| 115 | + message = f"/api/v2/{endpoint}{nonce}" |
| 116 | + else: |
| 117 | + message = f"/api/v2/{endpoint}{nonce}{data}" |
| 118 | + |
| 119 | + signature = hmac.new( |
| 120 | + key=self.__api_secret.encode("utf8"), |
| 121 | + msg=message.encode("utf8"), |
| 122 | + digestmod=hashlib.sha384, |
| 123 | + ) |
| 124 | + |
| 125 | + return { |
| 126 | + "bfx-nonce": nonce, |
| 127 | + "bfx-signature": signature.hexdigest(), |
| 128 | + "bfx-apikey": self.__api_key, |
| 129 | + } |
0 commit comments