How to use the duniterpy.api.bma.wot 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 / duniter-python-api / examples / send_certification.py View on Github external
# create our Identity document to sign the Certification document
    identity = await get_identity_document(client, current_block, pubkey_to)
    if identity is None:
        print("Identity not found for pubkey {0}".format(pubkey_to))
        # Close client aiohttp session
        await client.close()
        sys.exit(1)

    # send the Certification document to the node
    certification = get_certification_document(current_block, identity, pubkey_from)

    # sign document
    certification.sign([key])

    # Here we request for the path wot/certify
    response = await client(bma.wot.certify, certification.signed_raw())

    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing certification: {0}".format(await response.text()))

    # Close client aiohttp session
    await client.close()
github duniter / sakia / src / sakia / services / identities.py View on Github external
async def load_requirements(self, identity):
        """
        Refresh a given identity information
        :param sakia.data.entities.Identity identity:
        :return:
        """
        try:
            requirements = await self._bma_connector.get(self.currency, bma.wot.requirements,
                                                         req_args={'search': identity.pubkey})
            for identity_data in requirements['identities']:
                if not identity.uid or identity.uid == identity_data["uid"]:
                    if not identity.blockstamp or identity.blockstamp == block_uid(identity_data["meta"]["timestamp"]):
                        identity.uid = identity_data["uid"]
                        identity.blockstamp = block_uid(identity_data["meta"]["timestamp"])
                        identity.timestamp = self._blockchain_processor.rounded_timestamp(self.currency, identity.blockstamp.number)
                        identity.outdistanced = identity_data["outdistanced"]
                        identity.written = identity_data["wasMember"]
                        identity.sentry = identity_data["isSentry"]
                        identity.member = identity_data["membershipExpiresIn"] > 0
                        median_time = self._blockchain_processor.time(self.currency)
                        expiration_time = self._blockchain_processor.parameters(self.currency).ms_validity
                        identity.membership_timestamp = median_time - (expiration_time - identity_data["membershipExpiresIn"])
                        # We save connections pubkeys
                        if self._identities_processor.get_identity(self.currency, identity.pubkey, identity.uid):
github duniter / sakia / src / sakia / core / net / api / bma / access.py View on Github external
def _invalidate_cache(self, post_request):
        """
        Invalidate data depending on posted request
        :param class post_request: The posted request
        """
        invalidated = {bma.wot.Add: bma.wot.Lookup}
        if post_request in invalidated:
            invalidated_cache = self._data.copy()
            for data in self._data:
                if data[0] == str(invalidated[post_request]):
                    invalidated_cache.pop(data)
            self._data = invalidated_cache
github duniter / sakia / src / sakia / services / documents.py View on Github external
revocation = Revocation(10, currency, None)
        self_cert = identity.document()

        key = SigningKey(salt, password)
        revocation.sign(self_cert, [key])

        self._logger.debug("Self-Revokation Document : \n{0}".format(revocation.raw(self_cert)))
        self._logger.debug("Signature : \n{0}".format(revocation.signatures[0]))

        data = {
            'pubkey': identity.pubkey,
            'self_': self_cert.signed_raw(),
            'sig': revocation.signatures[0]
        }
        self._logger.debug("Posted data : {0}".format(data))
        responses = await self._bma_connector.broadcast(currency, bma.wot.Revoke, {}, data)
        result = await parse_bma_responses(responses)
        return result
github duniter / sakia / src / sakia / gui / revocation.py View on Github external
async def accept(self):
        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:
github duniter / sakia / src / sakia / data / connectors / bma.py View on Github external
elif isinstance(r, BaseException):
                                self._logger.debug("Exception in responses : " + str(r))
                                continue
                            else:
                                filtered_data = _filter_data(request, r)
                                data_hash = make_hash(filtered_data)
                            answers_data[data_hash] = r
                            if data_hash not in answers:
                                answers[data_hash] = [node]
                            else:
                                answers[data_hash].append(node)
        finally:
            await session.close()

        if len(answers_data) > 0:
            if request is bma.wot.lookup:
                return _merge_lookups(answers_data)
            else:
                return _best_answer(answers, answers_data, nb_verification)

        raise NoPeerAvailable("", len(synced_nodes))
github duniter / sakia / src / sakia / gui / identities_tab.py View on Github external
async def _async_execute_search_text(self, checked):
        cancel_once_task(self, self._async_search_direct_connections)

        self.ui.busy.show()
        text = self.ui.edit_textsearch.text()
        if len(text) < 2:
            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:
github duniter / duniter-python-api / examples / save_revoke_document.py View on Github external
async def get_identity_document(
    client: Client, current_block: dict, pubkey: str
) -> Optional[Identity]:
    """
    Get the identity document of the pubkey

    :param client: Client to connect to the api
    :param current_block: Current block data
    :param pubkey: UID/Public key

    :rtype: Identity
    """
    # Here we request for the path wot/lookup/pubkey
    lookup_data = await client(bma.wot.lookup, pubkey)
    identity = None

    # parse results
    for result in lookup_data["results"]:
        if result["pubkey"] == pubkey:
            uids = result["uids"]
            uid_data = uids[0]
            # capture data
            timestamp = BlockUID.from_str(uid_data["meta"]["timestamp"])
            uid = uid_data["uid"]  # type: str
            signature = uid_data["self"]  # type: str

            # return self-certification document
            identity = Identity(
                version=10,
                currency=current_block["currency"],
github duniter / sakia / src / sakia / gui / dialogs / revocation / model.py View on Github external
async def send_to_node(self, server, port, secured):
        signed_raw = self.revocation_document.signed_raw(self.revoked_identity)
        node_connector = await NodeConnector.from_address(None, secured, server, port, self.app.parameters)
        for endpoint in [e for e in node_connector.node.endpoints
                         if isinstance(e, BMAEndpoint) or isinstance(e, SecuredBMAEndpoint)]:
            try:
                self._logger.debug("Broadcasting : \n" + signed_raw)
                conn_handler = endpoint.conn_handler(node_connector.session, proxy=self.app.parameters.proxy())
                result = await bma.wot.revoke(conn_handler, signed_raw)
                if result.status == 200:
                    return True, ""
                else:
                    return False, bma.api.parse_error(await result.text())["message"]
            except errors.DuniterError as e:
                return False, e.message
            except (jsonschema.ValidationError, ClientError, gaierror,
                    TimeoutError, ConnectionRefusedError, ValueError) as e:
                return False, str(e)
            finally:
                node_connector.session.close()
        return True, ""