Пример #1
0
Vim�UnDo�L��ϸ�x�/�6
��ub\������5���?1                logger.error("{} e={}".format(e));.'''']/h�_�����]/`���5�_�����]/`��5�_�����]/`��4from coinmine.worker.utils import make_error_message5�_�����]/`��]�]5�_�����]/`��^�^5�_�����]/`��import logging5�_�����]/`��1logger = logging.getLogger("worker.grinmint.api")5�_�	����]/`��]import requests;from requests.exceptions import RequestException, HTTPError from utils import CoinmineLogger!logger = CoinmineLogger(__name__)def user_stats(username):    return UserStatsGateway(X        Connection.get("https://api.grinmint.com/v1/user/{}/userStats".format(username))    )#def worker_stats(username, worker):    return WorkerStatsGateway(        Connection.get(O            "https://api.grinmint.com/v1/user/{}/worker/{}/workerStats".format(                 username, worker
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError:E            logger.warning("FAILURE {}".format(make_error_message()))         except RequestException:O            logger.error("FAILURE {} url={}".format(make_error_message(), url))        return responseclass Gateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data class UserStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                balance = (V                    float(self.data["unpaid_balance"] + self.data["immature_balance"])                     / 1000000000                )K                return {"amount_mined": balance, "unpaid_balance": balance}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}"class WorkerStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                return {K                    "accepted_shares": self.data["worker"]["valid_shares"],(                    "rejected_shares": (=                        self.data["worker"]["invalid_shares"]=                        + self.data["worker"]["stale_shares"]                    ),                }"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}5�_�
	 ����]/`��!]        except HTTPError:5�_�	
!/����]/`�� "]E            logger.warning("FAILURE {}".format(make_error_message()))5�_�
!0����]/`�� "]2            logger.warning("FAILURE {}".format()))5�_�
!2����]/`�� "]2            logger.warning("FAILURE {}".format(e))5�_�
!1����]/`�� "]1            logger.warning("FAILURE {}".format(e)5�_�
$4����]/`��#%]O            logger.error("FAILURE {} url={}".format(make_error_message(), url))5�_�$6����]/`��#%]<            logger.error("FAILURE {} url={}".format(), url))5�_�$5����]/`��#%];            logger.error("FAILURE {} url={}".format(e url))5�_�#����]/`��"$]         except RequestException:5�_�E.����]/`��DF]G                logger.error("{} e={}".format(make_error_message(), e))5�_�E1����]/`��DF]4                logger.error("{} e={}".format(), e))5�_�E/����]/`��DF]2                logger.error("{} e={}".format()e))5�_�Y.����]/`��XZ]G                logger.error("{} e={}".format(make_error_message(), e))5�_�Y1����]/`��XZ]4                logger.error("{} e={}".format(), e))5�_�	����
	V]/a��	def user_stats(username):    return UserStatsGateway(X        Connection.get("https://api.grinmint.com/v1/user/{}/userStats".format(username))    )5�_�	����		V]/a��Ximport requests;from requests.exceptions import RequestException, HTTPError from utils import CoinmineLogger!logger = CoinmineLogger(__name__)#def worker_stats(username, worker):    return WorkerStatsGateway(        Connection.get(O            "https://api.grinmint.com/v1/user/{}/worker/{}/workerStats".format(                 username, worker
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError as e:2            logger.warning("FAILURE {}".format(e))%        except RequestException as e:<            logger.error("FAILURE {} url={}".format(e, url))        return responseclass Gateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data class UserStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                balance = (V                    float(self.data["unpaid_balance"] + self.data["immature_balance"])                     / 1000000000                )K                return {"amount_mined": balance, "unpaid_balance": balance}"            except Exception as e:1                logger.error("{} e={}".format(e))                return {}
        else:            return {}"class WorkerStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                return {K                    "accepted_shares": self.data["worker"]["valid_shares"],(                    "rejected_shares": (=                        self.data["worker"]["invalid_shares"]=                        + self.data["worker"]["stale_shares"]                    ),                }"            except Exception as e:1                logger.error("{} e={}".format(e))                return {}
        else:            return {}5�_�4����C4V]/a��34 class UserStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                balance = (V                    float(self.data["unpaid_balance"] + self.data["immature_balance"])                     / 1000000000                )K                return {"amount_mined": balance, "unpaid_balance": balance}"            except Exception as e:1                logger.error("{} e={}".format(e))                return {}
        else:            return {}5�_�4����44V]/a��Gimport requests;from requests.exceptions import RequestException, HTTPError from utils import CoinmineLogger!logger = CoinmineLogger(__name__)#def worker_stats(username, worker):    return WorkerStatsGateway(        Connection.get(O            "https://api.grinmint.com/v1/user/{}/worker/{}/workerStats".format(                 username, worker
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError as e:2            logger.warning("FAILURE {}".format(e))%        except RequestException as e:<            logger.error("FAILURE {} url={}".format(e, url))        return responseclass Gateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data"class WorkerStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                return {K                    "accepted_shares": self.data["worker"]["valid_shares"],(                    "rejected_shares": (=                        self.data["worker"]["invalid_shares"]=                        + self.data["worker"]["stale_shares"]                    ),                }"            except Exception as e:1                logger.error("{} e={}".format(e))                return {}
        else:            return {}5�_�9����V]/a��8:EK                    "accepted_shares": self.data["worker"]["valid_shares"],5�_�9/����V]/a��8:Ee                    "current_secondary_hashrateaccepted_shares": self.data["worker"]["valid_shares"],5�_�:����:'</V/]/a�	�9:(                    "rejected_shares": (=                        self.data["worker"]["invalid_shares"]=                        + self.data["worker"]["stale_shares"]5�_�9'����:':/V/]/a��8:BV                    "current_secondary_hashrate": self.data["worker"]["valid_shares"],5�_� 9����:':/V/]/a��8:BF                    "cuhashrate": self.data["worker"]["valid_shares"],5�_�! 95����:':/V/]/a��8:BD                    "hashrate": self.data["worker"]["valid_shares"],5�_� "!9O����:':/V/]/a�
�8:B^                    "hashrate": self.data["worker"]["current_secondary_hashratevalid_shares"],5�_�!#":����:':/V/]/a��9:                    ),5�_�"$#9R����:':/V/]/a��8:AR                    "hashrate": self.data["worker"]["current_secondary_hashrate"],5�_�#%$9P����:':/V/]/a��Aimport requests;from requests.exceptions import RequestException, HTTPError from utils import CoinmineLogger!logger = CoinmineLogger(__name__)#def worker_stats(username, worker):    return WorkerStatsGateway(        Connection.get(O            "https://api.grinmint.com/v1/user/{}/worker/{}/workerStats".format(                 username, worker
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError as e:2            logger.warning("FAILURE {}".format(e))%        except RequestException as e:<            logger.error("FAILURE {} url={}".format(e, url))        return responseclass Gateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data"class WorkerStatsGateway(Gateway):    def to_dict(self):!        if self.status() is True:            try:                return {Q                    "hashrate": self.data["worker"]["current_secondary_hashrate"]                }"            except Exception as e:1                logger.error("{} e={}".format(e))                return {}
        else:            return {}5�_�$&%����'/V/]/c��?    )5�_�%'&;.����'/V/]/h��:<?1                logger.error("{} e={}".format(e))5�_�&';.����'/V/]/h��:<?3                logger.error("{} e={}".format(, e))5��
VimЯUnDoеb3длуе,=ЦХ–#¤#УUH[ы%кWоЖHhЃШƒP                s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat1"}')9L
	_†Џx	_–(W¤¤¤¤^Вb-х')X        miner_status["mining"] = MinerRequests._is_hashing(miner_status.get("hashrate"))5Б_–([¤¤¤¤^Вb/х
import socketimport json from utils import CoinmineLogger+from utils.requests import CoinmineRequests!logger = CoinmineLogger(__name__)class MinerRequests:    @staticmethod%    def get_miner_status(coin, urls):        # we assume not mining        miner_status = {            "uptime": 0,            "hashrate": 0,!            "hashrate_list": [0],            "pool": "",            "errors": [],	        }        try:            miners = {W                "ethereum": lambda: MinerRequests.get_claymore_stats(urls["claymore"]),T                "zcash": lambda: MinerRequests.get_claymore_stats(urls["claymore"]),O                "monero": lambda: MinerRequests.get_xmrig_stats(urls["xmrig"]),S                "grin": lambda: MinerRequests.get_lolminer_stats(urls["lolminer"]),G                "hashcat": lambda: MinerRequests.get_hashtopolis_stats('                    urls["hashtopolis"]                ),X                "handshake": lambda: MinerRequests.get_sixminer_stats(urls["sixminer"]),K                None: lambda: {"errors": "missing coin value from config"},
            }=            miner_status = {**miner_status, **miners[coin]()}I            logger.debug("received miner status {}".format(miner_status))        except Exception as e:G            logger.warning("failed to get miner status e={}".format(e))]        miner_status["mining"] = MinerRequests._is_hashing(miner_status.get("hashrate") or 0)        return miner_status    @staticmethod,    def get_claymore_stats(claymore_socket):        try:H            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:                logger.debug(>                    "attempting to connect to claymore rpc on"1                    " {}".format(claymore_socket)                )*                s.connect(claymore_socket)9                logger.debug("connected to claymore rpc")                 s.settimeout(60)P                s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat1"}')C                logger.debug("sent json for stats to claymore rpc")#                data = s.recv(1024)?                logger.debug("received data from claymore rpc")'            string_data = data.decode()/            json_data = json.loads(string_data)-            result_list = json_data["result"]*            uptime_in_min = result_list[1]:            accepted_shares = result_list[2].split(";")[1]:            rejected_shares = result_list[2].split(";")[2]%            hashrate = result_list[3]            # multigpu            if ";" in hashrate:E                hashrate_list = list(map(float, hashrate.split(";")))-                hashrate = sum(hashrate_list)            else:1                hashrate_list = [float(hashrate)]4            fan_speed = result_list[6].split(";")[1]/            temp = result_list[6].split(";")[0]!            pool = result_list[7]            stats = {4                "uptime": int(float(uptime_in_min)),*                "hashrate": int(hashrate),/                "hashrate_list": hashrate_list,8                "accepted_shares": int(accepted_shares),8                "rejected_shares": int(rejected_shares),,                "fan_speed": int(fan_speed),"                "temp": int(temp),                "pool": pool,
            }C            logger.debug("claymore socket stats: {}".format(stats))            return stats        except Exception as e:            logger.warning(T                "could not handle sending or receiving from socket:" " {}".format(e)
            )B            return {"errors": "claymore http service unavailable"}    @staticmethod)    def get_xmr_stak_stats(xmr_stak_url):        try:B            stats = CoinmineRequests.get(xmr_stak_url, "api.json").            pool = stats["connection"]["pool"]9            uptime_in_sec = stats["connection"]["uptime"]4            # will report 0 if a single thread fails4            hashrate = stats["hashrate"]["total"][0]             if hashrate is None:                hashrate = 0=            accepted_shares = stats["results"]["shares_good"]P            rejected_shares = stats["results"]["shares_total"] - accepted_shares8            # None values come from failed gpus/threads,7            # we want to accurately report the hashrate$            # even if a thread fails8            hashrate_list = stats["hashrate"]["threads"]            # convert None to 0P            hashrate_list = [0 if i[0] is None else i[0] for i in hashrate_list]>            total_hashrate_threads = round(sum(hashrate_list))            return {2                "uptime": int(uptime_in_sec / 60),D                "hashrate": int(hashrate) or total_hashrate_threads,/                "hashrate_list": hashrate_list,8                "accepted_shares": int(accepted_shares),8                "rejected_shares": int(rejected_shares),                "pool": pool,
            }        except Exception as e:L            logger.warning("could not return xmr-stak stats e={}".format(e))B            return {"errors": "xmr-stak http service unavailable"}    @staticmethod+    def get_nanominer_stats(nanominer_url):        try:            hashrate = 0            hashrate_list = []            accepted_shares = 0            rejected_shares = 0            uptime = 0@            stats = CoinmineRequests.get(nanominer_url, "stats")&            algs = stats["Algorithms"]            adapter = 0            for alg in algs:S                values = next(iter(alg.values()))  # gets the first value from dict/                algorithm = list(alg.keys())[0]>                hashrate += float(values["Total"]["Hashrate"])C                accepted_shares += int(values["Total"]["Accepted"])A                rejected_shares += int(values["Total"]["Denied"])0                pool = values.pop("CurrentPool")/                del values["ReconnectionCount"]#                del values["Total"]1                for key, value in values.items():7                    if key == "GPU {}".format(adapter):$                        adapter += 12                        if algorithm == "RandomX":>                            # pass on gpu hashrates on randomx$                            continueB                    hashrate_list.append(float(value["Hashrate"]))&            uptime = stats["WorkTime"]            return {%                "hashrate": hashrate,/                "hashrate_list": hashrate_list,!                "uptime": uptime,3                "accepted_shares": accepted_shares,3                "rejected_shares": rejected_shares,                "pool": pool,
            }        except Exception as e:M            logger.warning("could not return nanominer stats e={}".format(e))C            return {"errors": "nanominer http service unavailable"}    @staticmethodF    def get_teamredminer_stats(teamredminer_socket=("0.0.0.0", 4028)):        stats = {}        try:A            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)            logger.debug(>                "attempting to connect to teamredminer rpc on"1                " {}".format(teamredminer_socket)
            )*            s.connect(teamredminer_socket)9            logger.debug("connected to teamredminer rpc")            s.settimeout(60)!            s.sendall(b"summary")C            logger.debug("sent json for stats to teamredminer rpc")            data = s.recv(1024)?            logger.debug("received data from teamredminer rpc")'            string_data = data.decode().            list_data = string_data.split(",")=            stats["uptime"] = int(list_data[5].split("=")[1])I            hashrate = round(float(list_data[6].split("=")[1]) * 10e5, 3)(            stats["hashrate"] = hashrate/            stats["hashrate_list"] = [hashrate]G            stats["hardware_errors"] = int(list_data[14].split("=")[1])G            stats["accepted_shares"] = int(list_data[12].split("=")[1])G            stats["rejected_shares"] = int(list_data[13].split("=")[1])        except Exception as e:            logger.warning(Q                "could not handle sending or receiving from socket: {}".format(e)
            )        return stats    @staticmethod/    def get_hashtopolis_stats(hashtopolis_url):>        stats = CoinmineRequests.get(hashtopolis_url, "stats").        stats["hashrate"] = stats.pop("speed")4        stats["hashrate_list"] = [stats["hashrate"]]8        stats["accepted_shares"] = stats.pop("accepted")8        stats["uptime"] = stats.pop("uptime_in_seconds")        return stats    @staticmethod)    def get_lolminer_stats(lolminer_url):        stats = {}        try:@            data = CoinmineRequests.get(lolminer_url, "summary")            stats = {4                "uptime": data["Session"]["Uptime"],C                "hashrate": data["Session"]["Performance_Summary"],N                "hashrate_list": [gpu["Performance"] for gpu in data["GPUs"]],?                "accepted_shares": data["Session"]["Accepted"],?                "rejected_shares": data["Session"]["Submitted"].                - data["Session"]["Accepted"],8                "pool": data["Stratum"]["Current_Pool"],
            }        except Exception as e:H            logger.warning("could not get lolminer stats: {}".format(e))        return stats    @staticmethod*    def get_sixminer_stats(handshake_url):;        return MinerRequests.get_local_stats(handshake_url)    @staticmethod#    def get_xmrig_stats(xmrig_url):        stats = {}        try:?            data = CoinmineRequests.get(xmrig_url, "1/summary")            stats = {)                "uptime": data["uptime"],9                "hashrate": data["hashrate"]["total"][0],W                "hashrate_list": [thread[0] for thread in data["hashrate"]["threads"]],B                "accepted_shares": data["results"]["shares_good"],B                "rejected_shares": data["results"]["shares_total"]1                - data["results"]["shares_good"],3                "pool": data["connection"]["pool"],
            }        except Exception as e:E            logger.warning("could not get xmrig stats: {}".format(e))        return stats    @staticmethod    def get_local_stats(url):        stats = {}        try:5            data = CoinmineRequests.get(url, "stats")W            stats = {"hashrate": data["hashrate"], "hashrate_list": [data["hashrate"]]}        except Exception as e:E            logger.warning("could not get local stats: {}".format(e))        return stats    @staticmethod    def _is_hashing(hashrate):$        return bool(float(hashrate))5Б_–yC¤¤¤¤^Вd)хxz
D                "hashrate": int(hashrate) or total_hashrate_threads,5Б_–ц8¤¤¤¤^Вdѓххч
9                "hashrate": data["hashrate"]["total"][0],5Б_–ч+¤¤¤¤^Вiохцш
W                "hashrate_list": [thread[0] for thread in data["hashrate"]["threads"]],5Б_–	ч/¤¤¤¤^Вiрх

import socketimport json from utils import CoinmineLogger+from utils.requests import CoinmineRequests!logger = CoinmineLogger(__name__)class MinerRequests:    @staticmethod%    def get_miner_status(coin, urls):        # we assume not mining        miner_status = {            "uptime": 0,            "hashrate": 0,!            "hashrate_list": [0],            "pool": "",            "errors": [],	        }        try:            miners = {W                "ethereum": lambda: MinerRequests.get_claymore_stats(urls["claymore"]),T                "zcash": lambda: MinerRequests.get_claymore_stats(urls["claymore"]),O                "monero": lambda: MinerRequests.get_xmrig_stats(urls["xmrig"]),S                "grin": lambda: MinerRequests.get_lolminer_stats(urls["lolminer"]),G                "hashcat": lambda: MinerRequests.get_hashtopolis_stats('                    urls["hashtopolis"]                ),X                "handshake": lambda: MinerRequests.get_sixminer_stats(urls["sixminer"]),K                None: lambda: {"errors": "missing coin value from config"},
            }=            miner_status = {**miner_status, **miners[coin]()}I            logger.debug("received miner status {}".format(miner_status))        except Exception as e:G            logger.warning("failed to get miner status e={}".format(e));        miner_status["mining"] = MinerRequests._is_hashing(-            miner_status.get("hashrate") or 0	        )        return miner_status    @staticmethod,    def get_claymore_stats(claymore_socket):        try:H            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:                logger.debug(>                    "attempting to connect to claymore rpc on"1                    " {}".format(claymore_socket)                )*                s.connect(claymore_socket)9                logger.debug("connected to claymore rpc")                 s.settimeout(60)P                s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat1"}')C                logger.debug("sent json for stats to claymore rpc")#                data = s.recv(1024)?                logger.debug("received data from claymore rpc")'            string_data = data.decode()/            json_data = json.loads(string_data)-            result_list = json_data["result"]*            uptime_in_min = result_list[1]:            accepted_shares = result_list[2].split(";")[1]:            rejected_shares = result_list[2].split(";")[2]%            hashrate = result_list[3]            # multigpu            if ";" in hashrate:E                hashrate_list = list(map(float, hashrate.split(";")))-                hashrate = sum(hashrate_list)            else:1                hashrate_list = [float(hashrate)]4            fan_speed = result_list[6].split(";")[1]/            temp = result_list[6].split(";")[0]!            pool = result_list[7]            stats = {4                "uptime": int(float(uptime_in_min)),*                "hashrate": int(hashrate),/                "hashrate_list": hashrate_list,8                "accepted_shares": int(accepted_shares),8                "rejected_shares": int(rejected_shares),,                "fan_speed": int(fan_speed),"                "temp": int(temp),                "pool": pool,
            }C            logger.debug("claymore socket stats: {}".format(stats))            return stats        except Exception as e:            logger.warning(T                "could not handle sending or receiving from socket:" " {}".format(e)
            )B            return {"errors": "claymore http service unavailable"}    @staticmethod)    def get_xmr_stak_stats(xmr_stak_url):        try:B            stats = CoinmineRequests.get(xmr_stak_url, "api.json").            pool = stats["connection"]["pool"]9            uptime_in_sec = stats["connection"]["uptime"]4            # will report 0 if a single thread fails4            hashrate = stats["hashrate"]["total"][0]             if hashrate is None:                hashrate = 0=            accepted_shares = stats["results"]["shares_good"]P            rejected_shares = stats["results"]["shares_total"] - accepted_shares8            # None values come from failed gpus/threads,7            # we want to accurately report the hashrate$            # even if a thread fails8            hashrate_list = stats["hashrate"]["threads"]            # convert None to 0P            hashrate_list = [0 if i[0] is None else i[0] for i in hashrate_list]>            total_hashrate_threads = round(sum(hashrate_list))            return {2                "uptime": int(uptime_in_sec / 60),I                "hashrate": int(hashrate) or total_hashrate_threads or 0,/                "hashrate_list": hashrate_list,8                "accepted_shares": int(accepted_shares),8                "rejected_shares": int(rejected_shares),                "pool": pool,
            }        except Exception as e:L            logger.warning("could not return xmr-stak stats e={}".format(e))B            return {"errors": "xmr-stak http service unavailable"}    @staticmethod+    def get_nanominer_stats(nanominer_url):        try:            hashrate = 0            hashrate_list = []            accepted_shares = 0            rejected_shares = 0            uptime = 0@            stats = CoinmineRequests.get(nanominer_url, "stats")&            algs = stats["Algorithms"]            adapter = 0            for alg in algs:S                values = next(iter(alg.values()))  # gets the first value from dict/                algorithm = list(alg.keys())[0]>                hashrate += float(values["Total"]["Hashrate"])C                accepted_shares += int(values["Total"]["Accepted"])A                rejected_shares += int(values["Total"]["Denied"])0                pool = values.pop("CurrentPool")/                del values["ReconnectionCount"]#                del values["Total"]1                for key, value in values.items():7                    if key == "GPU {}".format(adapter):$                        adapter += 12                        if algorithm == "RandomX":>                            # pass on gpu hashrates on randomx$                            continueB                    hashrate_list.append(float(value["Hashrate"]))&            uptime = stats["WorkTime"]            return {%                "hashrate": hashrate,/                "hashrate_list": hashrate_list,!                "uptime": uptime,3                "accepted_shares": accepted_shares,3                "rejected_shares": rejected_shares,                "pool": pool,
            }        except Exception as e:M            logger.warning("could not return nanominer stats e={}".format(e))C            return {"errors": "nanominer http service unavailable"}    @staticmethodF    def get_teamredminer_stats(teamredminer_socket=("0.0.0.0", 4028)):        stats = {}        try:A            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)            logger.debug(>                "attempting to connect to teamredminer rpc on"1                " {}".format(teamredminer_socket)
            )*            s.connect(teamredminer_socket)9            logger.debug("connected to teamredminer rpc")            s.settimeout(60)!            s.sendall(b"summary")C            logger.debug("sent json for stats to teamredminer rpc")            data = s.recv(1024)?            logger.debug("received data from teamredminer rpc")'            string_data = data.decode().            list_data = string_data.split(",")=            stats["uptime"] = int(list_data[5].split("=")[1])I            hashrate = round(float(list_data[6].split("=")[1]) * 10e5, 3)(            stats["hashrate"] = hashrate/            stats["hashrate_list"] = [hashrate]G            stats["hardware_errors"] = int(list_data[14].split("=")[1])G            stats["accepted_shares"] = int(list_data[12].split("=")[1])G            stats["rejected_shares"] = int(list_data[13].split("=")[1])        except Exception as e:            logger.warning(Q                "could not handle sending or receiving from socket: {}".format(e)
            )        return stats    @staticmethod/    def get_hashtopolis_stats(hashtopolis_url):>        stats = CoinmineRequests.get(hashtopolis_url, "stats").        stats["hashrate"] = stats.pop("speed")4        stats["hashrate_list"] = [stats["hashrate"]]8        stats["accepted_shares"] = stats.pop("accepted")8        stats["uptime"] = stats.pop("uptime_in_seconds")        return stats    @staticmethod)    def get_lolminer_stats(lolminer_url):        stats = {}        try:@            data = CoinmineRequests.get(lolminer_url, "summary")            stats = {4                "uptime": data["Session"]["Uptime"],C                "hashrate": data["Session"]["Performance_Summary"],N                "hashrate_list": [gpu["Performance"] for gpu in data["GPUs"]],?                "accepted_shares": data["Session"]["Accepted"],?                "rejected_shares": data["Session"]["Submitted"].                - data["Session"]["Accepted"],8                "pool": data["Stratum"]["Current_Pool"],
            }        except Exception as e:H            logger.warning("could not get lolminer stats: {}".format(e))        return stats    @staticmethod*    def get_sixminer_stats(handshake_url):;        return MinerRequests.get_local_stats(handshake_url)    @staticmethod#    def get_xmrig_stats(xmrig_url):        stats = {}        try:?            data = CoinmineRequests.get(xmrig_url, "1/summary")            stats = {)                "uptime": data["uptime"],>                "hashrate": data["hashrate"]["total"][0] or 0,\                "hashrate_list": [thread[0] or 0 for thread in data["hashrate"]["threads"]],B                "accepted_shares": data["results"]["shares_good"],B                "rejected_shares": data["results"]["shares_total"]1                - data["results"]["shares_good"],3                "pool": data["connection"]["pool"],
            }        except Exception as e:E            logger.warning("could not get xmrig stats: {}".format(e))        return stats    @staticmethod    def get_local_stats(url):        stats = {}        try:5            data = CoinmineRequests.get(url, "stats")W            stats = {"hashrate": data["hashrate"], "hashrate_list": [data["hashrate"]]}        except Exception as e:E            logger.warning("could not get local stats: {}".format(e))        return stats    @staticmethod    def _is_hashing(hashrate):$        return bool(float(hashrate))5Б_–
	9L¤¤¤¤_†’w	х8:P                s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat1"}')5Б_–	
1¤¤¤¤>+1v_†Џxх0?D        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:            logger.debug(:                "attempting to connect to claymore rpc on"-                " {}".format(claymore_socket)
            )&            s.connect(claymore_socket)5            logger.debug("connected to claymore rpc")            s.settimeout(60)L            s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat2"}')?            logger.debug("sent json for stats to claymore rpc")            data = s.recv(1024);            logger.debug("received data from claymore rpc")#        string_data = data.decode()+        json_data = json.loads(string_data)5Б_–
1¤¤¤¤>'1v_†Џxх0?@    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:        logger.debug(6            "attempting to connect to claymore rpc on")            " {}".format(claymore_socket)	        )"        s.connect(claymore_socket)1        logger.debug("connected to claymore rpc")        s.settimeout(60)H        s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat2"}');        logger.debug("sent json for stats to claymore rpc")        data = s.recv(1024)7        logger.debug("received data from claymore rpc")    string_data = data.decode()'    json_data = json.loads(string_data)5Б_–1¤¤¤¤1>V_†Џyх0?<with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:    logger.debug(2        "attempting to connect to claymore rpc on"%        " {}".format(claymore_socket)    )    s.connect(claymore_socket)-    logger.debug("connected to claymore rpc")    s.settimeout(60)D    s.sendall(b'{"id":0,"jsonrpc":"2.0","method":"miner_getstat2"}')7    logger.debug("sent json for stats to claymore rpc")    data = s.recv(1024)3    logger.debug("received data from claymore rpc")string_data = data.decode()#json_data = json.loads(string_data)5Б_–с¤¤¤¤^Вh™хрт
        stats = {	        }5Б_–с¤¤¤¤^ВhЂхстхтухту%                "accepted_shares": 0,$                "hashrate": 1041.74,:                "hashrate_list": [578.02, 231.77, 231.93],:                "pool": "xmr-us-east1.nanopool.org:14444",%                "rejected_shares": 0,                "uptime": 205,5Бз™
Пример #3
0
Vim�UnDo��
�����\��=*mA�/��uN,
D׌ f?$    return EstimatedEarningsGateway(
####]/S-
_�����]/RC��5�_�����]/RD�5�_�����V]/RI�+def load_account(coin_short_name, address):    return LoadAccountGateway(        Connection.get(D            "https://{}.nanopool.org/api/v1/load_account/{}".format((                coin_short_name, address
            )	        )    )'def payments(coin_short_name, address):    return PaymentsGateway(        Connection.get(@            "https://{}.nanopool.org/api/v1/payments/{}".format((                coin_short_name, address
            )	        )    )5�_�����V]/RI�5�_�����V]/Rm�\2def estimated_earnings(coin_short_name, hashrate):5�_�&����V]/R�\(def hashrate(coin_short_name, hashrate):5�_�$����V]/R��\'def hashrate(coin_short_name, address):$    return EstimatedEarningsGateway(        Connection.get(M            "https://api.nanopool.org/v1/{}/approximated_earnings/{}".format()                coin_short_name, hashrate
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError:E            logger.warning("FAILURE {}".format(make_error_message()))         except RequestException:O            logger.error("FAILURE {} url={}".format(make_error_message(), url))        return responseclass NanopoolGateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data*class LoadAccountGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:                return {W                    "unpaid_balance": float(self.data["data"]["userParams"]["balance"])                }"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}'class PaymentsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:W                return {"balance": float(self._parse_payments_dict(self.data["data"]))}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}2    def _parse_payments_dict(self, payments_dict):        total = 0*        for payment_dict in payments_dict:+            total += payment_dict["amount"]        return total0class EstimatedEarningsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:@                return {"estimated_earnings": self.data["data"]}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}5�_�	)����V]/R��[)                coin_short_name, hashrate5�_�
	,����V]/R��[M            "https://api.nanopool.org/v1/{}/approximated_earnings/{}".format(5�_�	
,����V]/R��[8            "https://api.nanopool.org/v1/{}//{}".format(5�_�
����V]/R��\�[5�_�
����V]/R��\import requests'def hashrate(coin_short_name, address):$    return EstimatedEarningsGateway(        Connection.get(@            "https://api.nanopool.org/v1/{}/hashrate/{}".format((                coin_short_name, address
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError:E            logger.warning("FAILURE {}".format(make_error_message()))         except RequestException:O            logger.error("FAILURE {} url={}".format(make_error_message(), url))        return responseclass NanopoolGateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data*class LoadAccountGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:                return {W                    "unpaid_balance": float(self.data["data"]["userParams"]["balance"])                }"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}'class PaymentsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:W                return {"balance": float(self._parse_payments_dict(self.data["data"]))}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}2    def _parse_payments_dict(self, payments_dict):        total = 0*        for payment_dict in payments_dict:+            total += payment_dict["amount"]        return total0class EstimatedEarningsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:@                return {"estimated_earnings": self.data["data"]}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}5�_�
����V]/R��^�^5�_�
����V]/R��aimport requests from utils import CoinmineLogger!logger = CoinmineLogger(__name__)'def hashrate(coin_short_name, address):$    return EstimatedEarningsGateway(        Connection.get(@            "https://api.nanopool.org/v1/{}/hashrate/{}".format((                coin_short_name, address
            )	        )    )class Connection:    def get(url):        response = None        try:(            response = requests.get(url)'            response.raise_for_status()        except HTTPError:E            logger.warning("FAILURE {}".format(make_error_message()))         except RequestException:O            logger.error("FAILURE {} url={}".format(make_error_message(), url))        return responseclass NanopoolGateway:&    def __init__(self, response_json):        try:,            self.data = response_json.json()        except Exception:            self.data = {}    def status(self):-        return self.data.get("status", False)    def error(self):+        return self.data.get("error", None)    def to_dict(self):        return self.data*class LoadAccountGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:                return {W                    "unpaid_balance": float(self.data["data"]["userParams"]["balance"])                }"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}'class PaymentsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:W                return {"balance": float(self._parse_payments_dict(self.data["data"]))}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}2    def _parse_payments_dict(self, payments_dict):        total = 0*        for payment_dict in payments_dict:+            total += payment_dict["amount"]        return total0class EstimatedEarningsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:@                return {"estimated_earnings": self.data["data"]}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}5�_�����v]/R��b        except HTTPError:5�_�/����v]/R��bE            logger.warning("FAILURE {}".format(make_error_message()))5�_�/����v]/R��b2            logger.warning("FAILURE {}".format()))5�_�����v]/R��b         except RequestException:5�_�4����v]/R��bO            logger.error("FAILURE {} url={}".format(make_error_message(), url))5�_�4����v]/R��b<            logger.error("FAILURE {} url={}".format(), url))5�_�6����v]/R��b=            logger.error("FAILURE {} url={}".format(e), url))5�_�3����v]/R��b3            logger.warning("FAILURE {}".format(e)))5�_�����v]/R�	�b�b5�_�4����4UV]/R��34"*class LoadAccountGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:                return {W                    "unpaid_balance": float(self.data["data"]["userParams"]["balance"])                }"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}'class PaymentsGateway(NanopoolGateway):    def to_dict(self):!        if self.status() is True:            try:W                return {"balance": float(self._parse_payments_dict(self.data["data"]))}"            except Exception as e:G                logger.error("{} e={}".format(make_error_message(), e))                return {}
        else:            return {}2    def _parse_payments_dict(self, payments_dict):        total = 0*        for payment_dict in payments_dict:+            total += payment_dict["amount"]        return total5�_�4����44V]/R��345�_�3����44V]/R��235�_�4����33V]/R��35?0class EstimatedEarningsGateway(NanopoolGateway):5�_�4����33V]/R�
�35?class Gateway(NanopoolGateway):5�_�8����33V]/R��79?@                return {"estimated_earnings": self.data["data"]}5�_�8����33V]/R��79?.                return {"": self.data["data"]}5�_� ;.����33V]/S�:<?G                logger.error("{} e={}".format(make_error_message(), e))5�_�! ;0����33V]/S�:<?4                logger.error("{} e={}".format(), e))5�_� "!;-����33V]/S�:<?1                logger.error("{} e={}".format e))5�_�!#";-����33V]/S�:<?0                logger.error("{} e={}".forma e))5�_�"#
����33V]/S,
�	?$    return EstimatedEarningsGateway(5��
Пример #4
0
Vim�UnDo�s��r�Zq�O��S�E������=`6�c�        ####]/S�_�����]/P+��5�_�����]/P8��5�_�����]/PA�class PoolHealthChecker()5�_�����]/PG��5�_�*����]/PN�*class PoolHealthChecker(BaseHealthChecker)5�_�'����]/PT�    �5�_�����]/Pn�    def _is_healthy(self)5�_�	����]/Pu�        �5�_�
	����]/P��        5�_�	
����]/P��        pss5�_�
����]/P��,from health_monitor import BaseHealthChecker!logger = CoinmineLogger(__name__)+class PoolHealthChecker(BaseHealthChecker):    def _is_healthy(self):        pass5�_�
����]/P���5�_�
����]/P��	,from health_monitor import BaseHealthChecker from utils import CoinmineLogger!logger = CoinmineLogger(__name__)+class PoolHealthChecker(BaseHealthChecker):    def _is_healthy(self):        pass5�_�
����]/P��
    �

5�_�	����]/P��
    def __init__(self)5�_�	����]/P��	5�_�	����]/P��	5�_�	����]/Q�

    def __init__(self):5�_�	����]/Q �	        �	
5�_�
����]/Q$�,from health_monitor import BaseHealthChecker from utils import CoinmineLogger!logger = CoinmineLogger(__name__)+class PoolHealthChecker(BaseHealthChecker):    def __init__(self, coin):        self.coin = coin    def _is_healthy(self):        pass5�_�
����]/Q%�
        �

5�_�	����]/Q.�
    def __init__(self, coin):5�_�	����]/Q/�
    def __init__(self, coin):5�_�����	V	]/SP�    �5�_�����	V	]/SY�    def _get_hashrate(self)5�_�
����	V	]/S[�
        �
5�_�����	V	]/Sa�
        if self5�_�
����	V	]/Sa�
        �
5�_�%����	V	]/Sn�        �5�_�!����	V	]/Sr�        �5�_�" !
����	V	]/S}�
            r5�_�!#"����	V	]/S��        pass5�_�"#����	V	]/S��        �5�_�! ����	V	]/Sx�
        self._get_hashrate()5�_�����]/R5�    ���o+def load_account(coin_short_name, address):    return LoadAccountGateway(        Connection.get(D            "https://{}.nanopool.org/api/v1/load_account/{}".format((                coin_short_name, address