Esempio n. 1
0
def get_work(client):
    """ Get work from the pool using the rest client.

    Args:
        client (TwentyOneRestClient): rest client used for communication with the backend api

    Returns:
        WorkNotification: a Swirl work notification message
    """
    try:
        response = client.get_work()
    except exceptions.ServerRequestError as e:
        if e.status_code == 403 and "detail" in e.data and "TO200" in e.data[
                "detail"]:
            raise exceptions.BitcoinComputerNeededError(
                msg=uxstring.UxString.mining_bitcoin_computer_needed,
                response=response)
        elif e.status_code == 403 and e.data.get("detail") == "TO201":
            raise exceptions.MiningDisabledError(
                uxstring.UxString.Error.suspended_account)
        elif e.status_code == 403 and e.data.get("detail") == "TO501":
            raise exceptions.MiningDisabledError(
                uxstring.UxString.monthly_mining_limit_reached)
        elif e.status_code == 403 and e.data.get("detail") == "TO502":
            raise exceptions.MiningDisabledError(
                uxstring.UxString.lifetime_earn_limit_reached)
        elif e.status_code == 403 and e.data.get("detail") == "TO503":
            raise exceptions.MiningDisabledError(
                uxstring.UxString.no_earn_allocations.format(
                    two1.TWO1_WWW_HOST, client.username))
        elif e.status_code == 404:
            if bitcoin_computer.has_mining_chip():
                raise exceptions.MiningDisabledError(
                    uxstring.UxString.monthly_mining_limit_reached)
            else:
                raise exceptions.MiningDisabledError(
                    uxstring.UxString.earn_limit_reached)
        else:
            raise e

    msg_factory = message_factory.SwirlMessageFactory()
    msg = base64.decodebytes(response.content)
    work = msg_factory.read_object(msg)
    return work
Esempio n. 2
0
    def _request(self,
                 sign_username=None,
                 method="GET",
                 path="",
                 two1_auth=None,
                 **kwargs):
        if self._session is None:
            self._create_session()

        url = self.server_url + path
        headers = {}
        if "data" in kwargs:
            headers["Content-Type"] = "application/json"
            data = kwargs["data"]
        else:
            data = ""
        if sign_username is not None:
            timestamp = datetime.datetime.now().isoformat()
            message = url + timestamp + data
            sig = self.auth.sign_message(message)
            headers["Authorization"] = "21 {} {} {}".format(
                timestamp, sign_username, sig)

        if two1_auth is not None:
            auth_string = 'Basic ' + base64.b64encode(
                bytes('{}:{}'.format(two1_auth[0], two1_auth[1]),
                      'utf-8')).decode().strip()
            headers["Authorization"] = auth_string
        # Change the user agent to contain the 21 CLI and version
        headers["User-Agent"] = "21/{}".format(two1.TWO1_VERSION)
        headers["From"] = "{}@{}".format(self._wallet_pk, self._device_id)

        try:
            response = self._session.request(method,
                                             url,
                                             headers=headers,
                                             **kwargs)
        except (requests.exceptions.Timeout,
                requests.exceptions.ConnectionError):
            raise exceptions.ServerConnectionError(
                uxstring.UxString.Error.connection.format("21 Servers"))

        # update required
        if response.status_code == 301:
            raise exceptions.UpdateRequiredError(
                uxstring.UxString.update_required)

        if response.status_code == 403:
            ex = exceptions.ServerRequestError(
                msg=uxstring.UxString.Error.server_403, response=response)
            if "detail" in ex.data and "TO100" in ex.data["detail"]:
                raise exceptions.BitcoinComputerNeededError(
                    uxstring.UxString.bitcoin_computer_needed,
                    response=response)
            else:
                raise ex

        if response.status_code > 299:
            raise exceptions.ServerRequestError(
                msg=uxstring.UxString.Error.server_err, response=response)

        return response
Esempio n. 3
0
    def _request(self,
                 sign_username=None,
                 method="GET",
                 path="",
                 two1_auth=None,
                 **kwargs):
        if self._session is None:
            self._create_session()

        url = self.server_url + path
        headers = {}
        if "data" in kwargs:
            headers["Content-Type"] = "application/json"
            data = kwargs["data"]
        else:
            data = ""
        if sign_username is not None:
            timestamp = datetime.datetime.now().isoformat()
            message = url + timestamp + data
            sig = self.auth.sign_message(message)
            headers["Authorization"] = "21 {} {} {}".format(
                timestamp, sign_username, sig)

        if two1_auth is not None:
            auth_string = 'Basic ' + base64.b64encode(
                bytes('{}:{}'.format(two1_auth[0], two1_auth[1]),
                      'utf-8')).decode().strip()
            headers["Authorization"] = auth_string
        # Change the user agent to contain the 21 CLI and version
        headers["User-Agent"] = "21/{}".format(two1.TWO1_VERSION)
        headers["From"] = "{}@{}".format(self._wallet_pk, self._device_id)

        try:
            response = self._session.request(method,
                                             url,
                                             headers=headers,
                                             **kwargs)
        except (requests.exceptions.Timeout,
                requests.exceptions.ConnectionError):
            raise exceptions.ServerConnectionError(
                'Error: Cannot connect to 21 servers. '
                'Please check your Internet connection.')
        if response.status_code == 301:
            raise exceptions.UpdateRequiredError(
                uxstring.UxString.update_required)
        elif response.status_code == 403:
            ex = exceptions.ServerRequestError(
                response,
                message=click.style(
                    "Received forbidden error (403). Login in with ",
                    fg="red") + click.style("21 login ", bold=True, fg="red") +
                click.style("and try again.", fg="red"))
            if ex.data.get('detail') in ('TO100', 'TO200'):
                raise exceptions.BitcoinComputerNeededError(
                    response,
                    message=(
                        "You need a 21 Bitcoin Computer (21.co/buy) to access "
                        "this service. If you believe you have received this "
                        "message in error, please contact [email protected]."))
            else:
                raise ex
        elif 400 <= response.status_code <= 499:
            raise exceptions.ServerRequestError(response)
        elif 500 <= response.status_code <= 599:
            raise exceptions.ServerRequestError(
                response,
                message="You have experienced a server error (%d). "
                "We are working to correct the issue." % response.status_code)
        else:
            return response