How to use the duniterpy.api.bma 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 / save_revoke_document.py View on Github external
# prompt hidden user entry
    password = getpass.getpass("Enter your password: ")

    # prompt public key
    pubkey = input("Enter your public key: ")

    # init signer instance
    signer = SigningKey.from_credentials(salt, password)

    # check public key
    if signer.pubkey != pubkey:
        print("Bad credentials!")
        sys.exit(0)

    # capture current block to get currency name
    current_block = await client(bma.blockchain.current)

    # create our Identity document to sign the Certification document
    identity = await get_identity_document(client, current_block, pubkey)
    if identity is None:
        print("Identity not found for pubkey {0}".format(pubkey))
        # Close client aiohttp session
        await client.close()
        sys.exit(1)

    # get the revoke document
    revocation_signed_raw_document = get_signed_raw_revocation_document(
        identity, salt, password
    )

    # save revoke document in a file
    fp = open(REVOCATION_DOCUMENT_FILE_PATH, "w")
github duniter / sakia / src / sakia / data / connectors / node.py View on Github external
"""
        Connects to the websocket entry point of the node
        If the connection fails, it tries the fallback mode on HTTP GET
        """
        for endpoint in [e for e in self.node.endpoints if isinstance(e, BMAEndpoint)]:
            if not self._connected['block']:
                try:
                    conn_handler = next(endpoint.conn_handler(self.session, proxy=self._user_parameters.proxy()))
                    ws_connection = bma.ws.block(conn_handler)
                    async with ws_connection as ws:
                        self._connected['block'] = True
                        self._logger.debug("Connected successfully to block ws")
                        async for msg in ws:
                            if msg.type == aiohttp.WSMsgType.TEXT:
                                self._logger.debug("Received a block")
                                block_data = bma.parse_text(msg.data, bma.ws.WS_BLOCk_SCHEMA)
                                self.block_found.emit(BlockUID(block_data['number'], block_data['hash']))
                            elif msg.type == aiohttp.WSMsgType.CLOSED:
                                break
                            elif msg.type == aiohttp.WSMsgType.ERROR:
                                break
                except (aiohttp.WSServerHandshakeError, ValueError) as e:
                    self._logger.debug("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
                    self.handle_failure()
                except (ClientError, gaierror, TimeoutError) as e:
                    self._logger.debug("{0} : {1}".format(str(e), self.node.pubkey[:5]))
                    self.handle_failure()
                except jsonschema.ValidationError as e:
                    self._logger.debug("{:}:{:}".format(str(e.__class__.__name__), str(e)))
                    self.handle_failure(weight=3)
                except RuntimeError:
                    if self.session.closed:
github duniter / duniter-python-api / examples / send_transaction.py View on Github external
# prompt hidden user entry
    password = getpass.getpass("Enter your password: ")

    # create keys from credentials
    key = SigningKey.from_credentials(salt, password)
    pubkey_from = key.pubkey

    # prompt entry
    pubkey_to = input("Enter recipient pubkey: ")

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # capture sources of account
    response = await client(bma.tx.sources, pubkey_from)

    if len(response["sources"]) == 0:
        print("no sources found for account %s" % pubkey_to)
        sys.exit(1)

    # get the first source
    source = response["sources"][0]

    # create the transaction document
    transaction = get_transaction_document(
        current_block, source, pubkey_from, pubkey_to
    )

    # sign document
    transaction.sign([key])
github duniter / sakia / src / sakia / gui / widgets / search_user.py View on Github external
async def search(self):
        """
        Search nodes when return is pressed in combobox lineEdit
        """
        self.search_started.emit()
        text = self.combobox_search.lineEdit().text()
        self.combobox_search.lineEdit().clear()
        self.combobox_search.lineEdit().setPlaceholderText(self.tr("Looking for {0}...".format(text)))

        if len(text) > 2:
            try:
                response = await self.community.bma_access.future_request(bma.wot.Lookup, {'search': text})

                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:
github duniter / sakia / src / sakia / core / txhistory.py View on Github external
async def _get_block_doc(self, community, number):
        """
        Retrieve the current block document
        :param sakia.core.Community community: The community we look for a block
        :param int number: The block number to retrieve
        :return: the block doc or None if no block was found
        """
        tries = 0
        block_doc = None
        block = None
        while block is None and tries < 3:
            try:
                block = await community.bma_access.future_request(bma.blockchain.Block,
                                      req_args={'number': number})
                signed_raw = "{0}{1}\n".format(block['raw'],
                                           block['signature'])
                try:
                    block_doc = Block.from_signed_raw(signed_raw)
                except TypeError:
                    logging.debug("Error in {0}".format(number))
                    block = None
                    tries += 1
            except errors.DuniterError as e:
                if e.ucode == errors.BLOCK_NOT_FOUND:
                    block = None
                    tries += 1
        return block_doc
github duniter / sakia / src / sakia / services / transactions.py View on Github external
async def parse_transactions_history(self, connections, start, end):
        """
        Request transactions from the network to initialize data for a given pubkey
        :param List[sakia.data.entities.Connection] connections: the list of connections found by tx parsing
        :param int start: the first block
        :param int end: the last block
        """
        transfers_changed = []
        new_transfers = {}
        for connection in connections:
            txid = 0
            new_transfers[connection] = []
            history_data = await self._bma_connector.get(self.currency, bma.tx.blocks,
                                                         req_args={'pubkey': connection.pubkey,
                                                                   'start': start,
                                                                   'end': end})
            for tx_data in history_data["history"]["sent"]:
                for tx in [t for t in self._transactions_processor.awaiting(self.currency)]:
                    if self._transactions_processor.run_state_transitions(tx, tx_data["hash"], tx_data["block_number"]):
                        transfers_changed.append(tx)
                        self._logger.debug("New transaction validated : {0}".format(tx.sha_hash))
            for tx_data in history_data["history"]["received"]:
                tx_doc = TransactionDoc.from_bma_history(history_data["currency"], tx_data)
                if not self._transactions_processor.find_by_hash(connection.pubkey, tx_doc.sha_hash) \
                    and SimpleTransaction.is_simple(tx_doc):
                    tx = parse_transaction_doc(tx_doc, connection.pubkey, tx_data["block_number"],
                                               tx_data["time"], txid)
                    if tx:
                        new_transfers[connection].append(tx)
github duniter / duniter-python-api / examples / create_and_publish_identity.py View on Github external
current_block = await client(bma.blockchain.current)

    # prompt entry
    uid = input("Enter your Unique IDentifier (pseudonym): ")

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: ")

    # create our signed identity document
    identity = get_identity_document(current_block, uid, salt, password)

    # send the identity document to the node
    response = await client(bma.wot.add, identity.signed_raw())
    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing identity : {0}".format(await response.text()))

    # Close client aiohttp session
    await client.close()
github duniter / sakia / src / sakia / data / processors / blockchain.py View on Github external
async def handle_new_blocks(self, currency, network_blockstamp):
        """
        Initialize blockchain for a given currency if no source exists locally
        :param str currency:
        :param BlockUID network_blockstamp: the blockstamp of the network
        """

        self._logger.debug("Requesting current block")
        try:
            current_block = await self._bma_connector.get(currency, bma.blockchain.block,
                                                                  req_args={'number': network_blockstamp.number})
            signed_raw = "{0}{1}\n".format(current_block['raw'], current_block['signature'])
            block = Block.from_signed_raw(signed_raw)
            blockchain = self._repo.get_one(currency=currency)
            blockchain.current_buid = block.blockUID
            blockchain.median_time = block.mediantime
            blockchain.current_members_count = block.members_count

            if blockchain.last_ud_time + blockchain.parameters.dt <= blockchain.median_time:
                await self.refresh_dividend_data(currency, blockchain)

            self._repo.update(blockchain)

        except errors.DuniterError as e:
            if e.ucode != errors.NO_CURRENT_BLOCK:
                raise
github duniter / sakia / src / sakia / core / net / node.py View on Github external
async def from_address(cls, currency, address, port, session):
        """
        Factory method to get a node from a given address

        :param str currency: The node currency. None if we don't know\
         the currency it should have, for example if its the first one we add
        :param str address: The node address
        :param int port: The node port
        :return: A new node
        :rtype: sakia.core.net.Node
        """
        peer_data = await bma.network.Peering(ConnectionHandler(address, port)).get(session)

        peer = Peer.from_signed_raw("{0}{1}\n".format(peer_data['raw'],
                                                  peer_data['signature']))

        if currency is not None:
            if peer.currency != currency:
                raise InvalidNodeCurrency(peer.currency, currency)

        node = cls(peer,
                   "", peer.pubkey, None, Node.ONLINE, time.time(),
                   {'root': "", 'leaves': []}, "", "", 0, session)
        logging.debug("Node from address : {:}".format(str(node)))
        return node