How to use the duniterpy.api.errors.DuniterError function in duniterpy

To help you get started, we’ve selected a few duniterpy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github duniter / sakia / src / sakia / core / net / node.py View on Github external
"""
        Refresh the blocks of this node
        :param dict block_data: The block data in json format
        """
        conn_handler = self.endpoint.conn_handler()

        logging.debug("Requesting {0}".format(conn_handler))
        block_hash = block_data['hash']
        self.state = Node.ONLINE

        if not self.block or block_hash != self.block['hash']:
            try:
                if self.block:
                    self.main_chain_previous_block = await bma.blockchain.Block(conn_handler,
                                                                                 self.block['number']).get(self._session)
            except errors.DuniterError as e:
                if e.ucode == errors.BLOCK_NOT_FOUND:
                    self.main_chain_previous_block = None
                else:
                    self.state = Node.OFFLINE
                logging.debug("Error in previous block reply :  {0}".format(self.pubkey[:5]))
                logging.debug(str(e))
                self.changed.emit()
            except (ClientError, gaierror, TimeoutError, DisconnectedError, ValueError) as e:
                logging.debug("{0} : {1}".format(str(e), self.pubkey[:5]))
                self.state = Node.OFFLINE
            except jsonschema.ValidationError as e:
                logging.debug(str(e))
                logging.debug("Validation error : {0}".format(self.pubkey[:5]))
                self.state = Node.CORRUPTED
            finally:
                self.set_block(block_data)
github duniter / sakia / src / sakia / gui / widgets / search_user.py View on Github external
nodes = {}
                for identity in response['results']:
                    nodes[identity['pubkey']] = identity['uids'][0]['uid']

                if nodes:
                    self.nodes = list()
                    self.blockSignals(True)
                    self.combobox_search.clear()
                    self.combobox_search.lineEdit().setText(text)
                    for pubkey, uid in nodes.items():
                        self.nodes.append({'pubkey': pubkey, 'uid': uid})
                        self.combobox_search.addItem(uid)
                    self.blockSignals(False)
                    self.combobox_search.showPopup()
            except errors.DuniterError as e:
                if e.ucode == errors.NO_MATCHING_IDENTITY:
                    self.nodes = list()
                    self.blockSignals(True)
                    self.combobox_search.clear()
                    self.blockSignals(False)
                    self.combobox_search.showPopup()
                else:
                    pass
            except NoPeerAvailable:
                pass
        self.search_completed.emit()
github duniter / sakia / src / sakia / gui / revocation.py View on Github external
try:
            session = aiohttp.ClientSession()
            if self.ui.radio_community.isChecked():
                community = self.account.communities[self.ui.combo_community.currentIndex()]
                await community.bma_access.broadcast(bma.wot.Revoke, {},
                       {
                           'revocation': self.revocation_document.signed_raw(self.revoked_selfcert)
                       })
            elif self.ui.radio_address.isChecked():
                    server = self.ui.edit_address.text()
                    port = self.ui.spinbox_port.value()
                    node = await Node.from_address(None, server, port, session=session)
                    conn_handler = node.endpoint.conn_handler()
                    await bma.wot.Revoke(conn_handler).post(session,
                                                revocation=self.revocation_document.signed_raw(self.revoked_selfcert))
        except (MalformedDocumentError, ValueError, errors.DuniterError,
            aiohttp.errors.ClientError, aiohttp.errors.DisconnectedError,
                aiohttp.errors.TimeoutError) as e:
            await QAsyncMessageBox.critical(self.widget, self.tr("Error broadcasting document"),
                                        str(e))
        else:
            await QAsyncMessageBox.information(self.widget, self.tr("Revocation broadcast"),
                                               self.tr("The document was successfully broadcasted."))
            self.widget.accept()
        finally:
            session.close()
github duniter / sakia / src / sakia / gui / navigation / txhistory / model.py View on Github external
def localized_balance(self):
        """
        Get the localized amount of the given tx history
        :return: the localized amount of given account in given community
        :rtype: int
        """
        try:
            amount = self.sources_service.amount(self.connection.pubkey)
            localized_amount = self.app.current_ref.instance(amount,
                                                             self.connection.currency,
                                                             self.app).localized(False, True)
            return localized_amount
        except NoPeerAvailable as e:
            logging.debug(str(e))
        except errors.DuniterError as e:
            logging.debug(str(e))
        return self.tr("Loading...")
github duniter / sakia / src / sakia / gui / transactions_tab.py View on Github external
block = await self.community.get_block(1)
            minimum_datetime = QDateTime()
            minimum_datetime.setTime_t(block['medianTime'])
            minimum_datetime.setTime(QTime(0, 0))

            self.ui.date_from.setMinimumDateTime(minimum_datetime)
            self.ui.date_from.setDateTime(minimum_datetime)
            self.ui.date_from.setMaximumDateTime(QDateTime().currentDateTime())

            self.ui.date_to.setMinimumDateTime(minimum_datetime)
            tomorrow_datetime = QDateTime().currentDateTime().addDays(1)
            self.ui.date_to.setDateTime(tomorrow_datetime)
            self.ui.date_to.setMaximumDateTime(tomorrow_datetime)
        except NoPeerAvailable as e:
            logging.debug(str(e))
        except errors.DuniterError as e:
            logging.debug(str(e))
github duniter / sakia / src / sakia / services / identities.py View on Github external
for ms in search['memberships']:
                if ms['blockNumber'] > blockstamp.number:
                    blockstamp = BlockUID(ms["blockNumber"], ms['blockHash'])
                    membership_data = ms
            if membership_data:
                identity.membership_timestamp = await self._blockchain_processor.timestamp(self.currency,
                                                                                           blockstamp.number)
                identity.membership_buid = blockstamp
                identity.membership_type = ms["membership"]
                identity.membership_written_on = ms["written"]
                identity = await self.load_requirements(identity)
            # We save connections pubkeys
            identity.written = True
            if self.is_identity_of_connection(identity):
                self._identities_processor.insert_or_update_identity(identity)
        except errors.DuniterError as e:
            logging.debug(str(e))
            if e.ucode in (errors.NO_MATCHING_IDENTITY, errors.NO_MEMBER_MATCHING_PUB_OR_UID):
                identity.written = False
                if self.is_identity_of_connection(identity):
                    self._identities_processor.insert_or_update_identity(identity)
        except NoPeerAvailable as e:
            logging.debug(str(e))
        return identity
github duniter / duniter-python-api / duniterpy / api / client.py View on Github external
"""
        logging.debug(
            "Request : %s", self.reverse_url(self.connection_handler.http_scheme, path)
        )
        url = self.reverse_url(self.connection_handler.http_scheme, path)
        response = await self.connection_handler.session.get(
            url,
            params=kwargs,
            headers=self.headers,
            proxy=self.connection_handler.proxy,
            timeout=15,
        )
        if response.status != 200:
            try:
                error_data = parse_error(await response.text())
                raise DuniterError(error_data)
            except (TypeError, jsonschema.ValidationError):
                raise ValueError(
                    "status code != 200 => %d (%s)"
                    % (response.status, (await response.text()))
                )

        return response
github duniter / sakia / src / sakia / gui / identities_tab.py View on Github external
return
        try:
            response = await self.community.bma_access.future_request(bma.wot.Lookup, {'search': text})
            identities = []
            for identity_data in response['results']:
                for uid_data in identity_data['uids']:
                    identity = Identity.from_handled_data(uid_data['uid'],
                                                         identity_data['pubkey'],
                                                         BlockUID.from_str(uid_data['meta']['timestamp']),
                                                         BlockchainState.BUFFERED)
                    identities.append(identity)

            self.ui.edit_textsearch.clear()
            self.ui.edit_textsearch.setPlaceholderText(text)
            await self.refresh_identities(identities)
        except errors.DuniterError as e:
            if e.ucode == errors.BLOCK_NOT_FOUND:
                logging.debug(str(e))
        except NoPeerAvailable as e:
            logging.debug(str(e))
        finally:
            self.ui.busy.hide()
github duniter / sakia / src / sakia / gui / sub / search_user / model.py View on Github external
async def find_user(self, text):
        """
        Search for a user
        :param text:
        :return:
        """
        try:
            self._nodes = await self.identities_processor.lookup(self.app.currency, text)
        except errors.DuniterError as e:
            if e.ucode == errors.NO_MATCHING_IDENTITY:
                self._nodes = list()
            else:
                logging.debug(str(e))
        except NoPeerAvailable as e:
            logging.debug(str(e))
        except BaseException as e:
            logging.debug(str(e))
github duniter / sakia / src / sakia / core / community.py View on Github external
try:
            udblocks = await self.bma_access.future_request(bma.blockchain.UD)
            blocks = udblocks['result']['blocks']
            if block_number:
                blocks = [b for b in blocks if b <= block_number]
            if len(blocks) > 0:
                index = len(blocks) - (1+x)
                if index < 0:
                    index = 0
                block_number = blocks[index]
                block = await self.bma_access.future_request(bma.blockchain.Block,
                                     req_args={'number': block_number})
                return block
            else:
                return None
        except errors.DuniterError as e:
            if e.ucode == errors.BLOCK_NOT_FOUND:
                logging.debug(str(e))
                return None
        except NoPeerAvailable as e:
            logging.debug(str(e))
            return None