async def exec_test():
     value = await referential.localized(units=True, international_system=True)
     self.assertEqual(value, "1.011000 mUD({0}) TC".format(QLocale.toString(
                     QLocale(),
                     QDateTime.fromTime_t(1452663088792).date(),
                     QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                 )))
Beispiel #2
0
    def add_certified_node(self, identity, certified, certification,
                           node_status):
        metadata = {
            'text': certified.uid if certified.uid else certified.pubkey[:12],
            'tooltip': certified.pubkey,
            'identity': certified,
            'status': node_status
        }
        self.nx_graph.add_node(certified.pubkey, attr_dict=metadata)

        arc_status = self.arc_status(certification.timestamp)
        sig_validity = self.blockchain_service.parameters().sig_validity
        arc = {
            'status':
            arc_status,
            'tooltip':
            QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(certification.timestamp +
                                     sig_validity).date(),
                QLocale.dateFormat(QLocale(), QLocale.ShortFormat)),
            'cert_time':
            certification.timestamp,
            'confirmation_text':
            self.confirmation_text(certification.written_on)
        }

        self.nx_graph.add_edge(identity.pubkey,
                               certified.pubkey,
                               attr_dict=arc)
 async def exec_test():
     value = await referential.diff_localized(units=True)
     self.assertEqual(value, "0.101100 UD({0}) TC".format(QLocale.toString(
                     QLocale(),
                     QDateTime.fromTime_t(1452663088792).date(),
                     QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                 )))
Beispiel #4
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_data = self.sourceModel().data(source_index, role)
        expiration_col = self.sourceModel().columns_ids.index('expiration')
        expiration_index = self.sourceModel().index(source_index.row(), expiration_col)
        expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
        current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
        sig_validity = self.community.parameters['sigValidity']
        warning_expiration_time = int(sig_validity / 3)
        #logging.debug("{0} > {1}".format(current_time, expiration_data))
        if expiration_data is not None:
            will_expire_soon = (current_time > expiration_data*1000 - warning_expiration_time*1000)
        if role == Qt.DisplayRole:
            if source_index.column() == self.sourceModel().columns_ids.index('renewed') \
                    or source_index.column() == self.sourceModel().columns_ids.index('expiration'):
                if source_data is not None:
                    return QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(source_data).date(),
                        QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                    )
                else:
                    return ""
            if source_index.column() == self.sourceModel().columns_ids.index('pubkey'):
                return "pub:{0}".format(source_data[:5])

        if role == Qt.ForegroundRole:
            if expiration_data:
                if will_expire_soon:
                    return QColor(Qt.red)
            else:
                return QColor(Qt.blue)
        return source_data
Beispiel #5
0
    def add_certifier_node(self, certifier, identity, certification,
                           node_status):
        sentry_symbol, sentry_text = sentry_display(certifier)
        name_text = certifier.uid if certifier.uid else certifier.pubkey[:12]
        metadata = {
            'text': sentry_symbol + name_text,
            'tooltip': sentry_text + certifier.pubkey,
            'identity': certifier,
            'status': node_status
        }
        self.nx_graph.add_node(certifier.pubkey, attr_dict=metadata)

        arc_status = self.arc_status(certification.timestamp)
        sig_validity = self.blockchain_service.parameters().sig_validity
        expiration = self.blockchain_service.adjusted_ts(
            certification.timestamp + sig_validity)
        arc = {
            'status':
            arc_status,
            'tooltip':
            QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(expiration).date(),
                QLocale.dateFormat(QLocale(), QLocale.ShortFormat)) + " BAT",
            'cert_time':
            certification.timestamp,
            'confirmation_text':
            self.confirmation_text(certification.written_on)
        }
        self.nx_graph.add_edge(certifier.pubkey,
                               identity.pubkey,
                               attr_dict=arc)
Beispiel #6
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                if source_data is not "":
                    amount_ref = self.account.units_to_diff_ref(source_data,
                                                                self.community)
                    # if referential type is quantitative...
                    if self.account.ref_type() == 'q':
                        # display int values
                        return QLocale().toString(float(amount_ref), 'f', 0)
                    else:
                        # display float values
                        return QLocale().toString(amount_ref, 'f', 6)

        if role == Qt.FontRole:
            font = QFont()
            if state_data == Transfer.AWAITING:
                font.setItalic(True)
            elif state_data == Transfer.REFUSED:
                font.setItalic(True)
            elif state_data == Transfer.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == Transfer.REFUSED:
                return QColor(Qt.red)
            elif state_data == Transfer.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)

        return source_data
Beispiel #7
0
 async def exec_test():
     value = await referential.localized(units=True)
     self.assertEqual(
         value, "0.101000 UD({0}) TC".format(
             QLocale.toString(
                 QLocale(),
                 QDateTime.fromTime_t(1452663088792).date(),
                 QLocale.dateFormat(QLocale(), QLocale.ShortFormat))))
Beispiel #8
0
 async def exec_test():
     value = await referential.diff_localized(units=False,
                                              international_system=True)
     self.assertEqual(
         value, "1.011000 mUD({0}) ".format(
             QLocale.toString(
                 QLocale(),
                 QDateTime.fromTime_t(1452663088792).date(),
                 QLocale.dateFormat(QLocale(), QLocale.ShortFormat))))
Beispiel #9
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = self.sourceModel().columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (self.sourceModel().columns_ids.index('renewed'),
                                             self.sourceModel().columns_ids.index('expiration'),
                                             self.sourceModel().columns_ids.index('publication')):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        )
                    else:
                        return ""
                if source_index.column() == self.sourceModel().columns_ids.index('pubkey'):
                    return "pub:{0}".format(source_data[:5])

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                else:
                    return QColor(Qt.blue)
            if role == Qt.DecorationRole and source_index.column() == self.sourceModel().columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Beispiel #10
0
    def add_certifier_list(self, certifier_list, person, person_account):
        """
        Add list of certifiers to graph
        :param list certifier_list: List of certifiers from api
        :param Person person:   Person instance which is certified
        :param Person person_account:   Account person instance
        :return:
        """
        #  add certifiers of uid
        for certifier in tuple(certifier_list):
            # add only valid certification...
            if (time.time() - certifier['cert_time']['medianTime']) > self.signature_validity:
                continue
            # new node
            if certifier['pubkey'] not in self._graph.keys():
                node_status = 0
                if certifier['pubkey'] == person_account.pubkey:
                    node_status += NODE_STATUS_HIGHLIGHTED
                if certifier['isMember'] is False:
                    node_status += NODE_STATUS_OUT
                self._graph[certifier['pubkey']] = {
                    'id': certifier['pubkey'],
                    'arcs': list(),
                    'text': certifier['uid'],
                    'tooltip': certifier['pubkey'],
                    'status': node_status,
                    'connected': [person.pubkey]
                }

            # keep only the latest certification
            if self._graph[certifier['pubkey']]['arcs']:
                if certifier['cert_time']['medianTime'] < self._graph[certifier['pubkey']]['arcs'][0]['cert_time']:
                    continue
            # display validity status
            if (time.time() - certifier['cert_time']['medianTime']) > self.ARC_STATUS_STRONG_time:
                arc_status = ARC_STATUS_WEAK
            else:
                arc_status = ARC_STATUS_STRONG
            arc = {
                'id': person.pubkey,
                'status': arc_status,
                'tooltip': QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(certifier['cert_time']['medianTime'] + self.signature_validity).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                ),
                'cert_time': certifier['cert_time']['medianTime']
            }
            #  add arc to certifier
            self._graph[certifier['pubkey']]['arcs'].append(arc)
            # if certifier node not in person nodes
            if certifier['pubkey'] not in tuple(self._graph[person.pubkey]['connected']):
                # add certifier node to person node
                self._graph[person.pubkey]['connected'].append(certifier['pubkey'])
Beispiel #11
0
    async def add_certified_list(self, certified_list, identity,
                                 account_identity):
        """
        Add list of certified from api to graph
        :param list certified_list: List of certified from api
        :param identity identity:   identity instance which is certifier
        :param identity account_identity:   Account identity instance
        :return:
        """

        if self.community:
            try:
                # add certified by uid
                for certified in tuple(certified_list):
                    node_status = await self.node_status(
                        certified['identity'], account_identity)
                    metadata = {
                        'text': certified['identity'].uid,
                        'tooltip': certified['identity'].pubkey,
                        'status': node_status
                    }
                    self.nx_graph.add_node(certified['identity'].pubkey,
                                           attr_dict=metadata)

                    arc_status = await self.arc_status(certified['cert_time'])
                    sig_validity = (await
                                    self.community.parameters())['sigValidity']
                    arc = {
                        'status':
                        arc_status,
                        'tooltip':
                        QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(certified['cert_time'] +
                                                 sig_validity).date(),
                            QLocale.dateFormat(QLocale(),
                                               QLocale.ShortFormat)),
                        'cert_time':
                        certified['cert_time'],
                        'confirmation_text':
                        self.confirmation_text(certified['block_number'])
                    }

                    self.nx_graph.add_edge(identity.pubkey,
                                           certified['identity'].pubkey,
                                           attr_dict=arc,
                                           weight=len(certified_list))

            except NoPeerAvailable as e:
                logging.debug(str(e))
Beispiel #12
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'date'):
                return QDateTime.fromTime_t(source_data).toString(
                    Qt.SystemLocaleLongDate)
            return None

        return source_data
Beispiel #13
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)
            return None

        return source_data
Beispiel #14
0
    async def diff_localized(self, units=False, international_system=False):
        from . import Relative
        value = await self.differential()
        block = await self.community.get_ud_block(0, self._block_number)
        prefix = ""
        if international_system and value != 0:
            localized_value, prefix = Relative.to_si(value, self.app.preferences['digits_after_comma'])
        else:
            localized_value = QLocale().toString(float(value), 'f', self.app.preferences['digits_after_comma'])

        if units or international_system:
            return QCoreApplication.translate("RelativeToPast", RelativeToPast._REF_STR_)\
                .format(localized_value,
                    prefix,
                    QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(block['medianTime']).date(),
                        QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                    ),
                    self.community.short_currency if units else "")
        else:
            return localized_value
Beispiel #15
0
    async def add_certified_list(self, certified_list, identity, account_identity):
        """
        Add list of certified from api to graph
        :param list certified_list: List of certified from api
        :param identity identity:   identity instance which is certifier
        :param identity account_identity:   Account identity instance
        :return:
        """

        if self.community:
            try:
                # add certified by uid
                for certified in tuple(certified_list):
                    node_status = await self.node_status(certified['identity'], account_identity)
                    metadata = {
                        'text': certified['identity'].uid,
                        'tooltip': certified['identity'].pubkey,
                        'status': node_status
                    }
                    self.nx_graph.add_node(certified['identity'].pubkey, attr_dict=metadata)

                    arc_status = await self.arc_status(certified['cert_time'])
                    sig_validity = (await self.community.parameters())['sigValidity']
                    arc = {
                        'status': arc_status,
                        'tooltip': QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(certified['cert_time'] + sig_validity).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ),
                        'cert_time': certified['cert_time'],
                        'confirmation_text': self.confirmation_text(certified['cert_time'])
                    }

                    self.nx_graph.add_edge(identity.pubkey, certified['identity'].pubkey, attr_dict=arc,
                                           weight=len(certified_list))

            except NoPeerAvailable as e:
                logging.debug(str(e))
Beispiel #16
0
    async def localized(self, units=False, international_system=False):
        from . import Relative
        value = await self.value()
        block = await self.community.get_ud_block()
        prefix = ""
        if international_system:
            localized_value, prefix = Relative.to_si(value, self.app.preferences['digits_after_comma'])
        else:
            localized_value = QLocale().toString(float(value), 'f', self.app.preferences['digits_after_comma'])

        if units or international_system:
            return QCoreApplication.translate("RelativeToPast", RelativeToPast._REF_STR_) \
                .format(localized_value,
                        prefix,
                        QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(block['medianTime']).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ),
                        self.community.short_currency if units else "")
        else:
            return localized_value
Beispiel #17
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        source_data = self.sourceModel().data(source_index, role)
        expiration_col = self.sourceModel().columns_ids.index('expiration')
        expiration_index = self.sourceModel().index(source_index.row(),
                                                    expiration_col)
        expiration_data = self.sourceModel().data(expiration_index,
                                                  Qt.DisplayRole)
        current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
        sig_validity = self.community.parameters['sigValidity']
        warning_expiration_time = int(sig_validity / 3)
        #logging.debug("{0} > {1}".format(current_time, expiration_data))
        if expiration_data is not None:
            will_expire_soon = (current_time > expiration_data * 1000 -
                                warning_expiration_time * 1000)
        if role == Qt.DisplayRole:
            if source_index.column() == self.sourceModel().columns_ids.index('renewed') \
                    or source_index.column() == self.sourceModel().columns_ids.index('expiration'):
                if source_data is not None:
                    return QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(source_data).date(),
                        QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
                else:
                    return ""
            if source_index.column() == self.sourceModel().columns_ids.index(
                    'pubkey'):
                return "pub:{0}".format(source_data[:5])

        if role == Qt.ForegroundRole:
            if expiration_data:
                if will_expire_soon:
                    return QColor(Qt.red)
            else:
                return QColor(Qt.blue)
        return source_data
Beispiel #18
0
    def refresh(self):
        parameters = self.community.parameters
        last_renewal = ""
        expiration = ""
        try:
            person = Person.lookup(self.account.pubkey, self.community)
            membership = person.membership(self.community)
            renew_block = membership['blockNumber']
            last_renewal = self.community.get_block(renew_block).mediantime
            expiration = last_renewal + parameters['sigValidity']
        except MembershipNotFoundError:
            last_renewal = None
            expiration = None

        certified = person.unique_valid_certified_by(self.community)
        certifiers = person.unique_valid_certifiers_of(self.community)
        if last_renewal and expiration:
            date_renewal = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(last_renewal).date(), QLocale.dateFormat(QLocale(), QLocale.LongFormat)
            )
            date_expiration = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(expiration).date(), QLocale.dateFormat(QLocale(), QLocale.LongFormat)
            )
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Membership"),
                    self.tr("Last renewal on {:}, expiration on {:}").format(date_renewal, date_expiration),
                    self.tr("Your web of trust"),
                    self.tr("Certified by {:} members; Certifier of {:} members").format(len(certifiers),
                                                                                             len(certified))
                )
            )
        else:
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Not a member"),
                    self.tr("Your web of trust"),
                    self.tr("Certified by {:} members; Certifier of {:} members").format(len(certifiers),
                                                                                             len(certified))
                )
            )

        amount = self.account.amount(self.community)
        maximum = self.community.monetary_mass
        # if referential type is quantitative...
        if self.account.ref_type() == 'q':
            # display int values
            localized_amount = QLocale().toString(float(self.get_referential_value(amount)), 'f', 0)
            localized_minimum = QLocale().toString(float(self.get_referential_value(0)), 'f', 0)
            localized_maximum = QLocale().toString(float(self.get_referential_value(maximum)), 'f', 0)
        else:
            # display float values
            localized_amount = QLocale().toString(float(self.get_referential_value(amount)), 'f', 6)
            localized_minimum = QLocale().toString(float(self.get_referential_value(0)), 'f', 6)
            localized_maximum = QLocale().toString(float(self.get_referential_value(maximum)), 'f', 6)

        # set infos in label
        self.label_balance.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                self.tr("Your money share "),
                self.tr("{:.2f}%").format(amount / maximum * 100) if maximum != 0 else "0%",
                self.tr("Your part "),
                self.tr("{:} {:} in [{:} ; {:}] {:}")
                .format(
                    localized_amount,
                    self.get_referential_name(),
                    localized_minimum,
                    localized_maximum,
                    self.get_referential_name()
                )
            )
        )

        wallets_model = WalletsTableModel(self.account, self.community)
        proxy_model = WalletsFilterProxyModel()
        proxy_model.setSourceModel(wallets_model)
        wallets_model.dataChanged.connect(self.wallet_changed)
        self.table_wallets.setModel(proxy_model)
        self.table_wallets.resizeColumnsToContents()
Beispiel #19
0
    async def refresh_informations_frame(self):
        parameters = self.community.parameters
        try:
            identity = await self.account.identity(self.community)
            membership = identity.membership(self.community)
            renew_block = membership['blockNumber']
            last_renewal = self.community.get_block(renew_block)['medianTime']
            expiration = last_renewal + parameters['sigValidity']
        except MembershipNotFoundError:
            last_renewal = None
            expiration = None

        certified = await identity.unique_valid_certified_by(
            self.app.identities_registry, self.community)
        certifiers = await identity.unique_valid_certifiers_of(
            self.app.identities_registry, self.community)
        if last_renewal and expiration:
            date_renewal = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(last_renewal).date(),
                QLocale.dateFormat(QLocale(), QLocale.LongFormat))
            date_expiration = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(expiration).date(),
                QLocale.dateFormat(QLocale(), QLocale.LongFormat))

            if self.account.pubkey in self.community.members_pubkeys():
                # set infos in label
                self.label_general.setText(
                    self.tr("""
                    <table cellpadding="5">
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    </table>
                    """).format(
                        self.account.name, self.account.pubkey,
                        self.tr("Membership"),
                        self.tr(
                            "Last renewal on {:}, expiration on {:}").format(
                                date_renewal, date_expiration),
                        self.tr("Your web of trust"),
                        self.
                        tr("Certified by {:} members; Certifier of {:} members"
                           ).format(len(certifiers), len(certified))))
            else:
                # set infos in label
                self.label_general.setText(
                    self.tr("""
                    <table cellpadding="5">
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    </table>
                    """).format(
                        self.account.name, self.account.pubkey,
                        self.tr("Not a member"),
                        self.tr(
                            "Last renewal on {:}, expiration on {:}").format(
                                date_renewal, date_expiration),
                        self.tr("Your web of trust"),
                        self.
                        tr("Certified by {:} members; Certifier of {:} members"
                           ).format(len(certifiers), len(certified))))
        else:
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Not a member"), self.tr("Your web of trust"),
                    self.tr(
                        "Certified by {:} members; Certifier of {:} members").
                    format(len(certifiers), len(certified))))
Beispiel #20
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = IdentitiesTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_UNKNOWN = 2
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data == 0:
                status = STATUS_UNKNOWN
            elif expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (IdentitiesTableModel.columns_ids.index('renewed'),
                                             IdentitiesTableModel.columns_ids.index('expiration')):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        ) + " BAT"
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('pubkey'):
                    return source_data
                if source_index.column() == IdentitiesTableModel.columns_ids.index('block'):
                    return str(source_data)[:20]

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                elif status == STATUS_UNKNOWN:
                    return QColor(Qt.black)
                else:
                    return QColor(Qt.blue)

            if role == Qt.FontRole and status == STATUS_UNKNOWN:
                font = QFont()
                font.setItalic(True)
                return font

            if role == Qt.DecorationRole and source_index.column() == IdentitiesTableModel.columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Beispiel #21
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = IdentitiesTableModel.columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_UNKNOWN = 2
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index, Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data == 0:
                status = STATUS_UNKNOWN
            elif expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data*1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data*1000) - (warning_expiration_time*1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (IdentitiesTableModel.columns_ids.index('renewed'),
                                             IdentitiesTableModel.columns_ids.index('expiration')):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        )
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('publication'):
                    if source_data:
                        ts = self.blockchain_processor.adjusted_ts(self.app.currency, source_data)
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(ts),
                            QLocale.dateTimeFormat(QLocale(), QLocale.LongFormat)
                        )
                    else:
                        return ""
                if source_index.column() == IdentitiesTableModel.columns_ids.index('pubkey'):
                    return source_data
                if source_index.column() == IdentitiesTableModel.columns_ids.index('block'):
                    return str(source_data)[:20]

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                elif status == STATUS_UNKNOWN:
                    return QColor(Qt.black)
                else:
                    return QColor(Qt.blue)

            if role == Qt.FontRole and status == STATUS_UNKNOWN:
                font = QFont()
                font.setItalic(True)
                return font

            if role == Qt.DecorationRole and source_index.column() == IdentitiesTableModel.columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Beispiel #22
0
    def add_certified_list(self, certified_list, identity, identity_account):
        """
        Add list of certified from api to graph
        :param list certified_list: List of certified from api
        :param identity identity:   identity instance which is certifier
        :param identity identity_account:   Account identity instance
        :return:
        """

        if self.community:
            try:
                yield from self.refresh_signature_validity()
                # add certified by uid
                for certified in tuple(certified_list):
                    # add only valid certification...
                    if (time.time() - certified['cert_time']) > self.signature_validity:
                        continue
                    if certified['identity'].pubkey not in self._graph.keys():
                        node_status = 0
                        is_member = yield from certified['identity'].is_member(self.community)
                        if certified['identity'].pubkey == identity_account.pubkey:
                            node_status += NODE_STATUS_HIGHLIGHTED
                        if is_member is False:
                            node_status += NODE_STATUS_OUT
                        self._graph[certified['identity'].pubkey] = {
                            'id': certified['identity'].pubkey,
                            'arcs': list(),
                            'text': certified['identity'].uid,
                            'tooltip': certified['identity'].pubkey,
                            'status': node_status,
                            'connected': [identity.pubkey]
                        }
                    # display validity status
                    if (time.time() - certified['cert_time']) > self.ARC_STATUS_STRONG_time:
                        arc_status = ARC_STATUS_WEAK
                    else:
                        arc_status = ARC_STATUS_STRONG
                    arc = {
                        'id': certified['identity'].pubkey,
                        'status': arc_status,
                        'tooltip': QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(certified['cert_time'] + self.signature_validity).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ),
                        'cert_time': certified['cert_time']
                    }

                    current_block_number = self.community.network.current_blockid.number
                    if current_block_number and certified['block_number']:
                        current_confirmations = current_block_number - certified['block_number'] + 1
                    else:
                        current_confirmations = 0
                    members_pubkeys = yield from self.community.members_pubkeys()
                    max_confirmations = self.community.network.fork_window(members_pubkeys) + 1

                    if max_confirmations > current_confirmations >= 0:
                        if self.app.preferences['expert_mode']:
                            arc['confirmation_text'] = "{0}/{1}".format(current_confirmations,
                                                                      max_confirmations)
                        else:
                            confirmation = current_confirmations / max_confirmations * 100
                            confirmation = 100 if confirmation > 100 else confirmation
                            arc['confirmation_text'] = "{0} %".format(QLocale().toString(float(confirmation), 'f', 0))
                    else:
                        arc['confirmation_text'] = None

                    # replace old arc if this one is more recent
                    new_arc = True
                    index = 0
                    for a in self._graph[identity.pubkey]['arcs']:
                        # if same arc already exists...
                        if a['id'] == arc['id']:
                            # if arc more recent, dont keep old one...
                            if arc['cert_time'] >= a['cert_time']:
                                self._graph[identity.pubkey]['arcs'][index] = arc
                            new_arc = False
                        index += 1

                    #  if arc not in graph...
                    if new_arc:
                        # add arc in graph
                        self._graph[identity.pubkey]['arcs'].append(arc)
                    # if certified node not in identity nodes
                    if certified['identity'].pubkey not in tuple(self._graph[identity.pubkey]['connected']):
                        # add certified node to identity node
                        self._graph[identity.pubkey]['connected'].append(certified['identity'].pubkey)
            except NoPeerAvailable as e:
                logging.debug(str(e))
Beispiel #23
0
    def add_certifier_list(self, certifier_list, identity, identity_account):
        """
        Add list of certifiers to graph
        :param list certifier_list: List of certifiers from api
        :param identity identity:   identity instance which is certified
        :param identity identity_account:   Account identity instance
        :return:
        """
        if self.community:
            try:
                yield from self.refresh_signature_validity()
                #  add certifiers of uid
                for certifier in tuple(certifier_list):
                    # add only valid certification...
                    if (time.time() - certifier['cert_time']) > self.signature_validity:
                        continue
                    # new node
                    if certifier['identity'].pubkey not in self._graph.keys():
                        node_status = 0
                        is_member = yield from certifier['identity'].is_member(self.community)
                        if certifier['identity'].pubkey == identity_account.pubkey:
                            node_status += NODE_STATUS_HIGHLIGHTED
                        if is_member is False:
                            node_status += NODE_STATUS_OUT
                        self._graph[certifier['identity'].pubkey] = {
                            'id': certifier['identity'].pubkey,
                            'arcs': list(),
                            'text': certifier['identity'].uid,
                            'tooltip': certifier['identity'].pubkey,
                            'status': node_status,
                            'connected': [identity.pubkey]
                        }

                    # keep only the latest certification
                    if self._graph[certifier['identity'].pubkey]['arcs']:
                        if certifier['cert_time'] < self._graph[certifier['identity'].pubkey]['arcs'][0]['cert_time']:
                            continue
                    # display validity status
                    if (time.time() - certifier['cert_time']) > self.ARC_STATUS_STRONG_time:
                        arc_status = ARC_STATUS_WEAK
                    else:
                        arc_status = ARC_STATUS_STRONG

                    arc = {
                        'id': identity.pubkey,
                        'status': arc_status,
                        'tooltip': QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(certifier['cert_time'] + self.signature_validity).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                        ),
                        'cert_time': certifier['cert_time']
                    }

                    current_block_number = self.community.network.current_blockid.number
                    if current_block_number and certifier['block_number']:
                        current_confirmations = current_block_number - certifier['block_number'] + 1
                    else:
                        current_confirmations = 0
                    members_pubkeys = yield from self.community.members_pubkeys()
                    max_confirmation = self.community.network.fork_window(members_pubkeys) + 1

                    # Current confirmation can be negative if self.community.network.current_blockid.number
                    # is not refreshed yet
                    if max_confirmation > current_confirmations >= 0:
                        if self.app.preferences['expert_mode']:
                            arc['confirmation_text'] = "{0}/{1}".format(current_confirmations,
                                                                      max_confirmation)
                        else:
                            confirmation = current_confirmations / max_confirmation * 100
                            arc['confirmation_text'] = "{0} %".format(QLocale().toString(float(confirmation), 'f', 0))
                    else:
                        arc['confirmation_text'] = None

                    #  add arc to certifier
                    self._graph[certifier['identity'].pubkey]['arcs'].append(arc)
                    # if certifier node not in identity nodes
                    if certifier['identity'].pubkey not in tuple(self._graph[identity.pubkey]['connected']):
                        # add certifier node to identity node
                        self._graph[identity.pubkey]['connected'].append(certifier['identity'].pubkey)
            except NoPeerAvailable as e:
                logging.debug(str(e))
Beispiel #24
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        if source_index.isValid():
            source_data = self.sourceModel().data(source_index, role)
            expiration_col = self.sourceModel().columns_ids.index('expiration')
            expiration_index = self.sourceModel().index(
                source_index.row(), expiration_col)

            STATUS_NOT_MEMBER = 0
            STATUS_MEMBER = 1
            STATUS_EXPIRE_SOON = 3
            status = STATUS_NOT_MEMBER
            expiration_data = self.sourceModel().data(expiration_index,
                                                      Qt.DisplayRole)
            current_time = QDateTime().currentDateTime().toMSecsSinceEpoch()
            sig_validity = self.sourceModel().sig_validity()
            warning_expiration_time = int(sig_validity / 3)
            #logging.debug("{0} > {1}".format(current_time, expiration_data))

            if expiration_data is not None:
                status = STATUS_MEMBER
                if current_time > (expiration_data * 1000):
                    status = STATUS_NOT_MEMBER
                elif current_time > ((expiration_data * 1000) -
                                     (warning_expiration_time * 1000)):
                    status = STATUS_EXPIRE_SOON

            if role == Qt.DisplayRole:
                if source_index.column() in (
                        self.sourceModel().columns_ids.index('renewed'),
                        self.sourceModel().columns_ids.index('expiration')):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(),
                            QDateTime.fromTime_t(source_data).date(),
                            QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
                    else:
                        return ""
                if source_index.column() == self.sourceModel(
                ).columns_ids.index('publication'):
                    if source_data is not None:
                        return QLocale.toString(
                            QLocale(), QDateTime.fromTime_t(source_data),
                            QLocale.dateTimeFormat(QLocale(),
                                                   QLocale.LongFormat))
                    else:
                        return ""
                if source_index.column() == self.sourceModel(
                ).columns_ids.index('pubkey'):
                    return "pub:{0}".format(source_data[:5])

            if role == Qt.ForegroundRole:
                if status == STATUS_EXPIRE_SOON:
                    return QColor("darkorange").darker(120)
                elif status == STATUS_NOT_MEMBER:
                    return QColor(Qt.red)
                else:
                    return QColor(Qt.blue)
            if role == Qt.DecorationRole and source_index.column(
            ) == self.sourceModel().columns_ids.index('uid'):
                if status == STATUS_NOT_MEMBER:
                    return QIcon(":/icons/not_member")
                elif status == STATUS_MEMBER:
                    return QIcon(":/icons/member")
                elif status == STATUS_EXPIRE_SOON:
                    return QIcon(":/icons/member_warning")

            return source_data
Beispiel #25
0
    def data(self, index, role):
        row = index.row()
        col = index.column()

        if not index.isValid():
            return QVariant()

        source_data = self.transfers_data[row][col]
        state_data = self.transfers_data[row][
            HistoryTableModel.columns_types.index('state')]
        block_data = self.transfers_data[row][
            HistoryTableModel.columns_types.index('block_number')]

        if state_data == Transaction.VALIDATED and block_data:
            current_confirmations = self.blockchain_processor.current_buid(
                self.app.currency).number - block_data
        else:
            current_confirmations = 0

        if role == Qt.DisplayRole:
            if col == HistoryTableModel.columns_types.index('pubkey'):
                return "<p>" + source_data.replace('\n', "<br>") + "</p>"
            if col == HistoryTableModel.columns_types.index('date'):
                ts = self.blockchain_processor.adjusted_ts(
                    self.connection.currency, source_data)
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(ts).date(),
                    QLocale.dateFormat(QLocale(),
                                       QLocale.ShortFormat)) + " BAT"
            if col == HistoryTableModel.columns_types.index('amount'):
                amount = self.app.current_ref.instance(
                    source_data, self.connection.currency, self.app,
                    block_data).diff_localized(False, False)
                return amount
            return source_data

        if role == Qt.FontRole:
            font = QFont()
            if state_data == Transaction.AWAITING or \
                    (state_data == Transaction.VALIDATED and current_confirmations < MAX_CONFIRMATIONS):
                font.setItalic(True)
            elif state_data == Transaction.REFUSED:
                font.setItalic(True)
            elif state_data == Transaction.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            color = None
            if state_data == Transaction.REFUSED:
                color = QColor(Qt.darkGray)
            elif state_data == Transaction.TO_SEND:
                color = QColor(Qt.blue)
            if col == HistoryTableModel.columns_types.index('amount'):
                if source_data < 0:
                    color = QColor(Qt.darkRed)
                elif state_data == HistoryTableModel.DIVIDEND:
                    color = QColor(Qt.darkBlue)
            if state_data == Transaction.AWAITING or \
                    (state_data == Transaction.VALIDATED and current_confirmations == 0):
                color = QColor("#ffb000")
            if color:
                if self.app.parameters.dark_theme:
                    return color.lighter(300)
                else:
                    return color

        if role == Qt.TextAlignmentRole:
            if HistoryTableModel.columns_types.index('amount'):
                return Qt.AlignRight | Qt.AlignVCenter
            if col == HistoryTableModel.columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if col == HistoryTableModel.columns_types.index('date'):
                ts = self.blockchain_processor.adjusted_ts(
                    self.connection.currency, source_data)
                return QDateTime.fromTime_t(ts).toString(
                    Qt.SystemLocaleLongDate)

            if state_data == Transaction.VALIDATED or state_data == Transaction.AWAITING:
                if current_confirmations >= MAX_CONFIRMATIONS:
                    return None
                elif self.app.parameters.expert_mode:
                    return self.tr("{0} / {1} confirmations").format(
                        current_confirmations, MAX_CONFIRMATIONS)
                else:
                    confirmation = current_confirmations / MAX_CONFIRMATIONS * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(
                        QLocale().toString(float(confirmation), 'f', 0))
Beispiel #26
0
    def add_certified_list(self, certified_list, person, person_account):
        """
        Add list of certified from api to graph
        :param list certified_list: List of certified from api
        :param Person person:   Person instance which is certifier
        :param Person person_account:   Account person instance
        :return:
        """
        # add certified by uid
        for certified in tuple(certified_list):
            # add only valid certification...
            if (time.time() - certified['cert_time']['medianTime']) > self.signature_validity:
                continue
            if certified['pubkey'] not in self._graph.keys():
                node_status = 0
                if certified['pubkey'] == person_account.pubkey:
                    node_status += NODE_STATUS_HIGHLIGHTED
                if certified['isMember'] is False:
                    node_status += NODE_STATUS_OUT
                self._graph[certified['pubkey']] = {
                    'id': certified['pubkey'],
                    'arcs': list(),
                    'text': certified['uid'],
                    'tooltip': certified['pubkey'],
                    'status': node_status,
                    'connected': [person.pubkey]
                }
            # display validity status
            if (time.time() - certified['cert_time']['medianTime']) > self.ARC_STATUS_STRONG_time:
                arc_status = ARC_STATUS_WEAK
            else:
                arc_status = ARC_STATUS_STRONG
            arc = {
                'id': certified['pubkey'],
                'status': arc_status,
                'tooltip': QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(certified['cert_time']['medianTime'] + self.signature_validity).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                ),
                'cert_time': certified['cert_time']['medianTime']
            }

            # replace old arc if this one is more recent
            new_arc = True
            index = 0
            for a in self._graph[person.pubkey]['arcs']:
                # if same arc already exists...
                if a['id'] == arc['id']:
                    # if arc more recent, dont keep old one...
                    if arc['cert_time'] >= a['cert_time']:
                        self._graph[person.pubkey]['arcs'][index] = arc
                    new_arc = False
                index += 1

            #  if arc not in graph...
            if new_arc:
                # add arc in graph
                self._graph[person.pubkey]['arcs'].append(arc)
            # if certified node not in person nodes
            if certified['pubkey'] not in tuple(self._graph[person.pubkey]['connected']):
                # add certified node to person node
                self._graph[person.pubkey]['connected'].append(certified['pubkey'])
Beispiel #27
0
    def refresh_informations_frame(self):
        parameters = self.community.parameters
        try:
            identity = yield from self.account.identity(self.community)
            membership = identity.membership(self.community)
            renew_block = membership['blockNumber']
            last_renewal = self.community.get_block(renew_block)['medianTime']
            expiration = last_renewal + parameters['sigValidity']
        except MembershipNotFoundError:
            last_renewal = None
            expiration = None

        certified = yield from identity.unique_valid_certified_by(self.app.identities_registry, self.community)
        certifiers = yield from identity.unique_valid_certifiers_of(self.app.identities_registry, self.community)
        if last_renewal and expiration:
            date_renewal = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(last_renewal).date(), QLocale.dateFormat(QLocale(), QLocale.LongFormat)
            )
            date_expiration = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(expiration).date(), QLocale.dateFormat(QLocale(), QLocale.LongFormat)
            )

            if self.account.pubkey in self.community.members_pubkeys():
                # set infos in label
                self.label_general.setText(
                    self.tr("""
                    <table cellpadding="5">
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    </table>
                    """).format(
                        self.account.name, self.account.pubkey,
                        self.tr("Membership"),
                        self.tr("Last renewal on {:}, expiration on {:}").format(date_renewal, date_expiration),
                        self.tr("Your web of trust"),
                        self.tr("Certified by {:} members; Certifier of {:} members").format(len(certifiers),
                                                                                             len(certified))
                    )
                )
            else:
                # set infos in label
                self.label_general.setText(
                    self.tr("""
                    <table cellpadding="5">
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                    </table>
                    """).format(
                        self.account.name, self.account.pubkey,
                        self.tr("Not a member"),
                        self.tr("Last renewal on {:}, expiration on {:}").format(date_renewal, date_expiration),
                        self.tr("Your web of trust"),
                        self.tr("Certified by {:} members; Certifier of {:} members").format(len(certifiers),
                                                                                             len(certified))
                    )
                )
        else:
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Not a member"),
                    self.tr("Your web of trust"),
                    self.tr("Certified by {:} members; Certifier of {:} members").format(len(certifiers),
                                                                                         len(certified))
                )
            )
Beispiel #28
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                )
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            if state_data == TransferState.AWAITING or state_data == TransferState.VALIDATING:
                font.setItalic(True)
            elif state_data == TransferState.REFUSED:
                font.setItalic(True)
            elif state_data == TransferState.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel().columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(Qt.SystemLocaleLongDate)

            if state_data == TransferState.VALIDATING or state_data == TransferState.AWAITING:
                block_col = model.columns_types.index('block_number')
                block_index = model.index(source_index.row(), block_col)
                block_data = model.data(block_index, Qt.DisplayRole)

                current_confirmations = 0
                if state_data == TransferState.VALIDATING:
                    current_blockid_number = self.community.network.current_blockid.number
                    if current_blockid_number:
                        current_confirmations = current_blockid_number - block_data
                elif state_data == TransferState.AWAITING:
                    current_confirmations = 0

                max_confirmations = self.sourceModel().max_confirmations()

                if self.app.preferences['expert_mode']:
                    return self.tr("{0} / {1} confirmations").format(current_confirmations, max_confirmations)
                else:
                    confirmation = current_confirmations / max_confirmations * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(QLocale().toString(float(confirmation), 'f', 0))

            return None

        return source_data
Beispiel #29
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)

        block_col = model.columns_types.index('block_number')
        block_index = model.index(source_index.row(), block_col)
        block_data = model.data(block_index, Qt.DisplayRole)

        if state_data == Transaction.VALIDATED and block_data:
            current_confirmations = self.blockchain_service.current_buid(
            ).number - block_data
        else:
            current_confirmations = 0

        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
            if source_index.column() == model.columns_types.index('amount'):
                amount = self.app.current_ref.instance(
                    source_data, model.connection.currency, self.app,
                    block_data).diff_localized(False, False)
                return amount

        if role == Qt.FontRole:
            font = QFont()
            if state_data == Transaction.AWAITING or \
                    (state_data == Transaction.VALIDATED and current_confirmations < MAX_CONFIRMATIONS):
                font.setItalic(True)
            elif state_data == Transaction.REFUSED:
                font.setItalic(True)
            elif state_data == Transaction.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == Transaction.REFUSED:
                return QColor(Qt.darkGray)
            elif state_data == Transaction.TO_SEND:
                return QColor(Qt.blue)
            if source_index.column() == model.columns_types.index('amount'):
                if source_data < 0:
                    return QColor(Qt.darkRed)
                elif state_data == HistoryTableModel.DIVIDEND:
                    return QColor(Qt.darkBlue)

        if role == Qt.TextAlignmentRole:
            if self.sourceModel().columns_types.index('amount'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == model.columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == model.columns_types.index('date'):
                return QDateTime.fromTime_t(source_data).toString(
                    Qt.SystemLocaleLongDate)

            if state_data == Transaction.VALIDATED or state_data == Transaction.AWAITING:
                if current_confirmations >= MAX_CONFIRMATIONS:
                    return None
                elif self.app.parameters.expert_mode:
                    return self.tr("{0} / {1} confirmations").format(
                        current_confirmations, MAX_CONFIRMATIONS)
                else:
                    confirmation = current_confirmations / MAX_CONFIRMATIONS * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(
                        QLocale().toString(float(confirmation), 'f', 0))

            return None
        return source_data
Beispiel #30
0
    def data(self, index, role):
        source_index = self.mapToSource(index)
        model = self.sourceModel()
        source_data = model.data(source_index, role)
        state_col = model.columns_types.index('state')
        state_index = model.index(source_index.row(), state_col)
        state_data = model.data(state_index, Qt.DisplayRole)
        if role == Qt.DisplayRole:
            if source_index.column() == model.columns_types.index('uid'):
                return source_data
            if source_index.column() == model.columns_types.index('date'):
                return QLocale.toString(
                    QLocale(),
                    QDateTime.fromTime_t(source_data).date(),
                    QLocale.dateFormat(QLocale(), QLocale.ShortFormat))
            if source_index.column() == model.columns_types.index('payment') or \
                    source_index.column() == model.columns_types.index('deposit'):
                return source_data

        if role == Qt.FontRole:
            font = QFont()
            if state_data == TransferState.AWAITING or state_data == TransferState.VALIDATING:
                font.setItalic(True)
            elif state_data == TransferState.REFUSED:
                font.setItalic(True)
            elif state_data == TransferState.TO_SEND:
                font.setBold(True)
            else:
                font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            if state_data == TransferState.REFUSED:
                return QColor(Qt.red)
            elif state_data == TransferState.TO_SEND:
                return QColor(Qt.blue)

        if role == Qt.TextAlignmentRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'deposit') or source_index.column() == self.sourceModel(
                    ).columns_types.index('payment'):
                return Qt.AlignRight | Qt.AlignVCenter
            if source_index.column() == self.sourceModel().columns_types.index(
                    'date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if source_index.column() == self.sourceModel().columns_types.index(
                    'date'):
                return QDateTime.fromTime_t(source_data).toString(
                    Qt.SystemLocaleLongDate)

            if state_data == TransferState.VALIDATING or state_data == TransferState.AWAITING:
                block_col = model.columns_types.index('block_number')
                block_index = model.index(source_index.row(), block_col)
                block_data = model.data(block_index, Qt.DisplayRole)

                current_confirmations = 0
                if state_data == TransferState.VALIDATING:
                    current_blockUID_number = self.community.network.current_blockUID.number
                    if current_blockUID_number:
                        current_confirmations = current_blockUID_number - block_data
                elif state_data == TransferState.AWAITING:
                    current_confirmations = 0

                max_confirmations = self.sourceModel().max_confirmations()

                if self.app.preferences['expert_mode']:
                    return self.tr("{0} / {1} confirmations").format(
                        current_confirmations, max_confirmations)
                else:
                    confirmation = current_confirmations / max_confirmations * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(
                        QLocale().toString(float(confirmation), 'f', 0))

            return None
        return source_data
Beispiel #31
0
    def refresh(self):
        parameters = self.community.parameters
        last_renewal = ""
        expiration = ""
        try:
            person = Person.lookup(self.account.pubkey, self.community)
            membership = person.membership(self.community)
            renew_block = membership['blockNumber']
            last_renewal = self.community.get_block(renew_block).mediantime
            expiration = last_renewal + parameters['sigValidity']
        except MembershipNotFoundError:
            last_renewal = None
            expiration = None

        certified = person.unique_valid_certified_by(self.community)
        certifiers = person.unique_valid_certifiers_of(self.community)
        if last_renewal and expiration:
            date_renewal = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(last_renewal).date(),
                QLocale.dateFormat(QLocale(), QLocale.LongFormat))
            date_expiration = QLocale.toString(
                QLocale(),
                QDateTime.fromTime_t(expiration).date(),
                QLocale.dateFormat(QLocale(), QLocale.LongFormat))
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Membership"),
                    self.tr("Last renewal on {:}, expiration on {:}").format(
                        date_renewal, date_expiration),
                    self.tr("Your web of trust"),
                    self.tr(
                        "Certified by {:} members; Certifier of {:} members").
                    format(len(certifiers), len(certified))))
        else:
            # set infos in label
            self.label_general.setText(
                self.tr("""
                <table cellpadding="5">
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                <tr><td align="right"><b>{:}</b></td></tr>
                <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
                </table>
                """).format(
                    self.account.name, self.account.pubkey,
                    self.tr("Not a member"), self.tr("Your web of trust"),
                    self.tr(
                        "Certified by {:} members; Certifier of {:} members").
                    format(len(certifiers), len(certified))))

        amount = self.account.amount(self.community)
        maximum = self.community.monetary_mass
        # if referential type is quantitative...
        if self.account.ref_type() == 'q':
            # display int values
            localized_amount = QLocale().toString(
                float(self.get_referential_value(amount)), 'f', 0)
            localized_minimum = QLocale().toString(
                float(self.get_referential_value(0)), 'f', 0)
            localized_maximum = QLocale().toString(
                float(self.get_referential_value(maximum)), 'f', 0)
        else:
            # display float values
            localized_amount = QLocale().toString(
                float(self.get_referential_value(amount)), 'f', 6)
            localized_minimum = QLocale().toString(
                float(self.get_referential_value(0)), 'f', 6)
            localized_maximum = QLocale().toString(
                float(self.get_referential_value(maximum)), 'f', 6)

        # set infos in label
        self.label_balance.setText(
            self.tr("""
            <table cellpadding="5">
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            <tr><td align="right"><b>{:}</b></td><td>{:}</td></tr>
            </table>
            """).format(
                self.tr("Your money share "),
                self.tr("{:.2f}%").format(amount / maximum *
                                          100) if maximum != 0 else "0%",
                self.tr("Your part "),
                self.tr("{:} {:} in [{:} ; {:}] {:}").format(
                    localized_amount, self.get_referential_name(),
                    localized_minimum, localized_maximum,
                    self.get_referential_name())))

        wallets_model = WalletsTableModel(self.account, self.community)
        proxy_model = WalletsFilterProxyModel()
        proxy_model.setSourceModel(wallets_model)
        wallets_model.dataChanged.connect(self.wallet_changed)
        self.table_wallets.setModel(proxy_model)
        self.table_wallets.resizeColumnsToContents()
Beispiel #32
0
    def data(self, index, role):
        row = index.row()
        col = index.column()

        if not index.isValid():
            return QVariant()

        source_data = self.transfers_data[row][col]
        txhash_data = self.transfers_data[row][HistoryTableModel.columns_types.index('txhash')]
        state_data = self.transfers_data[row][HistoryTableModel.columns_types.index('state')]
        block_data = self.transfers_data[row][HistoryTableModel.columns_types.index('block_number')]

        if state_data == Transaction.VALIDATED and block_data:
            current_confirmations = self.blockchain_processor.current_buid(self.app.currency).number - block_data
        else:
            current_confirmations = 0

        if role == Qt.DisplayRole:
            if col == HistoryTableModel.columns_types.index('pubkey'):
                return "<p>" + source_data.replace('\n', "<br>") + "</p>"
            if col == HistoryTableModel.columns_types.index('date'):
                if txhash_data == STOPLINE_HASH:
                    return ""
                else:
                    ts = self.blockchain_processor.adjusted_ts(self.connection.currency, source_data)
                    return QLocale.toString(
                        QLocale(),
                        QDateTime.fromTime_t(ts).date(),
                        QLocale.dateFormat(QLocale(), QLocale.ShortFormat)
                    ) + " BAT"
            if col == HistoryTableModel.columns_types.index('amount'):
                if txhash_data == STOPLINE_HASH:
                    return ""
                else:
                    amount = self.app.current_ref.instance(source_data, self.connection.currency,
                                                           self.app, block_data).diff_localized(False, False)
                    return amount

            return source_data

        if role == Qt.FontRole:
            font = QFont()
            if txhash_data == STOPLINE_HASH:
                font.setItalic(True)
            else:
                if state_data == Transaction.AWAITING or \
                        (state_data == Transaction.VALIDATED and current_confirmations < MAX_CONFIRMATIONS):
                    font.setItalic(True)
                elif state_data == Transaction.REFUSED:
                    font.setItalic(True)
                elif state_data == Transaction.TO_SEND:
                    font.setBold(True)
                else:
                    font.setItalic(False)
            return font

        if role == Qt.ForegroundRole:
            color = None
            if state_data == Transaction.REFUSED:
                color = QColor(Qt.darkGray)
            elif state_data == Transaction.TO_SEND:
                color = QColor(Qt.blue)
            if col == HistoryTableModel.columns_types.index('amount'):
                if source_data < 0:
                    color = QColor(Qt.darkRed)
                elif state_data == HistoryTableModel.DIVIDEND:
                    color = QColor(Qt.darkBlue)
            if state_data == Transaction.AWAITING or \
                    (state_data == Transaction.VALIDATED and current_confirmations == 0):
                color = QColor("#ffb000")
            if color:
                if self.app.parameters.dark_theme:
                    return color.lighter(300)
                else:
                    return color

        if role == Qt.TextAlignmentRole:
            if HistoryTableModel.columns_types.index('amount'):
                return Qt.AlignRight | Qt.AlignVCenter
            if col == HistoryTableModel.columns_types.index('date'):
                return Qt.AlignCenter

        if role == Qt.ToolTipRole:
            if col == HistoryTableModel.columns_types.index('date'):
                ts = self.blockchain_processor.adjusted_ts(self.connection.currency, source_data)
                return QDateTime.fromTime_t(ts).toString(Qt.SystemLocaleLongDate)

            if state_data == Transaction.VALIDATED or state_data == Transaction.AWAITING:
                if current_confirmations >= MAX_CONFIRMATIONS:
                    return None
                elif self.app.parameters.expert_mode:
                    return self.tr("{0} / {1} confirmations").format(current_confirmations, MAX_CONFIRMATIONS)
                else:
                    confirmation = current_confirmations / MAX_CONFIRMATIONS * 100
                    confirmation = 100 if confirmation > 100 else confirmation
                    return self.tr("Confirming... {0} %").format(QLocale().toString(float(confirmation), 'f', 0))