Exemple #1
0
    def _url_query(self, api_call, retries=0):
        try:
            if self.debug:
                print("Query url: " + self.url + api_call)
            response = urllib.request.urlopen(self.url + api_call)
            if response.code == 200:
                return True
            return False  # pragma: no cover

        except urllib.error.HTTPError as e:
            if e.code == 409:
                raise exceptions.AddressAlreadyRegistered(
                    self.address, self.url)
            elif e.code == 404:
                raise exceptions.FarmerNotFound(self.url)
            elif e.code == 400:
                raise exceptions.InvalidAddress(self.address)
            elif e.code == 500:  # pragma: no cover
                raise exceptions.FarmerError(self.url)  # pragma: no cover
            else:
                raise e  # pragma: no cover
        except HTTPException:
            self._handle_connection_error(api_call, retries)
        except urllib.error.URLError:
            self._handle_connection_error(api_call, retries)
        except socket.error:
            self._handle_connection_error(api_call, retries)
Exemple #2
0
    def __init__(self, url=common.DEFAULT_URL, debug=False,
                 max_size=common.DEFAULT_MAX_SIZE,
                 store_path=common.DEFAULT_STORE_PATH,
                 config_path=common.DEFAULT_CONFIG_PATH,
                 set_master_secret=None, set_payout_address=None,
                 connection_retry_limit=common.DEFAULT_CONNECTION_RETRY_LIMIT,
                 connection_retry_delay=common.DEFAULT_CONNECTION_RETRY_DELAY):

        # FIXME validate master_secret

        self.url = url
        self.config = None  # lazy
        self.messanger = None  # lazy
        self.debug = debug  # TODO validate
        self.retry_limit = deserialize.positive_integer(connection_retry_limit)
        self.retry_delay = deserialize.positive_integer(connection_retry_delay)
        self.max_size = deserialize.byte_count(max_size)

        # paths
        self.config_path = os.path.realpath(config_path)  # TODO validate
        self._ensure_path_exists(os.path.dirname(self.config_path))
        self.store_path = os.path.realpath(store_path)
        self._ensure_path_exists(self.store_path)

        # validate payout address
        self.btctxstore = BtcTxStore()
        if set_payout_address and (not self.btctxstore.validate_address(set_payout_address)):
            raise exceptions.InvalidAddress(set_payout_address)

        self._initialize_config(set_master_secret, set_payout_address)
 def _url_query(self, api_path, retries=0, authenticate=True):
     try:
         req = urllib.request.Request(self._server_url + api_path)
         if self._get_wif() and authenticate:
             headers = self._create_authentication_headers()
             req.add_header("Date", headers["Date"])
             req.add_header("Authorization", headers["Authorization"])
         response = urllib.request.urlopen(req)
         if response.code == 200:
             return response.read()
     except urllib.error.HTTPError as e:
         if e.code == 409:
             raise exceptions.AddressAlreadyRegistered(
                 self.auth_address(), self._server_url)
         elif e.code == 404:
             raise exceptions.FarmerNotFound(self._server_url)
         elif e.code == 400:
             raise exceptions.InvalidAddress(self.auth_address())
         elif e.code == 500:  # pragma: no cover
             raise exceptions.FarmerError(self._server_url)
         else:
             raise e  # pragma: no cover
     except http.client.HTTPException:
         self._handle_connection_error(api_path, retries, authenticate)
     except urllib.error.URLError:
         self._handle_connection_error(api_path, retries, authenticate)
     except socket.error:
         self._handle_connection_error(api_path, retries, authenticate)
Exemple #4
0
    def _url_query(self, api_call, retries=0):
        try:
            if self.debug:
                print("Query url: " + self.url + api_call)
            response = urllib.request.urlopen(self.url + api_call)
            if response.code == 200:
                return True
            return False  # pragma: no cover

        except urllib.error.HTTPError as e:
            if e.code == 409:
                raise exceptions.AddressAlreadyRegistered(self.address,
                                                          self.url)
            elif e.code == 404:
                raise exceptions.FarmerNotFound(self.url)
            elif e.code == 400:
                raise exceptions.InvalidAddress(self.address)
            elif e.code == 500:  # pragma: no cover
                raise exceptions.FarmerError(self.url)  # pragma: no cover
            else:
                raise e  # pragma: no cover
        except urllib.error.URLError:
            if retries >= self.connection_retry_limit:
                raise exceptions.ConnectionError(self.url)
            time.sleep(self.connection_retry_delay)
            return self._url_query(api_call, retries + 1)
 def register(self, payout_addr):
     """Attempt to register this client address."""
     if payout_addr and not self.btctxstore.validate_address(payout_addr):
         logger.error("Invalid payout address '{0}'".format(payout_addr))
         raise exceptions.InvalidAddress(payout_addr)
     if payout_addr:
         return self._url_query("/api/register/{0}/{1}".format(
             self.get_nodeid(), payout_addr))
 def _get_server_address(self):
     if not self._server_address:
         data = self._url_query("/api/address", authenticate=False)
         self._server_address = json.loads(data.decode("utf-8"))["address"]
         if not self.btctxstore.validate_address(self._server_address):
             logger.error("Invalid server address '{0}'".format(
                 self._server_address))
             raise exceptions.InvalidAddress(self._server_address)
     return self._server_address
 def register(self, payout_addr):
     """Attempt to register this client address."""
     if payout_addr and not self._btctxstore.validate_address(payout_addr):
         raise exceptions.InvalidAddress(payout_addr)
     if payout_addr:
         return self._url_query("/api/register/{0}/{1}".format(
             self.auth_address(), payout_addr))
     data = self._url_query("/api/register/{0}".format(self.auth_address()))
     data = json.loads(data.decode("utf-8"))
     payout_addr = payout_addr if payout_addr else self.auth_address()
     return (data["btc_addr"] == self.auth_address()
             and data["payout_addr"] == payout_addr)
    def _url_query(self, api_path, authenticate=True):  # NOQA
        i = 0
        while i <= self.retry_limit:
            i += 1
            try:
                query_url = self._server_url + api_path
                req = Request(query_url)
                starttime = datetime.utcnow()
                if self.wif and authenticate:
                    headers = storjcore.auth.create_headers(
                        self.btctxstore, self._get_server_address(), self.wif)
                    req.add_header("Date", headers["Date"])
                    req.add_header("Authorization", headers["Authorization"])
                logger.info("Query: {0} generated in {1}".format(
                    query_url,
                    datetime.utcnow() - starttime))
                response = urlopen(req, timeout=30)
                if 200 <= response.code <= 299:
                    return response.read()
            except HTTPError as e:
                if e.code == 409:
                    raise exceptions.AddressAlreadyRegistered(
                        self.get_nodeid(), self._server_url)
                elif e.code == 404:
                    raise exceptions.ServerNotFound(self._server_url +
                                                    api_path)
                elif e.code == 400:
                    raise exceptions.InvalidAddress(self.get_nodeid())
                elif e.code == 401:  # auth error (likely clock off)
                    # log "HTTP Error 401: UNAUTHORIZED"
                    logger.warning(logmessages.InvalidAuthenticationHeaders())
                elif e.code == 500:  # pragma: no cover
                    raise exceptions.ServerError(self._server_url)
                else:
                    raise e  # pragma: no cover
            except http.client.HTTPException as e:
                logger.warning(repr(e))
            except URLError as e:
                logger.warning(repr(e))
            except socket.error as e:
                logger.warning(repr(e))

            # retry
            delay = self.retry_delay
            logger.info("Query retry in {0} seconds.".format(delay))
            time.sleep(delay)

        # retry limit
        logger.error("Failed to connect to {0}".format(self._server_url))
        raise exceptions.ConnectionError(self._server_url)
Exemple #9
0
    def config(self, set_wallet=None, set_payout_address=None):
        """
        Set and then show the config settings.

        :param set_wallet: Set the HWIF for registration/auth address.
        :param set_payout_address:  Set the payout address.
        :return: Configuation object.
        """
        if((set_payout_address is not None) and
                (not self.btctxstore.validate_address(set_payout_address))):
            raise exceptions.InvalidAddress(set_payout_address)
        if((set_wallet is not None) and
                (not self.btctxstore.validate_wallet(set_wallet))):
            raise exceptions.InvalidHWIF(set_wallet)

        self._init_messenger()
        config_updated = False

        # update payout address if requested
        if set_payout_address:
            self.cfg["payout_address"] = set_payout_address
            config_updated = True

        # update wallet if requested
        if set_wallet:
            self.cfg["wallet"] = set_wallet
            config_updated = True

        # save config if updated
        if config_updated:
            control.config.save(self.btctxstore, self.cfg_path, self.cfg)

        # display config
        print(SHOW_CONFIG_TEMPLATE.format(
            self.messenger.auth_address(),
            self.cfg["payout_address"]
        ))
        return self.cfg
 def _url_query(self, api_path, retries=0, authenticate=True):
     try:
         query_url = self._server_url + api_path
         req = urllib.request.Request(query_url)
         if self.wif and authenticate:
             headers = storjcore.auth.create_headers(
                 self.btctxstore, self._get_server_address(), self.wif)
             req.add_header("Date", headers["Date"])
             req.add_header("Authorization", headers["Authorization"])
         logger.info("Query: {0}".format(query_url))
         response = urllib.request.urlopen(req)
         if response.code == 200:
             return response.read()
     except urllib.error.HTTPError as e:
         logger.warning(repr(e))
         if e.code == 409:
             raise exceptions.AddressAlreadyRegistered(
                 self.auth_address(), self._server_url)
         elif e.code == 404:
             raise exceptions.ServerNotFound(self._server_url)
         elif e.code == 400:
             raise exceptions.InvalidAddress(self.auth_address())
         elif e.code == 401:  # auth error (likely clock off)
             logger.warning(repr(e))
             self._handle_connection_error(api_path, retries, authenticate)
         elif e.code == 500:  # pragma: no cover
             raise exceptions.ServerError(self._server_url)
         else:
             raise e  # pragma: no cover
     except http.client.HTTPException as e:
         logger.warning(repr(e))
         self._handle_connection_error(api_path, retries, authenticate)
     except urllib.error.URLError as e:
         logger.warning(repr(e))
         self._handle_connection_error(api_path, retries, authenticate)
     except socket.error as e:
         logger.warning(repr(e))
         self._handle_connection_error(api_path, retries, authenticate)