예제 #1
0
 def __init__(self, parent):
     QAbstractItemModel.__init__(self, parent)
     Logger.__init__(self)
     self.parent = parent
     self.view = None  # type: DiceHistoryList
     self.transactions = OrderedDictWithIndex()
     self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
     self.summary = None
예제 #2
0
 def __init__(self, parent):
     super().__init__(parent)
     self.parent = parent  # main_window
     self.view = None  # type: HistoryList
     self.transactions = OrderedDictWithIndex()
     self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
     self.summary = None
     self.omni = hasattr(parent.wallet, 'omni') and parent.wallet.omni
예제 #3
0
 def __init__(self, parent):
     super().__init__(parent)
     self.parent = parent
     self.view = None  # type: HistoryList
     self.transactions = OrderedDictWithIndex()
     self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
     self.summary = None
예제 #4
0
    def __init__(self, parent=None):
        super().__init__(parent, self.create_menu, 2)
        self.std_model = QStandardItemModel(self)
        self.proxy = HistorySortModel(self)
        self.proxy.setSourceModel(self.std_model)
        self.setModel(self.proxy)

        self.txid_to_items = {}
        self.transactions = OrderedDictWithIndex()
        self.summary = {}
        self.blue_brush = QBrush(QColor("#1E1EFF"))
        self.red_brush = QBrush(QColor("#BC1E1E"))
        self.monospace_font = QFont(MONOSPACE_FONT)
        self.config = parent.config
        AcceptFileDragDrop.__init__(self, ".txn")
        self.setSortingEnabled(True)
        self.start_timestamp = None
        self.end_timestamp = None
        self.years = []
        self.create_toolbar_buttons()
        self.wallet = self.parent.wallet  # type: Abstract_Wallet
        self.refresh_headers()
        self.sortByColumn(0, Qt.AscendingOrder)
예제 #5
0
    def __init__(self, parent=None):
        super().__init__(parent, self.create_menu, 2)
        self.std_model = QStandardItemModel(self)
        self.proxy = HistorySortModel(self)
        self.proxy.setSourceModel(self.std_model)
        self.setModel(self.proxy)

        self.txid_to_items = {}
        self.transactions = OrderedDictWithIndex()
        self.summary = {}
        self.blue_brush = QBrush(QColor("#1E1EFF"))
        self.red_brush = QBrush(QColor("#BC1E1E"))
        self.monospace_font = QFont(MONOSPACE_FONT)
        self.config = parent.config
        AcceptFileDragDrop.__init__(self, ".txn")
        self.setSortingEnabled(True)
        self.start_timestamp = None
        self.end_timestamp = None
        self.years = []
        self.create_toolbar_buttons()
        self.wallet = self.parent.wallet  # type: Abstract_Wallet
        self.refresh_headers()
        self.sortByColumn(0, Qt.AscendingOrder)
예제 #6
0
class TokenHistoryModel(QAbstractItemModel, Logger):
    def __init__(self, parent: 'ElectrumWindow'):
        QAbstractItemModel.__init__(self, parent)
        Logger.__init__(self)
        self.parent = parent
        self.view = None  # type: TokenHistoryList
        self.transactions = OrderedDictWithIndex()
        self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]

    def set_view(self, token_hist_list: 'TokenHistoryList'):
        # FIXME HistoryModel and HistoryList mutually depend on each other.
        # After constructing both, this method needs to be called.
        self.view = token_hist_list  # type: TokenHistoryList
        self.set_visibility_of_columns()

    def columnCount(self, parent: QModelIndex):
        return len(TokenHistoryColumns)

    def rowCount(self, parent: QModelIndex):
        return len(self.transactions)

    def index(self, row: int, column: int, parent: QModelIndex):
        return self.createIndex(row, column)

    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        if not tx_item:
            return QVariant()
        tx_hash = tx_item['txid']
        conf = tx_item['confirmations']
        txpos = tx_item['txpos_in_block'] or 0
        height = tx_item['height']
        token = self.parent.wallet.db.get_token(tx_item['token_key'])
        bind_addr = tx_item['bind_addr']
        from_addr = tx_item['from_addr']
        to_addr = tx_item['to_addr']

        timestamp = tx_item['timestamp']
        if timestamp is None:
            timestamp = float("inf")

        try:
            status, status_str = self.tx_status_cache[tx_hash]
        except KeyError:
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            status, status_str = self.parent.wallet.get_tx_status(
                tx_hash, tx_mined_info)

        balance_str = f"{tx_item['amount']}" if to_addr == bind_addr else f"- {tx_item['amount']}"

        if role == Qt.UserRole:
            # for sorting
            d = {
                TokenHistoryColumns.STATUS:
                (-timestamp, conf, -status, -height, -txpos),
                TokenHistoryColumns.BIND_ADDRESS:
                bind_addr,
                TokenHistoryColumns.TOKEN:
                token.symbol,
                TokenHistoryColumns.AMOUNT:
                balance_str,
            }
            return QVariant(d[col])

        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == TokenHistoryColumns.STATUS and role == Qt.DecorationRole:
                return QVariant(read_QIcon(TX_ICONS[status]))
            elif col == TokenHistoryColumns.STATUS and role == Qt.ToolTipRole:
                return QVariant(
                    str(conf) + _(" confirmation" +
                                  ("s" if conf != 1 else "")))
            elif col > TokenHistoryColumns.BIND_ADDRESS and role == Qt.TextAlignmentRole:
                return QVariant(int(Qt.AlignRight | Qt.AlignVCenter))
            elif col != TokenHistoryColumns.STATUS and role == Qt.FontRole:
                return QVariant(QFont(MONOSPACE_FONT))
            elif col in (TokenHistoryColumns.TOKEN, TokenHistoryColumns.AMOUNT) \
                    and role == Qt.ForegroundRole and from_addr == bind_addr:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            return QVariant()
        if col == TokenHistoryColumns.STATUS:
            return QVariant(status_str)
        elif col == TokenHistoryColumns.BIND_ADDRESS:
            return QVariant(bind_addr)
        elif col == TokenHistoryColumns.TOKEN:
            return QVariant(token.symbol)
        elif col == TokenHistoryColumns.AMOUNT:
            amount = tx_item['amount']
            if from_addr == bind_addr:
                amount = -amount
            v_str = self.parent.format_amount(amount,
                                              is_diff=True,
                                              whitespaces=True,
                                              num_zeros=0,
                                              decimal_point=token.decimals)
            return QVariant(v_str)
        return QVariant()

    def parent(self, index: QModelIndex):
        return QModelIndex()

    def hasChildren(self, index: QModelIndex):
        return not index.isValid()

    @profiler
    def refresh(self, reason: str):
        self.logger.info(f"token refreshing... reason: {reason}")
        assert self.parent.gui_thread == threading.current_thread(
        ), 'must be called from GUI thread'
        assert self.view, 'view not set'
        selected = self.view.selectionModel().currentIndex()
        selected_row = None
        if selected:
            selected_row = selected.row()
        self.set_visibility_of_columns()

        hist = self.parent.wallet.get_full_token_history()
        if hist == list(self.transactions.values()):
            return
        old_length = len(self.transactions)
        if old_length != 0:
            self.beginRemoveRows(QModelIndex(), 0, old_length)
            self.transactions.clear()
            self.endRemoveRows()
        self.beginInsertRows(QModelIndex(), 0, len(hist) - 1)
        for tx_item in hist:
            txid = tx_item['bind_addr'] + "_" + tx_item['txid']
            self.transactions[txid] = tx_item
        self.endInsertRows()
        if selected_row:
            self.view.selectionModel().select(
                self.createIndex(selected_row, 0),
                QItemSelectionModel.Rows | QItemSelectionModel.SelectCurrent)
        # update tx_status_cache
        self.tx_status_cache.clear()
        for txid, tx_item in self.transactions.items():
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            self.tx_status_cache[txid] = self.parent.wallet.get_tx_status(
                txid, tx_mined_info)

    def set_visibility_of_columns(self):
        def set_visible(col: int, b: bool):
            self.view.showColumn(col) if b else self.view.hideColumn(col)

        # set_visible(TokenHistoryColumns.TXID, False)

    def update_tx_mined_status(self, tx_hash: str, tx_mined_info: TxMinedInfo):
        try:
            row = self.transactions.pos_from_key(tx_hash)
            tx_item = self.transactions[tx_hash]
        except KeyError:
            return
        self.tx_status_cache[tx_hash] = self.parent.wallet.get_tx_status(
            tx_hash, tx_mined_info)
        tx_item.update({
            'confirmations': tx_mined_info.conf,
            'timestamp': tx_mined_info.timestamp,
            'txpos_in_block': tx_mined_info.txpos,
            'date': timestamp_to_datetime(tx_mined_info.timestamp),
        })
        topLeft = self.createIndex(row, 0)
        bottomRight = self.createIndex(row, len(TokenHistoryColumns) - 1)
        self.dataChanged.emit(topLeft, bottomRight)

    def headerData(self, section: int, orientation: Qt.Orientation,
                   role: Qt.ItemDataRole):
        assert orientation == Qt.Horizontal
        if role != Qt.DisplayRole:
            return None
        return {
            TokenHistoryColumns.STATUS: _('Date'),
            TokenHistoryColumns.BIND_ADDRESS: _('Bind Address'),
            TokenHistoryColumns.TOKEN: _('Token'),
            TokenHistoryColumns.AMOUNT: _('Amount'),
        }[section]

    def flags(self, idx):
        extra_flags = Qt.NoItemFlags  # type: Qt.ItemFlag
        if idx.column() in self.view.editable_columns:
            extra_flags |= Qt.ItemIsEditable
        return super().flags(idx) | int(extra_flags)

    @staticmethod
    def tx_mined_info_from_tx_item(tx_item):
        tx_mined_info = TxMinedInfo(height=tx_item['height'],
                                    conf=tx_item['confirmations'],
                                    timestamp=tx_item['timestamp'])
        return tx_mined_info
예제 #7
0
class HistoryModel(CustomModel, Logger):
    def __init__(self, parent: 'ElectrumWindow'):
        CustomModel.__init__(self, parent, len(HistoryColumns))
        Logger.__init__(self)
        self.parent = parent
        self.view = None  # type: HistoryList
        self.transactions = OrderedDictWithIndex()
        self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]

    def set_view(self, history_list: 'HistoryList'):
        # FIXME HistoryModel and HistoryList mutually depend on each other.
        # After constructing both, this method needs to be called.
        self.view = history_list  # type: HistoryList
        self.set_visibility_of_columns()

    def update_label(self, index):
        tx_item = index.internalPointer().get_data()
        tx_item['label'] = self.parent.wallet.get_label_for_txid(
            get_item_key(tx_item))
        topLeft = bottomRight = self.createIndex(index.row(),
                                                 HistoryColumns.DESCRIPTION)
        self.dataChanged.emit(topLeft, bottomRight, [Qt.DisplayRole])
        self.parent.utxo_list.update()

    def get_domain(self):
        """Overridden in address_dialog.py"""
        return self.parent.wallet.get_addresses()

    def should_include_lightning_payments(self) -> bool:
        """Overridden in address_dialog.py"""
        return True

    @profiler
    def refresh(self, reason: str):
        self.logger.info(f"refreshing... reason: {reason}")
        assert self.parent.gui_thread == threading.current_thread(
        ), 'must be called from GUI thread'
        assert self.view, 'view not set'
        if self.view.maybe_defer_update():
            return
        selected = self.view.selectionModel().currentIndex()
        selected_row = None
        if selected:
            selected_row = selected.row()
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        wallet = self.parent.wallet
        self.set_visibility_of_columns()
        transactions = wallet.get_full_history(
            self.parent.fx,
            onchain_domain=self.get_domain(),
            include_lightning=self.should_include_lightning_payments())
        if transactions == self.transactions:
            return
        old_length = self._root.childCount()
        if old_length != 0:
            self.beginRemoveRows(QModelIndex(), 0, old_length)
            self.transactions.clear()
            self._root = HistoryNode(self, None)
            self.endRemoveRows()
        parents = {}
        for tx_item in transactions.values():
            node = HistoryNode(self, tx_item)
            group_id = tx_item.get('group_id')
            if group_id is None:
                self._root.addChild(node)
            else:
                parent = parents.get(group_id)
                if parent is None:
                    # create parent if it does not exist
                    self._root.addChild(node)
                    parents[group_id] = node
                else:
                    # if parent has no children, create two children
                    if parent.childCount() == 0:
                        child_data = dict(parent.get_data())
                        node1 = HistoryNode(self, child_data)
                        parent.addChild(node1)
                        parent._data['label'] = child_data.get('group_label')
                        parent._data['bc_value'] = child_data.get(
                            'bc_value', Satoshis(0))
                        parent._data['ln_value'] = child_data.get(
                            'ln_value', Satoshis(0))
                    # add child to parent
                    parent.addChild(node)
                    # update parent data
                    parent._data['balance'] = tx_item['balance']
                    parent._data['value'] += tx_item['value']
                    if 'group_label' in tx_item:
                        parent._data['label'] = tx_item['group_label']
                    if 'bc_value' in tx_item:
                        parent._data['bc_value'] += tx_item['bc_value']
                    if 'ln_value' in tx_item:
                        parent._data['ln_value'] += tx_item['ln_value']
                    if 'fiat_value' in tx_item:
                        parent._data['fiat_value'] += tx_item['fiat_value']
                    if tx_item.get('txid') == group_id:
                        parent._data['lightning'] = False
                        parent._data['txid'] = tx_item['txid']
                        parent._data['timestamp'] = tx_item['timestamp']
                        parent._data['height'] = tx_item['height']
                        parent._data['confirmations'] = tx_item[
                            'confirmations']

        new_length = self._root.childCount()
        self.beginInsertRows(QModelIndex(), 0, new_length - 1)
        self.transactions = transactions
        self.endInsertRows()

        if selected_row:
            self.view.selectionModel().select(
                self.createIndex(selected_row, 0),
                QItemSelectionModel.Rows | QItemSelectionModel.SelectCurrent)
        self.view.filter()
        # update time filter
        if not self.view.years and self.transactions:
            start_date = date.today()
            end_date = date.today()
            if len(self.transactions) > 0:
                start_date = self.transactions.value_from_pos(0).get(
                    'date') or start_date
                end_date = self.transactions.value_from_pos(
                    len(self.transactions) - 1).get('date') or end_date
            self.view.years = [
                str(i) for i in range(start_date.year, end_date.year + 1)
            ]
            self.view.period_combo.insertItems(1, self.view.years)
        # update tx_status_cache
        self.tx_status_cache.clear()
        for txid, tx_item in self.transactions.items():
            if not tx_item.get('lightning', False):
                tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
                self.tx_status_cache[txid] = self.parent.wallet.get_tx_status(
                    txid, tx_mined_info)

    def set_visibility_of_columns(self):
        def set_visible(col: int, b: bool):
            self.view.showColumn(col) if b else self.view.hideColumn(col)

        # txid
        set_visible(HistoryColumns.TXID, False)
        # fiat
        history = self.parent.fx.show_history()
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        set_visible(HistoryColumns.FIAT_VALUE, history)
        set_visible(HistoryColumns.FIAT_ACQ_PRICE, history and cap_gains)
        set_visible(HistoryColumns.FIAT_CAP_GAINS, history and cap_gains)

    def update_fiat(self, idx):
        tx_item = idx.internalPointer().get_data()
        txid = tx_item['txid']
        fee = tx_item.get('fee')
        value = tx_item['value'].value
        fiat_fields = self.parent.wallet.get_tx_item_fiat(
            tx_hash=txid,
            amount_sat=value,
            fx=self.parent.fx,
            tx_fee=fee.value if fee else None)
        tx_item.update(fiat_fields)
        self.dataChanged.emit(idx, idx, [Qt.DisplayRole, Qt.ForegroundRole])

    def update_tx_mined_status(self, tx_hash: str, tx_mined_info: TxMinedInfo):
        try:
            row = self.transactions.pos_from_key(tx_hash)
            tx_item = self.transactions[tx_hash]
        except KeyError:
            return
        self.tx_status_cache[tx_hash] = self.parent.wallet.get_tx_status(
            tx_hash, tx_mined_info)
        tx_item.update({
            'confirmations': tx_mined_info.conf,
            'timestamp': tx_mined_info.timestamp,
            'txpos_in_block': tx_mined_info.txpos,
            'date': timestamp_to_datetime(tx_mined_info.timestamp),
        })
        topLeft = self.createIndex(row, 0)
        bottomRight = self.createIndex(row, len(HistoryColumns) - 1)
        self.dataChanged.emit(topLeft, bottomRight)

    def on_fee_histogram(self):
        for tx_hash, tx_item in list(self.transactions.items()):
            if tx_item.get('lightning'):
                continue
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            if tx_mined_info.conf > 0:
                # note: we could actually break here if we wanted to rely on the order of txns in self.transactions
                continue
            self.update_tx_mined_status(tx_hash, tx_mined_info)

    def headerData(self, section: int, orientation: Qt.Orientation,
                   role: Qt.ItemDataRole):
        assert orientation == Qt.Horizontal
        if role != Qt.DisplayRole:
            return None
        fx = self.parent.fx
        fiat_title = 'n/a fiat value'
        fiat_acq_title = 'n/a fiat acquisition price'
        fiat_cg_title = 'n/a fiat capital gains'
        if fx and fx.show_history():
            fiat_title = '%s ' % fx.ccy + _('Value')
            fiat_acq_title = '%s ' % fx.ccy + _('Acquisition price')
            fiat_cg_title = '%s ' % fx.ccy + _('Capital Gains')
        return {
            HistoryColumns.STATUS: _('Date'),
            HistoryColumns.DESCRIPTION: _('Description'),
            HistoryColumns.AMOUNT: _('Amount'),
            HistoryColumns.BALANCE: _('Balance'),
            HistoryColumns.FIAT_VALUE: fiat_title,
            HistoryColumns.FIAT_ACQ_PRICE: fiat_acq_title,
            HistoryColumns.FIAT_CAP_GAINS: fiat_cg_title,
            HistoryColumns.TXID: 'TXID',
        }[section]

    def flags(self, idx):
        extra_flags = Qt.NoItemFlags  # type: Qt.ItemFlag
        if idx.column() in self.view.editable_columns:
            extra_flags |= Qt.ItemIsEditable
        return super().flags(idx) | int(extra_flags)

    @staticmethod
    def tx_mined_info_from_tx_item(tx_item):
        tx_mined_info = TxMinedInfo(height=tx_item['height'],
                                    conf=tx_item['confirmations'],
                                    timestamp=tx_item['timestamp'])
        return tx_mined_info
예제 #8
0
class HistoryModel(QAbstractItemModel, Logger):
    def __init__(self, parent: 'ElectrumWindow'):
        QAbstractItemModel.__init__(self, parent)
        Logger.__init__(self)
        self.parent = parent
        self.view = None  # type: HistoryList
        self.transactions = OrderedDictWithIndex()
        self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]

    def set_view(self, history_list: 'HistoryList'):
        # FIXME HistoryModel and HistoryList mutually depend on each other.
        # After constructing both, this method needs to be called.
        self.view = history_list  # type: HistoryList
        self.set_visibility_of_columns()

    def columnCount(self, parent: QModelIndex):
        return len(HistoryColumns)

    def rowCount(self, parent: QModelIndex):
        return len(self.transactions)

    def index(self, row: int, column: int, parent: QModelIndex):
        return self.createIndex(row, column)

    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        is_lightning = tx_item.get('lightning', False)
        timestamp = tx_item['timestamp']
        if is_lightning:
            status = 0
            txpos = tx_item['txpos']
            if timestamp is None:
                status_str = 'unconfirmed'
            else:
                status_str = format_time(int(timestamp))
        else:
            tx_hash = tx_item['txid']
            conf = tx_item['confirmations']
            txpos = tx_item['txpos_in_block'] or 0
            height = tx_item['height']
            try:
                status, status_str = self.tx_status_cache[tx_hash]
            except KeyError:
                tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
                status, status_str = self.parent.wallet.get_tx_status(
                    tx_hash, tx_mined_info)

        # we sort by timestamp
        if timestamp is None:
            timestamp = float("inf")

        if role == Qt.UserRole:
            # for sorting
            d = {
                HistoryColumns.STATUS:
                    # height breaks ties for unverified txns
                    # txpos breaks ties for verified same block txns
                    (-timestamp, conf, -status, -height, -txpos) if not is_lightning else (-timestamp, 0,0,0,-txpos),
                HistoryColumns.DESCRIPTION:
                    tx_item['label'] if 'label' in tx_item else None,
                HistoryColumns.AMOUNT:
                    (tx_item['bc_value'].value if 'bc_value' in tx_item else 0)\
                    + (tx_item['ln_value'].value if 'ln_value' in tx_item else 0),
                HistoryColumns.BALANCE:
                    (tx_item['balance'].value if 'balance' in tx_item else 0)\
                    + (tx_item['balance_msat']//1000 if 'balance_msat'in tx_item else 0),
                HistoryColumns.FIAT_VALUE:
                    tx_item['fiat_value'].value if 'fiat_value' in tx_item else None,
                HistoryColumns.FIAT_ACQ_PRICE:
                    tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None,
                HistoryColumns.FIAT_CAP_GAINS:
                    tx_item['capital_gain'].value if 'capital_gain' in tx_item else None,
                HistoryColumns.TXID: tx_hash if not is_lightning else None,
            }
            return QVariant(d[col])
        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == HistoryColumns.STATUS and role == Qt.DecorationRole:
                icon = "lightning" if is_lightning else TX_ICONS[status]
                return QVariant(read_QIcon(icon))
            elif col == HistoryColumns.STATUS and role == Qt.ToolTipRole:
                msg = 'lightning transaction' if is_lightning else str(
                    conf) + _(" confirmation" + ("s" if conf != 1 else ""))
                return QVariant(msg)
            elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole:
                return QVariant(Qt.AlignRight | Qt.AlignVCenter)
            elif col != HistoryColumns.STATUS and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            #elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole and not is_lightning\
            #        and self.parent.wallet.invoices.paid.get(tx_hash):
            #    return QVariant(read_QIcon("seal"))
            elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.AMOUNT) \
                    and role == Qt.ForegroundRole and tx_item['value'].value < 0:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            return QVariant()
        if col == HistoryColumns.STATUS:
            return QVariant(status_str)
        elif col == HistoryColumns.DESCRIPTION and 'label' in tx_item:
            return QVariant(tx_item['label'])
        elif col == HistoryColumns.AMOUNT:
            bc_value = tx_item['bc_value'].value if 'bc_value' in tx_item else 0
            ln_value = tx_item['ln_value'].value if 'ln_value' in tx_item else 0
            value = bc_value + ln_value
            v_str = self.parent.format_amount(value,
                                              is_diff=True,
                                              whitespaces=True)
            return QVariant(v_str)
        elif col == HistoryColumns.BALANCE:
            balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == HistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == HistoryColumns.TXID:
            return QVariant(tx_hash)
        return QVariant()

    def parent(self, index: QModelIndex):
        return QModelIndex()

    def hasChildren(self, index: QModelIndex):
        return not index.isValid()

    def update_label(self, row):
        tx_item = self.transactions.value_from_pos(row)
        tx_item['label'] = self.parent.wallet.get_label(get_item_key(tx_item))
        topLeft = bottomRight = self.createIndex(row, 2)
        self.dataChanged.emit(topLeft, bottomRight, [Qt.DisplayRole])
        self.parent.utxo_list.update()

    def get_domain(self):
        """Overridden in address_dialog.py"""
        return self.parent.wallet.get_addresses()

    def should_include_lightning_payments(self) -> bool:
        """Overridden in address_dialog.py"""
        return True

    @profiler
    def refresh(self, reason: str):
        self.logger.info(f"refreshing... reason: {reason}")
        assert self.parent.gui_thread == threading.current_thread(
        ), 'must be called from GUI thread'
        assert self.view, 'view not set'
        selected = self.view.selectionModel().currentIndex()
        selected_row = None
        if selected:
            selected_row = selected.row()
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        wallet = self.parent.wallet
        self.set_visibility_of_columns()
        transactions = wallet.get_full_history(
            self.parent.fx,
            onchain_domain=self.get_domain(),
            include_lightning=self.should_include_lightning_payments())
        if transactions == list(self.transactions.values()):
            return
        old_length = len(self.transactions)
        if old_length != 0:
            self.beginRemoveRows(QModelIndex(), 0, old_length)
            self.transactions.clear()
            self.endRemoveRows()
        self.beginInsertRows(QModelIndex(), 0, len(transactions) - 1)
        self.transactions = transactions
        self.endInsertRows()
        if selected_row:
            self.view.selectionModel().select(
                self.createIndex(selected_row, 0),
                QItemSelectionModel.Rows | QItemSelectionModel.SelectCurrent)
        self.view.filter()
        # update time filter
        if not self.view.years and self.transactions:
            start_date = date.today()
            end_date = date.today()
            if len(self.transactions) > 0:
                start_date = self.transactions.value_from_pos(0).get(
                    'date') or start_date
                end_date = self.transactions.value_from_pos(
                    len(self.transactions) - 1).get('date') or end_date
            self.view.years = [
                str(i) for i in range(start_date.year, end_date.year + 1)
            ]
            self.view.period_combo.insertItems(1, self.view.years)
        # update tx_status_cache
        self.tx_status_cache.clear()
        for txid, tx_item in self.transactions.items():
            if not tx_item.get('lightning', False):
                tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
                self.tx_status_cache[txid] = self.parent.wallet.get_tx_status(
                    txid, tx_mined_info)

    def set_visibility_of_columns(self):
        def set_visible(col: int, b: bool):
            self.view.showColumn(col) if b else self.view.hideColumn(col)

        # txid
        set_visible(HistoryColumns.TXID, False)
        # fiat
        history = self.parent.fx.show_history()
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        set_visible(HistoryColumns.FIAT_VALUE, history)
        set_visible(HistoryColumns.FIAT_ACQ_PRICE, history and cap_gains)
        set_visible(HistoryColumns.FIAT_CAP_GAINS, history and cap_gains)

    def update_fiat(self, row, idx):
        tx_item = self.transactions.value_from_pos(row)
        key = tx_item['txid']
        fee = tx_item.get('fee')
        value = tx_item['value'].value
        fiat_fields = self.parent.wallet.get_tx_item_fiat(
            key, value, self.parent.fx, fee.value if fee else None)
        tx_item.update(fiat_fields)
        self.dataChanged.emit(idx, idx, [Qt.DisplayRole, Qt.ForegroundRole])

    def update_tx_mined_status(self, tx_hash: str, tx_mined_info: TxMinedInfo):
        try:
            row = self.transactions.pos_from_key(tx_hash)
            tx_item = self.transactions[tx_hash]
        except KeyError:
            return
        self.tx_status_cache[tx_hash] = self.parent.wallet.get_tx_status(
            tx_hash, tx_mined_info)
        tx_item.update({
            'confirmations': tx_mined_info.conf,
            'timestamp': tx_mined_info.timestamp,
            'txpos_in_block': tx_mined_info.txpos,
            'date': timestamp_to_datetime(tx_mined_info.timestamp),
        })
        topLeft = self.createIndex(row, 0)
        bottomRight = self.createIndex(row, len(HistoryColumns) - 1)
        self.dataChanged.emit(topLeft, bottomRight)

    def on_fee_histogram(self):
        for tx_hash, tx_item in list(self.transactions.items()):
            if tx_item.get('lightning'):
                continue
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            if tx_mined_info.conf > 0:
                # note: we could actually break here if we wanted to rely on the order of txns in self.transactions
                continue
            self.update_tx_mined_status(tx_hash, tx_mined_info)

    def headerData(self, section: int, orientation: Qt.Orientation,
                   role: Qt.ItemDataRole):
        assert orientation == Qt.Horizontal
        if role != Qt.DisplayRole:
            return None
        fx = self.parent.fx
        fiat_title = 'n/a fiat value'
        fiat_acq_title = 'n/a fiat acquisition price'
        fiat_cg_title = 'n/a fiat capital gains'
        if fx and fx.show_history():
            fiat_title = '%s ' % fx.ccy + _('Value')
            fiat_acq_title = '%s ' % fx.ccy + _('Acquisition price')
            fiat_cg_title = '%s ' % fx.ccy + _('Capital Gains')
        return {
            HistoryColumns.STATUS: _('Date'),
            HistoryColumns.DESCRIPTION: _('Description'),
            HistoryColumns.AMOUNT: _('Amount'),
            HistoryColumns.BALANCE: _('Balance'),
            HistoryColumns.FIAT_VALUE: fiat_title,
            HistoryColumns.FIAT_ACQ_PRICE: fiat_acq_title,
            HistoryColumns.FIAT_CAP_GAINS: fiat_cg_title,
            HistoryColumns.TXID: 'TXID',
        }[section]

    def flags(self, idx):
        extra_flags = Qt.NoItemFlags  # type: Qt.ItemFlag
        if idx.column() in self.view.editable_columns:
            extra_flags |= Qt.ItemIsEditable
        return super().flags(idx) | extra_flags

    @staticmethod
    def tx_mined_info_from_tx_item(tx_item):
        tx_mined_info = TxMinedInfo(height=tx_item['height'],
                                    conf=tx_item['confirmations'],
                                    timestamp=tx_item['timestamp'])
        return tx_mined_info
예제 #9
0
 def __init__(self, parent):
     super().__init__(parent)
     self.parent = parent
     self.view = None  # type: HistoryList
     self.transactions = OrderedDictWithIndex()
     self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
예제 #10
0
class BettingHistoryModel(QAbstractItemModel, Logger):

    def __init__(self, parent):
        QAbstractItemModel.__init__(self, parent)
        Logger.__init__(self)
        self.parent = parent
        self.view = None  # type: BettingHistoryList
        self.transactions = OrderedDictWithIndex()
        self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
        self.summary = None
    def set_view(self, history_list: 'BettingHistoryList'):
        # FIXME BettingHistoryModel and BettingHistoryList mutually depend on each other.
        # After constructing both, this method needs to be called.
        self.view = history_list  # type: BettingHistoryList
        self.set_visibility_of_columns()

    def columnCount(self, parent: QModelIndex):
        return len(BettingHistoryColumns)

    def rowCount(self, parent: QModelIndex):
        return len(self.transactions)

    def index(self, row: int, column: int, parent: QModelIndex):
        return self.createIndex(row, column)
    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        tx_hash = tx_item['txid'].split('-')[0] #remove extra leg number from string
        conf = tx_item['confirmations']
        txpos = tx_item['txpos_in_block'] or 0
        height = tx_item['height']
        eventId = tx_item['event_id']
        eventTime = time.strftime('%b %d %I:%M %p', time.localtime(tx_item['event_start_time']))
        home = tx_item['home_team']
        away = tx_item['away_team'] 
        outcomeType = tx_item['team_to_win']
        effectiveOdds = tx_item['effectiveOdds']
        points = tx_item['spreadPoints'] if outcomeType in [4,5] else tx_item['totalPoints'] if outcomeType in [6,7] else ''
        twgr_amount = tx_item['bet_amount']
        result = tx_item['result']
        betType = tx_item['betType']
        payoutTxHash = tx_item['payoutTxHash']
        payout = tx_item['payout']
        
        if(tx_item['flip_color']): #backgroun color fliping for bet list item.
            backg_color = '#8c8c8c'
            text_color ="#ffffff"
        else:
            backg_color = '#ffffff'
            text_color ="#000000"

       

        

        try:
            status, status_str = self.tx_status_cache[tx_hash]
        except KeyError:
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            status, status_str = self.parent.wallet.get_tx_status(tx_hash, tx_mined_info)
        if role == Qt.UserRole:
            # for sorting
            d = {
                BettingHistoryColumns.STATUS_ICON:
                    # height breaks ties for unverified txns
                    # txpos breaks ties for verified same block txns
                    (conf, -status, -height, -txpos),
                BettingHistoryColumns.STATUS_TEXT: status_str,
                BettingHistoryColumns.DESCRIPTION: tx_item['label'],
                
                BettingHistoryColumns.TRANSACTION_ID: tx_item['txid'],

                BettingHistoryColumns.COIN_VALUE:  tx_item['value'].value,
                BettingHistoryColumns.RUNNING_COIN_BALANCE: tx_item['balance'].value,
                BettingHistoryColumns.FIAT_VALUE:
                    tx_item['fiat_value'].value if 'fiat_value' in tx_item else None,
                BettingHistoryColumns.FIAT_ACQ_PRICE:
                    tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None,
                BettingHistoryColumns.FIAT_CAP_GAINS:
                    tx_item['capital_gain'].value if 'capital_gain' in tx_item else None,
                BettingHistoryColumns.TXID: tx_hash,
            }
            return QVariant(d.get(col))
        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == BettingHistoryColumns.STATUS_ICON and role == Qt.DecorationRole:
                return QVariant(read_QIcon(TX_ICONS[status]))
            elif col == BettingHistoryColumns.STATUS_ICON and role == Qt.ToolTipRole:
                return QVariant(str(conf) + _(" confirmation" + ("s" if conf != 1 else "")))
            elif col > BettingHistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole:
                 return QVariant(Qt.AlignVCenter)
            elif col != BettingHistoryColumns.STATUS_TEXT and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            elif col == BettingHistoryColumns.DESCRIPTION and role == Qt.DecorationRole \
                    and self.parent.wallet.invoices.paid.get(tx_hash):
                return QVariant(read_QIcon("seal"))
            elif col in (BettingHistoryColumns.DESCRIPTION, BettingHistoryColumns.COIN_VALUE) \
                    and role == Qt.ForegroundRole and tx_item['value'].value < 0:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            elif col == BettingHistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            elif role == Qt.BackgroundRole: #set parlay bet list item background
                backg_brush = QBrush(QColor(backg_color))
                return QVariant(backg_brush)
            elif role == Qt.ForegroundRole:
                text_brush = QBrush(QColor(text_color))
                return QVariant(text_brush)
            elif col == BettingHistoryColumns.PAYOUT_TX_HASH and not payoutTxHash == '' and role == Qt.DecorationRole:
                return QVariant(read_QIcon('copy.png'))
            return QVariant()
        if col == BettingHistoryColumns.STATUS_TEXT:
            return QVariant(status_str)
        elif col == BettingHistoryColumns.DESCRIPTION:
            return QVariant(tx_item['label'])
        elif col == BettingHistoryColumns.EVENT_ID:
            return QVariant(eventId)
        elif col == BettingHistoryColumns.TRANSACTION_ID:
            return QVariant(tx_item['txid'])
        elif col == BettingHistoryColumns.BET_OUTCOME:
            return QVariant( OUTCOME[outcomeType]+ ' ' + points )
        elif col == BettingHistoryColumns.EFFECTIVE_ODDS:
            return QVariant(effectiveOdds)
        elif col == BettingHistoryColumns.HOME:
            return QVariant(home)
        elif col == BettingHistoryColumns.AWAY:
            return QVariant(away)
        elif col == BettingHistoryColumns.START_TIME:
            return QVariant(eventTime)
        elif col == BettingHistoryColumns.TWGR_AMOUNT:
            return QVariant(twgr_amount)
        elif col == BettingHistoryColumns.BET_TYPE:
            return QVariant(betType)
        elif col == BettingHistoryColumns.RESULT:
            return QVariant(result)
        elif col == BettingHistoryColumns.PAYOUT_TX_HASH:
            return QVariant(payoutTxHash)
        elif col == BettingHistoryColumns.PAYOUT_AMOUNT:
            return QVariant(payout)
        elif col == BettingHistoryColumns.COIN_VALUE:
            value = tx_item['value'].value
            v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True)
            return QVariant(v_str)
        elif col == BettingHistoryColumns.RUNNING_COIN_BALANCE:
            balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == BettingHistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == BettingHistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == BettingHistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == BettingHistoryColumns.TXID:
            return QVariant(tx_hash)
        return QVariant()

    def parent(self, index: QModelIndex):
        return QModelIndex()

    def hasChildren(self, index: QModelIndex):
        return not index.isValid()

    def update_label(self, row):
        tx_item = self.transactions.value_from_pos(row)
        tx_item['label'] = self.parent.wallet.get_label(tx_item['txid'])
        topLeft = bottomRight = self.createIndex(row, 2)
        self.dataChanged.emit(topLeft, bottomRight, [Qt.DisplayRole])

    def get_domain(self):
        '''Overridden in address_dialog.py'''
        return self.parent.wallet.get_addresses()

    @profiler
    def refresh(self, reason: str):
        self.logger.info(f"refreshing... reason: {reason}")
        assert self.parent.gui_thread == threading.current_thread(), 'must be called from GUI thread'
        assert self.view, 'view not set'
        selected = self.view.selectionModel().currentIndex()
        selected_row = None
        if selected:
            selected_row = selected.row()
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        r = self.parent.wallet.get_full_betting_history(domain=self.get_domain(), show_addresses=True,from_timestamp=None, to_timestamp=None, fx=fx)
        #print("r",r)
        self.set_visibility_of_columns()
        if r['transactions'] == list(self.transactions.values()):
            return
        old_length = len(self.transactions)
        if old_length != 0:
            self.beginRemoveRows(QModelIndex(), 0, old_length)
            self.transactions.clear()
            self.endRemoveRows()
        self.beginInsertRows(QModelIndex(), 0, len(r['transactions'])-1)
        for tx_item in r['transactions']:
            txid = tx_item['txid']
            self.transactions[txid] = tx_item
        self.endInsertRows()
        if selected_row:
            self.view.selectionModel().select(self.createIndex(selected_row, 0), QItemSelectionModel.Rows | QItemSelectionModel.SelectCurrent)
        self.view.filter()
        # update summary
        self.summary = r['summary']
        if not self.view.years and self.transactions:
            start_date = date.today()
            end_date = date.today()
            if len(self.transactions) > 0:
                start_date = self.transactions.value_from_pos(0).get('date') or start_date
                end_date = self.transactions.value_from_pos(len(self.transactions) - 1).get('date') or end_date
            self.view.years = [str(i) for i in range(start_date.year, end_date.year + 1)]
            self.view.period_combo.insertItems(1, self.view.years)
        # update tx_status_cache
        self.tx_status_cache.clear()
        for txid, tx_item in self.transactions.items():
            txid = txid.split('-')[0] #remove leg no 
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            self.tx_status_cache[txid] = self.parent.wallet.get_tx_status(txid, tx_mined_info)

    def set_visibility_of_columns(self):
        def set_visible(col: int, b: bool):
            self.view.showColumn(col) if b else self.view.hideColumn(col)
        # txid
        
            
            
        set_visible(BettingHistoryColumns.TXID, False)
        set_visible(BettingHistoryColumns.STATUS_TEXT, False)
        set_visible(BettingHistoryColumns.DESCRIPTION, False)
        set_visible(BettingHistoryColumns.TRANSACTION_ID, False)
        set_visible(BettingHistoryColumns.COIN_VALUE, False)
        set_visible(BettingHistoryColumns.RUNNING_COIN_BALANCE, False)

        # fiat
        history = self.parent.fx.show_history()
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        set_visible(BettingHistoryColumns.FIAT_VALUE, history)
        set_visible(BettingHistoryColumns.FIAT_ACQ_PRICE, history and cap_gains)
        set_visible(BettingHistoryColumns.FIAT_CAP_GAINS, history and cap_gains)

    def update_fiat(self, row, idx):
        tx_item = self.transactions.value_from_pos(row)
        key = tx_item['txid']
        fee = tx_item.get('fee')
        value = tx_item['value'].value
        fiat_fields = self.parent.wallet.get_tx_item_fiat(key, value, self.parent.fx, fee.value if fee else None)
        tx_item.update(fiat_fields)
        self.dataChanged.emit(idx, idx, [Qt.DisplayRole, Qt.ForegroundRole])

    def update_tx_mined_status(self, tx_hash: str, tx_mined_info: TxMinedInfo):
        try:
            row = self.transactions.pos_from_key(tx_hash)
            tx_item = self.transactions[tx_hash]
        except KeyError:
            return
        self.tx_status_cache[tx_hash] = self.parent.wallet.get_tx_status(tx_hash, tx_mined_info)
        tx_item.update({
            'confirmations':  tx_mined_info.conf,
            'timestamp':      tx_mined_info.timestamp,
            'txpos_in_block': tx_mined_info.txpos,
            'date':           timestamp_to_datetime(tx_mined_info.timestamp),
        })
        topLeft = self.createIndex(row, 0)
        bottomRight = self.createIndex(row, len(BettingHistoryColumns) - 1)
        self.dataChanged.emit(topLeft, bottomRight)

    def on_fee_histogram(self):
        for tx_hash, tx_item in list(self.transactions.items()):
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            if tx_mined_info.conf > 0:
                # note: we could actually break here if we wanted to rely on the order of txns in self.transactions
                continue
            self.update_tx_mined_status(tx_hash, tx_mined_info)

    def headerData(self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole):
        assert orientation == Qt.Horizontal
        if role != Qt.DisplayRole:
            return None
        fx = self.parent.fx
        fiat_title = 'n/a fiat value'
        fiat_acq_title = 'n/a fiat acquisition price'
        fiat_cg_title = 'n/a fiat capital gains'
        t_label= constants.net.SYMBOL + ' Amount'
        if fx and fx.show_history():
            fiat_title = '%s '%fx.ccy + _('Value')
            fiat_acq_title = '%s '%fx.ccy + _('Acquisition price')
            fiat_cg_title =  '%s '%fx.ccy + _('Capital Gains')
        return {
            BettingHistoryColumns.STATUS_ICON: '',
            BettingHistoryColumns.STATUS_TEXT: _('Date'),
            BettingHistoryColumns.DESCRIPTION: _('Description'),
            BettingHistoryColumns.COIN_VALUE: _('Amount'),
            BettingHistoryColumns.RUNNING_COIN_BALANCE: _('Balance'),
            BettingHistoryColumns.FIAT_VALUE: fiat_title,
            BettingHistoryColumns.FIAT_ACQ_PRICE: fiat_acq_title,
            BettingHistoryColumns.FIAT_CAP_GAINS: fiat_cg_title,
            BettingHistoryColumns.TXID: 'TXID',
            BettingHistoryColumns.EVENT_ID:_('Event ID'),
            BettingHistoryColumns.TRANSACTION_ID:_('Transaction ID'),
            BettingHistoryColumns.START_TIME:_('Start Time'),
            BettingHistoryColumns.BET_OUTCOME:_('Bet Selection'),
            BettingHistoryColumns.EFFECTIVE_ODDS:_('Effective Odds'),
            BettingHistoryColumns.HOME:_('Home'),
            BettingHistoryColumns.AWAY:_('Away'),
            BettingHistoryColumns.TWGR_AMOUNT:_(t_label),
            BettingHistoryColumns.BET_TYPE:_('Bet Type'),
            BettingHistoryColumns.RESULT:_('Result'),
            BettingHistoryColumns.PAYOUT_TX_HASH:_('Payout TX Hash'),
            BettingHistoryColumns.PAYOUT_AMOUNT:_('Payout Amount')



        }[section]

    def flags(self, idx):
        extra_flags = Qt.NoItemFlags # type: Qt.ItemFlag
        if idx.column() in self.view.editable_columns:
            extra_flags |= Qt.ItemIsEditable
        return super().flags(idx) | extra_flags

    @staticmethod
    def tx_mined_info_from_tx_item(tx_item):
        tx_mined_info = TxMinedInfo(height=tx_item['height'],
                                    conf=tx_item['confirmations'],
                                    timestamp=tx_item['timestamp'])
        return tx_mined_info
예제 #11
0
class HistoryList(MyTreeView, AcceptFileDragDrop):
    filter_columns = [1, 2, 3]  # Date, Description, Amount
    TX_HASH_ROLE = Qt.UserRole
    SORT_ROLE = Qt.UserRole + 1

    def should_hide(self, proxy_row):
        if self.start_timestamp and self.end_timestamp:
            item = self.item_from_coordinate(proxy_row, 0)
            txid = item.data(self.TX_HASH_ROLE)
            date = self.transactions[txid]['date']
            if date:
                in_interval = self.start_timestamp <= date <= self.end_timestamp
                if not in_interval:
                    return True
            return False

    def __init__(self, parent=None):
        super().__init__(parent, self.create_menu, 2)
        self.std_model = QStandardItemModel(self)
        self.proxy = HistorySortModel(self)
        self.proxy.setSourceModel(self.std_model)
        self.setModel(self.proxy)

        self.txid_to_items = {}
        self.transactions = OrderedDictWithIndex()
        self.summary = {}
        self.blue_brush = QBrush(QColor("#1E1EFF"))
        self.red_brush = QBrush(QColor("#BC1E1E"))
        self.monospace_font = QFont(MONOSPACE_FONT)
        self.config = parent.config
        AcceptFileDragDrop.__init__(self, ".txn")
        self.setSortingEnabled(True)
        self.start_timestamp = None
        self.end_timestamp = None
        self.years = []
        self.create_toolbar_buttons()
        self.wallet = self.parent.wallet  # type: Abstract_Wallet
        self.refresh_headers()
        self.sortByColumn(0, Qt.AscendingOrder)

    def format_date(self, d):
        return str(datetime.date(d.year, d.month, d.day)) if d else _('None')

    def refresh_headers(self):
        headers = ['', _('Date'), _('Description'), _('Amount'), _('Balance')]
        fx = self.parent.fx
        if fx and fx.show_history():
            headers.extend(['%s ' % fx.ccy + _('Value')])
            self.editable_columns |= {5}
            if fx.get_history_capital_gains_config():
                headers.extend(['%s ' % fx.ccy + _('Acquisition price')])
                headers.extend(['%s ' % fx.ccy + _('Capital Gains')])
        else:
            self.editable_columns -= {5}
        col_count = self.std_model.columnCount()
        diff = col_count - len(headers)
        if col_count > len(headers):
            if diff == 2:
                self.std_model.removeColumns(6, diff)
            else:
                assert diff in [1, 3]
                self.std_model.removeColumns(5, diff)
            for items in self.txid_to_items.values():
                while len(items) > col_count:
                    items.pop()
        elif col_count < len(headers):
            self.std_model.clear()
            self.txid_to_items.clear()
            self.transactions.clear()
            self.summary.clear()
        self.update_headers(headers, self.std_model)

    def get_domain(self):
        '''Replaced in address_dialog.py'''
        return self.wallet.get_addresses()

    def on_combo(self, x):
        s = self.period_combo.itemText(x)
        x = s == _('Custom')
        self.start_button.setEnabled(x)
        self.end_button.setEnabled(x)
        if s == _('All'):
            self.start_timestamp = None
            self.end_timestamp = None
            self.start_button.setText("-")
            self.end_button.setText("-")
        else:
            try:
                year = int(s)
            except:
                return
            self.start_timestamp = start_date = datetime.datetime(year, 1, 1)
            self.end_timestamp = end_date = datetime.datetime(year + 1, 1, 1)
            self.start_button.setText(
                _('From') + ' ' + self.format_date(start_date))
            self.end_button.setText(_('To') + ' ' + self.format_date(end_date))
        self.hide_rows()

    def create_toolbar_buttons(self):
        self.period_combo = QComboBox()
        self.start_button = QPushButton('-')
        self.start_button.pressed.connect(self.select_start_date)
        self.start_button.setEnabled(False)
        self.end_button = QPushButton('-')
        self.end_button.pressed.connect(self.select_end_date)
        self.end_button.setEnabled(False)
        self.period_combo.addItems([_('All'), _('Custom')])
        self.period_combo.activated.connect(self.on_combo)

    def get_toolbar_buttons(self):
        return self.period_combo, self.start_button, self.end_button

    def on_hide_toolbar(self):
        self.start_timestamp = None
        self.end_timestamp = None
        self.hide_rows()

    def save_toolbar_state(self, state, config):
        config.set_key('show_toolbar_history', state)

    def select_start_date(self):
        self.start_timestamp = self.select_date(self.start_button)
        self.hide_rows()

    def select_end_date(self):
        self.end_timestamp = self.select_date(self.end_button)
        self.hide_rows()

    def select_date(self, button):
        d = WindowModalDialog(self, _("Select date"))
        d.setMinimumSize(600, 150)
        d.date = None
        vbox = QVBoxLayout()

        def on_date(date):
            d.date = date

        cal = QCalendarWidget()
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(on_date)
        vbox.addWidget(cal)
        vbox.addLayout(Buttons(OkButton(d), CancelButton(d)))
        d.setLayout(vbox)
        if d.exec_():
            if d.date is None:
                return None
            date = d.date.toPyDate()
            button.setText(self.format_date(date))
            return datetime.datetime(date.year, date.month, date.day)

    def show_summary(self):
        h = self.summary
        if not h:
            self.parent.show_message(_("Nothing to summarize."))
            return
        start_date = h.get('start_date')
        end_date = h.get('end_date')
        format_amount = lambda x: self.parent.format_amount(
            x.value) + ' ' + self.parent.base_unit()
        d = WindowModalDialog(self, _("Summary"))
        d.setMinimumSize(600, 150)
        vbox = QVBoxLayout()
        grid = QGridLayout()
        grid.addWidget(QLabel(_("Start")), 0, 0)
        grid.addWidget(QLabel(self.format_date(start_date)), 0, 1)
        grid.addWidget(QLabel(str(h.get('start_fiat_value')) + '/BTC'), 0, 2)
        grid.addWidget(QLabel(_("Initial balance")), 1, 0)
        grid.addWidget(QLabel(format_amount(h['start_balance'])), 1, 1)
        grid.addWidget(QLabel(str(h.get('start_fiat_balance'))), 1, 2)
        grid.addWidget(QLabel(_("End")), 2, 0)
        grid.addWidget(QLabel(self.format_date(end_date)), 2, 1)
        grid.addWidget(QLabel(str(h.get('end_fiat_value')) + '/BTC'), 2, 2)
        grid.addWidget(QLabel(_("Final balance")), 4, 0)
        grid.addWidget(QLabel(format_amount(h['end_balance'])), 4, 1)
        grid.addWidget(QLabel(str(h.get('end_fiat_balance'))), 4, 2)
        grid.addWidget(QLabel(_("Income")), 5, 0)
        grid.addWidget(QLabel(format_amount(h.get('income'))), 5, 1)
        grid.addWidget(QLabel(str(h.get('fiat_income'))), 5, 2)
        grid.addWidget(QLabel(_("Expenditures")), 6, 0)
        grid.addWidget(QLabel(format_amount(h.get('expenditures'))), 6, 1)
        grid.addWidget(QLabel(str(h.get('fiat_expenditures'))), 6, 2)
        grid.addWidget(QLabel(_("Capital gains")), 7, 0)
        grid.addWidget(QLabel(str(h.get('capital_gains'))), 7, 2)
        grid.addWidget(QLabel(_("Unrealized gains")), 8, 0)
        grid.addWidget(QLabel(str(h.get('unrealized_gains', ''))), 8, 2)
        vbox.addLayout(grid)
        vbox.addLayout(Buttons(CloseButton(d)))
        d.setLayout(vbox)
        d.exec_()

    def plot_history_dialog(self):
        if plot_history is None:
            self.parent.show_message(
                _("Can't plot history.") + '\n' +
                _("Perhaps some dependencies are missing...") +
                " (matplotlib?)")
            return
        try:
            plt = plot_history(list(self.transactions.values()))
            plt.show()
        except NothingToPlotException as e:
            self.parent.show_message(str(e))

    def insert_tx(self, tx_item):
        fx = self.parent.fx
        tx_hash = tx_item['txid']
        height = tx_item['height']
        conf = tx_item['confirmations']
        timestamp = tx_item['timestamp']
        value = tx_item['value'].value
        balance = tx_item['balance'].value
        label = tx_item['label']
        tx_mined_status = TxMinedInfo(height=height,
                                      conf=conf,
                                      timestamp=timestamp)
        status, status_str = self.wallet.get_tx_status(tx_hash,
                                                       tx_mined_status)
        has_invoice = self.wallet.invoices.paid.get(tx_hash)
        v_str = self.parent.format_amount(value,
                                          is_diff=True,
                                          whitespaces=True)
        balance_str = self.parent.format_amount(balance, whitespaces=True)
        entry = ['', status_str, label, v_str, balance_str]
        item = [QStandardItem(e) for e in entry]
        item[3].setData(value, self.SORT_ROLE)
        item[4].setData(balance, self.SORT_ROLE)
        if has_invoice:
            item[2].setIcon(self.icon_cache.get(":icons/seal"))
        for i in range(len(entry)):
            self.set_item_properties(item[i], i, tx_hash)
        if value and value < 0:
            item[2].setForeground(self.red_brush)
            item[3].setForeground(self.red_brush)
        self.txid_to_items[tx_hash] = item
        self.update_item(tx_hash, self.wallet.get_tx_height(tx_hash))
        source_row_idx = self.std_model.rowCount()
        self.std_model.insertRow(source_row_idx, item)
        new_idx = self.std_model.index(source_row_idx, 0)
        history = fx.show_history()
        if history:
            self.update_fiat(tx_hash, tx_item)
        self.hide_row(self.proxy.mapFromSource(new_idx).row())

    def set_item_properties(self, item, i, tx_hash):
        if i > 2:
            item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
        if i != 1:
            item.setFont(self.monospace_font)
        item.setEditable(i in self.editable_columns)
        item.setData(tx_hash, self.TX_HASH_ROLE)

    def ensure_fields_available(self, items, idx, txid):
        while len(items) < idx + 1:
            row = self.transactions.get_pos_of_key(txid)
            qidx = self.std_model.index(row, len(items))
            assert qidx.isValid(), (self.std_model.columnCount(), idx)
            item = self.std_model.itemFromIndex(qidx)
            self.set_item_properties(item, len(items), txid)
            items.append(item)

    @profiler
    def update(self):
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        r = self.wallet.get_full_history(domain=self.get_domain(),
                                         from_timestamp=None,
                                         to_timestamp=None,
                                         fx=fx)
        seen = set()
        history = fx.show_history()
        tx_list = list(self.transactions.values())
        if r['transactions'] == tx_list:
            return
        if r['transactions'][:-1] == tx_list:
            print_error('history_list: one new transaction')
            row = r['transactions'][-1]
            txid = row['txid']
            if txid not in self.transactions:
                self.transactions[txid] = row
                self.insert_tx(row)
                return
            else:
                print_error(
                    'history_list: tx added but txid is already in list (weird), txid: ',
                    txid)
        for idx, row in enumerate(r['transactions']):
            txid = row['txid']
            seen.add(txid)
            if txid not in self.transactions:
                self.transactions[txid] = row
                self.insert_tx(row)
                continue
            old = self.transactions[txid]
            if old == row:
                continue
            self.update_item(txid, self.wallet.get_tx_height(txid))
            if history:
                self.update_fiat(txid, row)
            balance_str = self.parent.format_amount(row['balance'].value,
                                                    whitespaces=True)
            self.txid_to_items[txid][4].setText(balance_str)
            self.txid_to_items[txid][4].setData(row['balance'].value,
                                                self.SORT_ROLE)
            old.clear()
            old.update(**row)
        removed = 0
        l = list(enumerate(self.transactions.keys()))
        for idx, txid in l:
            if txid not in seen:
                del self.transactions[txid]
                del self.txid_to_items[txid]
                items = self.std_model.takeRow(idx - removed)
                removed_txid = items[0].data(self.TX_HASH_ROLE)
                assert removed_txid == txid, (idx, removed)
                removed += 1
        self.apply_filter()
        # update summary
        self.summary = r['summary']
        if not self.years and self.transactions:
            start_date = next(iter(
                self.transactions.values())).get('date') or date.today()
            end_date = next(iter(reversed(
                self.transactions.values()))).get('date') or date.today()
            self.years = [
                str(i) for i in range(start_date.year, end_date.year + 1)
            ]
            self.period_combo.insertItems(1, self.years)

    def update_fiat(self, txid, row):
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        items = self.txid_to_items[txid]
        self.ensure_fields_available(items, 7 if cap_gains else 5, txid)
        if not row['fiat_default'] and row['fiat_value']:
            items[5].setForeground(self.blue_brush)
        value_str = self.parent.fx.format_fiat(row['fiat_value'].value)
        items[5].setText(value_str)
        items[5].setData(row['fiat_value'].value, self.SORT_ROLE)
        # fixme: should use is_mine
        if row['value'].value < 0 and cap_gains:
            acq = row['acquisition_price'].value
            items[6].setText(self.parent.fx.format_fiat(acq))
            items[6].setData(acq, self.SORT_ROLE)
            cg = row['capital_gain'].value
            items[7].setText(self.parent.fx.format_fiat(cg))
            items[7].setData(cg, self.SORT_ROLE)

    def update_on_new_fee_histogram(self):
        pass
        # TODO update unconfirmed tx'es

    def on_edited(self, index, user_role, text):
        row, column = index.row(), index.column()
        item = self.item_from_coordinate(row, column)
        key = item.data(self.TX_HASH_ROLE)
        # fixme
        if column == 2:
            self.wallet.set_label(key, text)
            self.update_labels()
            self.parent.update_completions()
        elif column == 5:
            tx_item = self.transactions[key]
            self.wallet.set_fiat_value(key, self.parent.fx.ccy, text,
                                       self.parent.fx, tx_item['value'].value)
            value = tx_item['value'].value
            if value is not None:
                fee = tx_item['fee']
                fiat_fields = self.wallet.get_tx_item_fiat(
                    key, value, self.parent.fx, fee.value if fee else None)
                tx_item.update(fiat_fields)
                self.update_fiat(key, tx_item)
        else:
            assert False

    def mouseDoubleClickEvent(self, event: QMouseEvent):
        idx = self.indexAt(event.pos())
        item = self.item_from_coordinate(idx.row(), idx.column())
        if not item or item.isEditable():
            super().mouseDoubleClickEvent(event)
        elif item:
            tx_hash = item.data(self.TX_HASH_ROLE)
            self.show_transaction(tx_hash)

    def show_transaction(self, tx_hash):
        tx = self.wallet.transactions.get(tx_hash)
        if not tx:
            return
        label = self.wallet.get_label(
            tx_hash
        ) or None  # prefer 'None' if not defined (force tx dialog to hide Description field if missing)
        self.parent.show_transaction(tx, label)

    def update_labels(self):
        root = self.std_model.invisibleRootItem()
        child_count = root.rowCount()
        for i in range(child_count):
            item = root.child(i, 2)
            txid = item.data(self.TX_HASH_ROLE)
            label = self.wallet.get_label(txid)
            item.setText(label)

    def update_item(self, tx_hash, tx_mined_status):
        conf = tx_mined_status.conf
        status, status_str = self.wallet.get_tx_status(tx_hash,
                                                       tx_mined_status)
        icon = self.icon_cache.get(":icons/" + TX_ICONS[status])
        if tx_hash not in self.txid_to_items:
            return
        items = self.txid_to_items[tx_hash]
        items[0].setIcon(icon)
        items[0].setToolTip(
            str(conf) + _(" confirmation" + ("s" if conf != 1 else "")))
        items[0].setData((status, conf), self.SORT_ROLE)
        items[1].setText(status_str)

    def create_menu(self, position: QPoint):
        org_idx: QModelIndex = self.indexAt(position)
        idx = self.proxy.mapToSource(org_idx)
        item: QStandardItem = self.std_model.itemFromIndex(idx)
        if not item:
            # can happen e.g. before list is populated for the first time
            return
        tx_hash = idx.data(self.TX_HASH_ROLE)
        column = idx.column()
        assert tx_hash, "create_menu: no tx hash"
        tx = self.wallet.transactions.get(tx_hash)
        assert tx, "create_menu: no tx"
        if column == 0:
            column_title = _('Transaction ID')
            column_data = tx_hash
        else:
            column_title = self.std_model.horizontalHeaderItem(column).text()
            column_data = item.text()
        tx_URL = block_explorer_URL(self.config, 'tx', tx_hash)
        height = self.wallet.get_tx_height(tx_hash).height
        is_relevant, is_mine, v, fee = self.wallet.get_wallet_delta(tx)
        is_unconfirmed = height <= 0
        pr_key = self.wallet.invoices.paid.get(tx_hash)
        menu = QMenu()
        if height == TX_HEIGHT_LOCAL:
            menu.addAction(_("Remove"), lambda: self.remove_local_tx(tx_hash))
        menu.addAction(
            _("Copy {}").format(column_title),
            lambda: self.parent.app.clipboard().setText(column_data))
        for c in self.editable_columns:
            label = self.std_model.horizontalHeaderItem(c).text()
            # TODO use siblingAtColumn when min Qt version is >=5.11
            persistent = QPersistentModelIndex(
                org_idx.sibling(org_idx.row(), c))
            menu.addAction(_("Edit {}").format(label),
                           lambda p=persistent: self.edit(QModelIndex(p)))
        menu.addAction(_("Details"), lambda: self.show_transaction(tx_hash))
        if is_unconfirmed and tx:
            # note: the current implementation of RBF *needs* the old tx fee
            rbf = is_mine and not tx.is_final() and fee is not None
            if rbf:
                menu.addAction(_("Increase fee"),
                               lambda: self.parent.bump_fee_dialog(tx))
            else:
                child_tx = self.wallet.cpfp(tx, 0)
                if child_tx:
                    menu.addAction(_("Child pays for parent"),
                                   lambda: self.parent.cpfp(tx, child_tx))
        if pr_key:
            menu.addAction(self.icon_cache.get(":icons/seal"),
                           _("View invoice"),
                           lambda: self.parent.show_invoice(pr_key))
        if tx_URL:
            menu.addAction(_("View on block explorer"),
                           lambda: webbrowser.open(tx_URL))
        menu.exec_(self.viewport().mapToGlobal(position))

    def remove_local_tx(self, delete_tx):
        to_delete = {delete_tx}
        to_delete |= self.wallet.get_depending_transactions(delete_tx)
        question = _("Are you sure you want to remove this transaction?")
        if len(to_delete) > 1:
            question = _(
                "Are you sure you want to remove this transaction and {} child transactions?"
                .format(len(to_delete) - 1))
        answer = QMessageBox.question(self.parent, _("Please confirm"),
                                      question, QMessageBox.Yes,
                                      QMessageBox.No)
        if answer == QMessageBox.No:
            return
        for tx in to_delete:
            self.wallet.remove_transaction(tx)
        self.wallet.save_transactions(write=True)
        # need to update at least: history_list, utxo_list, address_list
        self.parent.need_update.set()

    def onFileAdded(self, fn):
        try:
            with open(fn) as f:
                tx = self.parent.tx_from_text(f.read())
                self.parent.save_transaction_into_wallet(tx)
        except IOError as e:
            self.parent.show_error(e)

    def export_history_dialog(self):
        d = WindowModalDialog(self, _('Export History'))
        d.setMinimumSize(400, 200)
        vbox = QVBoxLayout(d)
        defaultname = os.path.expanduser('~/electrum-history.csv')
        select_msg = _('Select file to export your wallet transactions to')
        hbox, filename_e, csv_button = filename_field(self, self.config,
                                                      defaultname, select_msg)
        vbox.addLayout(hbox)
        vbox.addStretch(1)
        hbox = Buttons(CancelButton(d), OkButton(d, _('Export')))
        vbox.addLayout(hbox)
        #run_hook('export_history_dialog', self, hbox)
        self.update()
        if not d.exec_():
            return
        filename = filename_e.text()
        if not filename:
            return
        try:
            self.do_export_history(filename, csv_button.isChecked())
        except (IOError, os.error) as reason:
            export_error_label = _(
                "Electrum was unable to produce a transaction export.")
            self.parent.show_critical(export_error_label + "\n" + str(reason),
                                      title=_("Unable to export history"))
            return
        self.parent.show_message(
            _("Your wallet history has been successfully exported."))

    def do_export_history(self, file_name, is_csv):
        hist = self.wallet.get_full_history(domain=self.get_domain(),
                                            from_timestamp=None,
                                            to_timestamp=None,
                                            fx=self.parent.fx,
                                            show_fees=True)
        txns = hist['transactions']
        lines = []
        if is_csv:
            for item in txns:
                lines.append([
                    item['txid'],
                    item.get('label', ''), item['confirmations'],
                    item['value'],
                    item.get('fiat_value', ''),
                    item.get('fee', ''),
                    item.get('fiat_fee', ''), item['date']
                ])
        with open(file_name, "w+", encoding='utf-8') as f:
            if is_csv:
                import csv
                transaction = csv.writer(f, lineterminator='\n')
                transaction.writerow([
                    "transaction_hash", "label", "confirmations", "value",
                    "fiat_value", "fee", "fiat_fee", "timestamp"
                ])
                for line in lines:
                    transaction.writerow(line)
            else:
                from electrum.util import json_encode
                f.write(json_encode(txns))
예제 #12
0
class HistoryList(MyTreeView, AcceptFileDragDrop):
    filter_columns = [1, 2, 3]  # Date, Description, Amount
    TX_HASH_ROLE = Qt.UserRole
    SORT_ROLE = Qt.UserRole + 1

    def should_hide(self, proxy_row):
        if self.start_timestamp and self.end_timestamp:
            item = self.item_from_coordinate(proxy_row, 0)
            txid = item.data(self.TX_HASH_ROLE)
            date = self.transactions[txid]['date']
            if date:
                in_interval = self.start_timestamp <= date <= self.end_timestamp
                if not in_interval:
                    return True
            return False

    def __init__(self, parent=None):
        super().__init__(parent, self.create_menu, 2)
        self.std_model = QStandardItemModel(self)
        self.proxy = HistorySortModel(self)
        self.proxy.setSourceModel(self.std_model)
        self.setModel(self.proxy)

        self.txid_to_items = {}
        self.transactions = OrderedDictWithIndex()
        self.summary = {}
        self.blue_brush = QBrush(QColor("#1E1EFF"))
        self.red_brush = QBrush(QColor("#BC1E1E"))
        self.monospace_font = QFont(MONOSPACE_FONT)
        self.config = parent.config
        AcceptFileDragDrop.__init__(self, ".txn")
        self.setSortingEnabled(True)
        self.start_timestamp = None
        self.end_timestamp = None
        self.years = []
        self.create_toolbar_buttons()
        self.wallet = self.parent.wallet  # type: Abstract_Wallet
        self.refresh_headers()
        self.sortByColumn(0, Qt.AscendingOrder)

    def format_date(self, d):
        return str(datetime.date(d.year, d.month, d.day)) if d else _('None')

    def refresh_headers(self):
        headers = ['', _('Date'), _('Description'), _('Amount'), _('Balance')]
        fx = self.parent.fx
        if fx and fx.show_history():
            headers.extend(['%s '%fx.ccy + _('Value')])
            self.editable_columns |= {5}
            if fx.get_history_capital_gains_config():
                headers.extend(['%s '%fx.ccy + _('Acquisition price')])
                headers.extend(['%s '%fx.ccy + _('Capital Gains')])
        else:
            self.editable_columns -= {5}
        col_count = self.std_model.columnCount()
        diff = col_count-len(headers)
        if col_count > len(headers):
            if diff == 2:
                self.std_model.removeColumns(6, diff)
            else:
                assert diff in [1, 3]
                self.std_model.removeColumns(5, diff)
            for items in self.txid_to_items.values():
                while len(items) > col_count:
                    items.pop()
        elif col_count < len(headers):
            self.std_model.clear()
            self.txid_to_items.clear()
            self.transactions.clear()
            self.summary.clear()
        self.update_headers(headers, self.std_model)

    def get_domain(self):
        '''Replaced in address_dialog.py'''
        return self.wallet.get_addresses()

    def on_combo(self, x):
        s = self.period_combo.itemText(x)
        x = s == _('Custom')
        self.start_button.setEnabled(x)
        self.end_button.setEnabled(x)
        if s == _('All'):
            self.start_timestamp = None
            self.end_timestamp = None
            self.start_button.setText("-")
            self.end_button.setText("-")
        else:
            try:
                year = int(s)
            except:
                return
            self.start_timestamp = start_date = datetime.datetime(year, 1, 1)
            self.end_timestamp = end_date = datetime.datetime(year+1, 1, 1)
            self.start_button.setText(_('From') + ' ' + self.format_date(start_date))
            self.end_button.setText(_('To') + ' ' + self.format_date(end_date))
        self.hide_rows()

    def create_toolbar_buttons(self):
        self.period_combo = QComboBox()
        self.start_button = QPushButton('-')
        self.start_button.pressed.connect(self.select_start_date)
        self.start_button.setEnabled(False)
        self.end_button = QPushButton('-')
        self.end_button.pressed.connect(self.select_end_date)
        self.end_button.setEnabled(False)
        self.period_combo.addItems([_('All'), _('Custom')])
        self.period_combo.activated.connect(self.on_combo)

    def get_toolbar_buttons(self):
        return self.period_combo, self.start_button, self.end_button

    def on_hide_toolbar(self):
        self.start_timestamp = None
        self.end_timestamp = None
        self.hide_rows()

    def save_toolbar_state(self, state, config):
        config.set_key('show_toolbar_history', state)

    def select_start_date(self):
        self.start_timestamp = self.select_date(self.start_button)
        self.hide_rows()

    def select_end_date(self):
        self.end_timestamp = self.select_date(self.end_button)
        self.hide_rows()

    def select_date(self, button):
        d = WindowModalDialog(self, _("Select date"))
        d.setMinimumSize(600, 150)
        d.date = None
        vbox = QVBoxLayout()
        def on_date(date):
            d.date = date
        cal = QCalendarWidget()
        cal.setGridVisible(True)
        cal.clicked[QDate].connect(on_date)
        vbox.addWidget(cal)
        vbox.addLayout(Buttons(OkButton(d), CancelButton(d)))
        d.setLayout(vbox)
        if d.exec_():
            if d.date is None:
                return None
            date = d.date.toPyDate()
            button.setText(self.format_date(date))
            return datetime.datetime(date.year, date.month, date.day)

    def show_summary(self):
        h = self.summary
        if not h:
            self.parent.show_message(_("Nothing to summarize."))
            return
        start_date = h.get('start_date')
        end_date = h.get('end_date')
        format_amount = lambda x: self.parent.format_amount(x.value) + ' ' + self.parent.base_unit()
        d = WindowModalDialog(self, _("Summary"))
        d.setMinimumSize(600, 150)
        vbox = QVBoxLayout()
        grid = QGridLayout()
        grid.addWidget(QLabel(_("Start")), 0, 0)
        grid.addWidget(QLabel(self.format_date(start_date)), 0, 1)
        grid.addWidget(QLabel(str(h.get('start_fiat_value')) + f'/{constants.net.CODE}'), 0, 2)
        grid.addWidget(QLabel(_("Initial balance")), 1, 0)
        grid.addWidget(QLabel(format_amount(h['start_balance'])), 1, 1)
        grid.addWidget(QLabel(str(h.get('start_fiat_balance'))), 1, 2)
        grid.addWidget(QLabel(_("End")), 2, 0)
        grid.addWidget(QLabel(self.format_date(end_date)), 2, 1)
        grid.addWidget(QLabel(str(h.get('end_fiat_value')) + f'/{constants.net.CODE}'), 2, 2)
        grid.addWidget(QLabel(_("Final balance")), 4, 0)
        grid.addWidget(QLabel(format_amount(h['end_balance'])), 4, 1)
        grid.addWidget(QLabel(str(h.get('end_fiat_balance'))), 4, 2)
        grid.addWidget(QLabel(_("Income")), 5, 0)
        grid.addWidget(QLabel(format_amount(h.get('income'))), 5, 1)
        grid.addWidget(QLabel(str(h.get('fiat_income'))), 5, 2)
        grid.addWidget(QLabel(_("Expenditures")), 6, 0)
        grid.addWidget(QLabel(format_amount(h.get('expenditures'))), 6, 1)
        grid.addWidget(QLabel(str(h.get('fiat_expenditures'))), 6, 2)
        grid.addWidget(QLabel(_("Capital gains")), 7, 0)
        grid.addWidget(QLabel(str(h.get('capital_gains'))), 7, 2)
        grid.addWidget(QLabel(_("Unrealized gains")), 8, 0)
        grid.addWidget(QLabel(str(h.get('unrealized_gains', ''))), 8, 2)
        vbox.addLayout(grid)
        vbox.addLayout(Buttons(CloseButton(d)))
        d.setLayout(vbox)
        d.exec_()

    def plot_history_dialog(self):
        if plot_history is None:
            self.parent.show_message(
                _("Can't plot history.") + '\n' +
                _("Perhaps some dependencies are missing...") + " (matplotlib?)")
            return
        try:
            plt = plot_history(list(self.transactions.values()))
            plt.show()
        except NothingToPlotException as e:
            self.parent.show_message(str(e))

    def insert_tx(self, tx_item):
        fx = self.parent.fx
        tx_hash = tx_item['txid']
        height = tx_item['height']
        conf = tx_item['confirmations']
        timestamp = tx_item['timestamp']
        value = tx_item['value'].value
        balance = tx_item['balance'].value
        label = tx_item['label']
        tx_mined_status = TxMinedInfo(height=height, conf=conf, timestamp=timestamp)
        status, status_str = self.wallet.get_tx_status(tx_hash, tx_mined_status)
        has_invoice = self.wallet.invoices.paid.get(tx_hash)
        v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True)
        balance_str = self.parent.format_amount(balance, whitespaces=True)
        entry = ['', status_str, label, v_str, balance_str]
        item = [QStandardItem(e) for e in entry]
        item[3].setData(value, self.SORT_ROLE)
        item[4].setData(balance, self.SORT_ROLE)
        if has_invoice:
            item[2].setIcon(self.icon_cache.get(":icons/seal"))
        for i in range(len(entry)):
            self.set_item_properties(item[i], i, tx_hash)
        if value and value < 0:
            item[2].setForeground(self.red_brush)
            item[3].setForeground(self.red_brush)
        self.txid_to_items[tx_hash] = item
        self.update_item(tx_hash, self.wallet.get_tx_height(tx_hash))
        source_row_idx = self.std_model.rowCount()
        self.std_model.insertRow(source_row_idx, item)
        new_idx = self.std_model.index(source_row_idx, 0)
        history = fx.show_history()
        if history:
            self.update_fiat(tx_hash, tx_item)
        self.hide_row(self.proxy.mapFromSource(new_idx).row())

    def set_item_properties(self, item, i, tx_hash):
        if i>2:
            item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter)
        if i!=1:
            item.setFont(self.monospace_font)
        item.setEditable(i in self.editable_columns)
        item.setData(tx_hash, self.TX_HASH_ROLE)

    def ensure_fields_available(self, items, idx, txid):
        while len(items) < idx + 1:
            row = self.transactions.get_pos_of_key(txid)
            qidx = self.std_model.index(row, len(items))
            assert qidx.isValid(), (self.std_model.columnCount(), idx)
            item = self.std_model.itemFromIndex(qidx)
            self.set_item_properties(item, len(items), txid)
            items.append(item)

    @profiler
    def update(self):
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        r = self.wallet.get_full_history(domain=self.get_domain(), from_timestamp=None, to_timestamp=None, fx=fx)
        seen = set()
        history = fx.show_history()
        tx_list = list(self.transactions.values())
        if r['transactions'] == tx_list:
            return
        if r['transactions'][:-1] == tx_list:
            print_error('history_list: one new transaction')
            row = r['transactions'][-1]
            txid = row['txid']
            if txid not in self.transactions:
                self.transactions[txid] = row
                self.insert_tx(row)
                return
            else:
                print_error('history_list: tx added but txid is already in list (weird), txid: ', txid)
        for idx, row in enumerate(r['transactions']):
            txid = row['txid']
            seen.add(txid)
            if txid not in self.transactions:
                self.transactions[txid] = row
                self.insert_tx(row)
                continue
            old = self.transactions[txid]
            if old == row:
                continue
            self.update_item(txid, self.wallet.get_tx_height(txid))
            if history:
                self.update_fiat(txid, row)
            balance_str = self.parent.format_amount(row['balance'].value, whitespaces=True)
            self.txid_to_items[txid][4].setText(balance_str)
            self.txid_to_items[txid][4].setData(row['balance'].value, self.SORT_ROLE)
            old.clear()
            old.update(**row)
        removed = 0
        l = list(enumerate(self.transactions.keys()))
        for idx, txid in l:
            if txid not in seen:
                del self.transactions[txid]
                del self.txid_to_items[txid]
                items = self.std_model.takeRow(idx - removed)
                removed_txid = items[0].data(self.TX_HASH_ROLE)
                assert removed_txid == txid, (idx, removed)
                removed += 1
        self.apply_filter()
        # update summary
        self.summary = r['summary']
        if not self.years and self.transactions:
            start_date = next(iter(self.transactions.values())).get('date') or date.today()
            end_date = next(iter(reversed(self.transactions.values()))).get('date') or date.today()
            self.years = [str(i) for i in range(start_date.year, end_date.year + 1)]
            self.period_combo.insertItems(1, self.years)

    def update_fiat(self, txid, row):
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        items = self.txid_to_items[txid]
        self.ensure_fields_available(items, 7 if cap_gains else 5, txid)
        if not row['fiat_default'] and row['fiat_value']:
            items[5].setForeground(self.blue_brush)
        value_str = self.parent.fx.format_fiat(row['fiat_value'].value)
        items[5].setText(value_str)
        items[5].setData(row['fiat_value'].value, self.SORT_ROLE)
        # fixme: should use is_mine
        if row['value'].value < 0 and cap_gains:
            acq = row['acquisition_price'].value
            items[6].setText(self.parent.fx.format_fiat(acq))
            items[6].setData(acq, self.SORT_ROLE)
            cg = row['capital_gain'].value
            items[7].setText(self.parent.fx.format_fiat(cg))
            items[7].setData(cg, self.SORT_ROLE)

    def update_on_new_fee_histogram(self):
        pass
        # TODO update unconfirmed tx'es

    def on_edited(self, index, user_role, text):
        row, column = index.row(), index.column()
        item = self.item_from_coordinate(row, column)
        key = item.data(self.TX_HASH_ROLE)
        # fixme
        if column == 2:
            self.wallet.set_label(key, text)
            self.update_labels()
            self.parent.update_completions()
        elif column == 5:
            tx_item = self.transactions[key]
            self.wallet.set_fiat_value(key, self.parent.fx.ccy, text, self.parent.fx, tx_item['value'].value)
            value = tx_item['value'].value
            if value is not None:
                fee = tx_item['fee']
                fiat_fields = self.wallet.get_tx_item_fiat(key, value, self.parent.fx, fee.value if fee else None)
                tx_item.update(fiat_fields)
                self.update_fiat(key, tx_item)
        else:
            assert False

    def mouseDoubleClickEvent(self, event: QMouseEvent):
        idx = self.indexAt(event.pos())
        item = self.item_from_coordinate(idx.row(), idx.column())
        if not item or item.isEditable():
            super().mouseDoubleClickEvent(event)
        elif item:
            tx_hash = item.data(self.TX_HASH_ROLE)
            self.show_transaction(tx_hash)

    def show_transaction(self, tx_hash):
        tx = self.wallet.transactions.get(tx_hash)
        if not tx:
            return
        label = self.wallet.get_label(tx_hash) or None # prefer 'None' if not defined (force tx dialog to hide Description field if missing)
        self.parent.show_transaction(tx, label)

    def update_labels(self):
        root = self.std_model.invisibleRootItem()
        child_count = root.rowCount()
        for i in range(child_count):
            item = root.child(i, 2)
            txid = item.data(self.TX_HASH_ROLE)
            label = self.wallet.get_label(txid)
            item.setText(label)

    def update_item(self, tx_hash, tx_mined_status):
        conf = tx_mined_status.conf
        status, status_str = self.wallet.get_tx_status(tx_hash, tx_mined_status)
        icon = self.icon_cache.get(":icons/" +  TX_ICONS[status])
        if tx_hash not in self.txid_to_items:
            return
        items = self.txid_to_items[tx_hash]
        items[0].setIcon(icon)
        items[0].setToolTip(str(conf) + _(" confirmation" + ("s" if conf != 1 else "")))
        items[0].setData((status, conf), self.SORT_ROLE)
        items[1].setText(status_str)

    def create_menu(self, position: QPoint):
        org_idx: QModelIndex = self.indexAt(position)
        idx = self.proxy.mapToSource(org_idx)
        item: QStandardItem = self.std_model.itemFromIndex(idx)
        if not item:
            # can happen e.g. before list is populated for the first time
            return
        tx_hash = idx.data(self.TX_HASH_ROLE)
        column = idx.column()
        assert tx_hash, "create_menu: no tx hash"
        tx = self.wallet.transactions.get(tx_hash)
        assert tx, "create_menu: no tx"
        if column == 0:
            column_title = _('Transaction ID')
            column_data = tx_hash
        else:
            column_title = self.std_model.horizontalHeaderItem(column).text()
            column_data = item.text()
        tx_URL = block_explorer_URL(self.config, 'tx', tx_hash)
        height = self.wallet.get_tx_height(tx_hash).height
        is_relevant, is_mine, v, fee = self.wallet.get_wallet_delta(tx)
        is_unconfirmed = height <= 0
        pr_key = self.wallet.invoices.paid.get(tx_hash)
        menu = QMenu()
        if height == TX_HEIGHT_LOCAL:
            menu.addAction(_("Remove"), lambda: self.remove_local_tx(tx_hash))
        menu.addAction(_("Copy {}").format(column_title), lambda: self.parent.app.clipboard().setText(column_data))
        for c in self.editable_columns:
            label = self.std_model.horizontalHeaderItem(c).text()
            # TODO use siblingAtColumn when min Qt version is >=5.11
            persistent = QPersistentModelIndex(org_idx.sibling(org_idx.row(), c))
            menu.addAction(_("Edit {}").format(label), lambda p=persistent: self.edit(QModelIndex(p)))
        menu.addAction(_("Details"), lambda: self.show_transaction(tx_hash))
        if is_unconfirmed and tx:
            # note: the current implementation of RBF *needs* the old tx fee
            rbf = is_mine and not tx.is_final() and fee is not None
            if rbf:
                menu.addAction(_("Increase fee"), lambda: self.parent.bump_fee_dialog(tx))
            else:
                child_tx = self.wallet.cpfp(tx, 0)
                if child_tx:
                    menu.addAction(_("Child pays for parent"), lambda: self.parent.cpfp(tx, child_tx))
        if pr_key:
            menu.addAction(self.icon_cache.get(":icons/seal"), _("View invoice"), lambda: self.parent.show_invoice(pr_key))
        if tx_URL:
            menu.addAction(_("View on block explorer"), lambda: webbrowser.open(tx_URL))
        menu.exec_(self.viewport().mapToGlobal(position))

    def remove_local_tx(self, delete_tx):
        to_delete = {delete_tx}
        to_delete |= self.wallet.get_depending_transactions(delete_tx)
        question = _("Are you sure you want to remove this transaction?")
        if len(to_delete) > 1:
            question = _(
                "Are you sure you want to remove this transaction and {} child transactions?".format(len(to_delete) - 1)
            )
        answer = QMessageBox.question(self.parent, _("Please confirm"), question, QMessageBox.Yes, QMessageBox.No)
        if answer == QMessageBox.No:
            return
        for tx in to_delete:
            self.wallet.remove_transaction(tx)
        self.wallet.save_transactions(write=True)
        # need to update at least: history_list, utxo_list, address_list
        self.parent.need_update.set()

    def onFileAdded(self, fn):
        try:
            with open(fn) as f:
                tx = self.parent.tx_from_text(f.read())
                self.parent.save_transaction_into_wallet(tx)
        except IOError as e:
            self.parent.show_error(e)

    def export_history_dialog(self):
        d = WindowModalDialog(self, _('Export History'))
        d.setMinimumSize(400, 200)
        vbox = QVBoxLayout(d)
        defaultname = os.path.expanduser('~/electrum-history.csv')
        select_msg = _('Select file to export your wallet transactions to')
        hbox, filename_e, csv_button = filename_field(self, self.config, defaultname, select_msg)
        vbox.addLayout(hbox)
        vbox.addStretch(1)
        hbox = Buttons(CancelButton(d), OkButton(d, _('Export')))
        vbox.addLayout(hbox)
        #run_hook('export_history_dialog', self, hbox)
        self.update()
        if not d.exec_():
            return
        filename = filename_e.text()
        if not filename:
            return
        try:
            self.do_export_history(filename, csv_button.isChecked())
        except (IOError, os.error) as reason:
            export_error_label = _("Electrum was unable to produce a transaction export.")
            self.parent.show_critical(export_error_label + "\n" + str(reason), title=_("Unable to export history"))
            return
        self.parent.show_message(_("Your wallet history has been successfully exported."))

    def do_export_history(self, file_name, is_csv):
        hist = self.wallet.get_full_history(domain=self.get_domain(),
                                            from_timestamp=None,
                                            to_timestamp=None,
                                            fx=self.parent.fx,
                                            show_fees=True)
        txns = hist['transactions']
        lines = []
        if is_csv:
            for item in txns:
                lines.append([item['txid'],
                              item.get('label', ''),
                              item['confirmations'],
                              item['value'],
                              item.get('fiat_value', ''),
                              item.get('fee', ''),
                              item.get('fiat_fee', ''),
                              item['date']])
        with open(file_name, "w+", encoding='utf-8') as f:
            if is_csv:
                import csv
                transaction = csv.writer(f, lineterminator='\n')
                transaction.writerow(["transaction_hash",
                                      "label",
                                      "confirmations",
                                      "value",
                                      "fiat_value",
                                      "fee",
                                      "fiat_fee",
                                      "timestamp"])
                for line in lines:
                    transaction.writerow(line)
            else:
                from electrum.util import json_encode
                f.write(json_encode(txns))
예제 #13
0
class HistoryModel(QAbstractItemModel, PrintError):

    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent
        self.view = None  # type: HistoryList
        self.transactions = OrderedDictWithIndex()
        self.tx_status_cache = {}  # type: Dict[str, Tuple[int, str]]
        self.summary = None

    def set_view(self, history_list: 'HistoryList'):
        # FIXME HistoryModel and HistoryList mutually depend on each other.
        # After constructing both, this method needs to be called.
        self.view = history_list  # type: HistoryList
        self.set_visibility_of_columns()

    def columnCount(self, parent: QModelIndex):
        return len(HistoryColumns)

    def rowCount(self, parent: QModelIndex):
        return len(self.transactions)

    def index(self, row: int, column: int, parent: QModelIndex):
        return self.createIndex(row, column)

    def data(self, index: QModelIndex, role: Qt.ItemDataRole) -> QVariant:
        # note: this method is performance-critical.
        # it is called a lot, and so must run extremely fast.
        assert index.isValid()
        col = index.column()
        tx_item = self.transactions.value_from_pos(index.row())
        tx_hash = tx_item['txid']
        conf = tx_item['confirmations']
        txpos = tx_item['txpos_in_block'] or 0
        height = tx_item['height']
        try:
            status, status_str = self.tx_status_cache[tx_hash]
        except KeyError:
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            status, status_str = self.parent.wallet.get_tx_status(tx_hash, tx_mined_info)
        if role == Qt.UserRole:
            # for sorting
            d = {
                HistoryColumns.STATUS_ICON:
                    # height breaks ties for unverified txns
                    # txpos breaks ties for verified same block txns
                    (status, conf, -height, -txpos),
                HistoryColumns.STATUS_TEXT: status_str,
                HistoryColumns.DESCRIPTION: tx_item['label'],
                HistoryColumns.COIN_VALUE:  tx_item['value'].value,
                HistoryColumns.RUNNING_COIN_BALANCE: tx_item['balance'].value,
                HistoryColumns.FIAT_VALUE:
                    tx_item['fiat_value'].value if 'fiat_value' in tx_item else None,
                HistoryColumns.FIAT_ACQ_PRICE:
                    tx_item['acquisition_price'].value if 'acquisition_price' in tx_item else None,
                HistoryColumns.FIAT_CAP_GAINS:
                    tx_item['capital_gain'].value if 'capital_gain' in tx_item else None,
                HistoryColumns.TXID: tx_hash,
            }
            return QVariant(d[col])
        if role not in (Qt.DisplayRole, Qt.EditRole):
            if col == HistoryColumns.STATUS_ICON and role == Qt.DecorationRole:
                return QVariant(read_QIcon(TX_ICONS[status]))
            elif col == HistoryColumns.STATUS_ICON and role == Qt.ToolTipRole:
                return QVariant(str(conf) + _(" confirmation" + ("s" if conf != 1 else "")))
            elif col > HistoryColumns.DESCRIPTION and role == Qt.TextAlignmentRole:
                return QVariant(Qt.AlignRight | Qt.AlignVCenter)
            elif col != HistoryColumns.STATUS_TEXT and role == Qt.FontRole:
                monospace_font = QFont(MONOSPACE_FONT)
                return QVariant(monospace_font)
            elif col == HistoryColumns.DESCRIPTION and role == Qt.DecorationRole \
                    and self.parent.wallet.invoices.paid.get(tx_hash):
                return QVariant(read_QIcon("seal"))
            elif col in (HistoryColumns.DESCRIPTION, HistoryColumns.COIN_VALUE) \
                    and role == Qt.ForegroundRole and tx_item['value'].value < 0:
                red_brush = QBrush(QColor("#BC1E1E"))
                return QVariant(red_brush)
            elif col == HistoryColumns.FIAT_VALUE and role == Qt.ForegroundRole \
                    and not tx_item.get('fiat_default') and tx_item.get('fiat_value') is not None:
                blue_brush = QBrush(QColor("#1E1EFF"))
                return QVariant(blue_brush)
            return QVariant()
        if col == HistoryColumns.STATUS_TEXT:
            return QVariant(status_str)
        elif col == HistoryColumns.DESCRIPTION:
            return QVariant(tx_item['label'])
        elif col == HistoryColumns.COIN_VALUE:
            value = tx_item['value'].value
            v_str = self.parent.format_amount(value, is_diff=True, whitespaces=True)
            return QVariant(v_str)
        elif col == HistoryColumns.RUNNING_COIN_BALANCE:
            balance = tx_item['balance'].value
            balance_str = self.parent.format_amount(balance, whitespaces=True)
            return QVariant(balance_str)
        elif col == HistoryColumns.FIAT_VALUE and 'fiat_value' in tx_item:
            value_str = self.parent.fx.format_fiat(tx_item['fiat_value'].value)
            return QVariant(value_str)
        elif col == HistoryColumns.FIAT_ACQ_PRICE and \
                tx_item['value'].value < 0 and 'acquisition_price' in tx_item:
            # fixme: should use is_mine
            acq = tx_item['acquisition_price'].value
            return QVariant(self.parent.fx.format_fiat(acq))
        elif col == HistoryColumns.FIAT_CAP_GAINS and 'capital_gain' in tx_item:
            cg = tx_item['capital_gain'].value
            return QVariant(self.parent.fx.format_fiat(cg))
        elif col == HistoryColumns.TXID:
            return QVariant(tx_hash)
        return QVariant()

    def parent(self, index: QModelIndex):
        return QModelIndex()

    def hasChildren(self, index: QModelIndex):
        return not index.isValid()

    def update_label(self, row):
        tx_item = self.transactions.value_from_pos(row)
        tx_item['label'] = self.parent.wallet.get_label(tx_item['txid'])
        topLeft = bottomRight = self.createIndex(row, 2)
        self.dataChanged.emit(topLeft, bottomRight, [Qt.DisplayRole])

    def get_domain(self):
        '''Overridden in address_dialog.py'''
        return self.parent.wallet.get_addresses()

    @profiler
    def refresh(self, reason: str):
        self.print_error(f"refreshing... reason: {reason}")
        assert self.parent.gui_thread == threading.current_thread(), 'must be called from GUI thread'
        assert self.view, 'view not set'
        selected = self.view.selectionModel().currentIndex()
        selected_row = None
        if selected:
            selected_row = selected.row()
        fx = self.parent.fx
        if fx: fx.history_used_spot = False
        r = self.parent.wallet.get_full_history(domain=self.get_domain(), from_timestamp=None, to_timestamp=None, fx=fx)
        self.set_visibility_of_columns()
        if r['transactions'] == list(self.transactions.values()):
            return
        old_length = len(self.transactions)
        if old_length != 0:
            self.beginRemoveRows(QModelIndex(), 0, old_length)
            self.transactions.clear()
            self.endRemoveRows()
        self.beginInsertRows(QModelIndex(), 0, len(r['transactions'])-1)
        for tx_item in r['transactions']:
            txid = tx_item['txid']
            self.transactions[txid] = tx_item
        self.endInsertRows()
        if selected_row:
            self.view.selectionModel().select(self.createIndex(selected_row, 0), QItemSelectionModel.Rows | QItemSelectionModel.SelectCurrent)
        f = self.view.current_filter
        if f:
            self.view.filter(f)
        # update summary
        self.summary = r['summary']
        if not self.view.years and self.transactions:
            start_date = date.today()
            end_date = date.today()
            if len(self.transactions) > 0:
                start_date = self.transactions.value_from_pos(0).get('date') or start_date
                end_date = self.transactions.value_from_pos(len(self.transactions) - 1).get('date') or end_date
            self.view.years = [str(i) for i in range(start_date.year, end_date.year + 1)]
            self.view.period_combo.insertItems(1, self.view.years)
        # update tx_status_cache
        self.tx_status_cache.clear()
        for txid, tx_item in self.transactions.items():
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            self.tx_status_cache[txid] = self.parent.wallet.get_tx_status(txid, tx_mined_info)

    def set_visibility_of_columns(self):
        def set_visible(col: int, b: bool):
            self.view.showColumn(col) if b else self.view.hideColumn(col)
        # txid
        set_visible(HistoryColumns.TXID, False)
        # fiat
        history = self.parent.fx.show_history()
        cap_gains = self.parent.fx.get_history_capital_gains_config()
        set_visible(HistoryColumns.FIAT_VALUE, history)
        set_visible(HistoryColumns.FIAT_ACQ_PRICE, history and cap_gains)
        set_visible(HistoryColumns.FIAT_CAP_GAINS, history and cap_gains)

    def update_fiat(self, row, idx):
        tx_item = self.transactions.value_from_pos(row)
        key = tx_item['txid']
        fee = tx_item.get('fee')
        value = tx_item['value'].value
        fiat_fields = self.parent.wallet.get_tx_item_fiat(key, value, self.parent.fx, fee.value if fee else None)
        tx_item.update(fiat_fields)
        self.dataChanged.emit(idx, idx, [Qt.DisplayRole, Qt.ForegroundRole])

    def update_tx_mined_status(self, tx_hash: str, tx_mined_info: TxMinedInfo):
        try:
            row = self.transactions.pos_from_key(tx_hash)
            tx_item = self.transactions[tx_hash]
        except KeyError:
            return
        self.tx_status_cache[tx_hash] = self.parent.wallet.get_tx_status(tx_hash, tx_mined_info)
        tx_item.update({
            'confirmations':  tx_mined_info.conf,
            'timestamp':      tx_mined_info.timestamp,
            'txpos_in_block': tx_mined_info.txpos,
            'date':           timestamp_to_datetime(tx_mined_info.timestamp),
        })
        topLeft = self.createIndex(row, 0)
        bottomRight = self.createIndex(row, len(HistoryColumns) - 1)
        self.dataChanged.emit(topLeft, bottomRight)

    def on_fee_histogram(self):
        for tx_hash, tx_item in list(self.transactions.items()):
            tx_mined_info = self.tx_mined_info_from_tx_item(tx_item)
            if tx_mined_info.conf > 0:
                # note: we could actually break here if we wanted to rely on the order of txns in self.transactions
                continue
            self.update_tx_mined_status(tx_hash, tx_mined_info)

    def headerData(self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole):
        assert orientation == Qt.Horizontal
        if role != Qt.DisplayRole:
            return None
        fx = self.parent.fx
        fiat_title = 'n/a fiat value'
        fiat_acq_title = 'n/a fiat acquisition price'
        fiat_cg_title = 'n/a fiat capital gains'
        if fx and fx.show_history():
            fiat_title = '%s '%fx.ccy + _('Value')
            fiat_acq_title = '%s '%fx.ccy + _('Acquisition price')
            fiat_cg_title =  '%s '%fx.ccy + _('Capital Gains')
        return {
            HistoryColumns.STATUS_ICON: '',
            HistoryColumns.STATUS_TEXT: _('Date'),
            HistoryColumns.DESCRIPTION: _('Description'),
            HistoryColumns.COIN_VALUE: _('Amount'),
            HistoryColumns.RUNNING_COIN_BALANCE: _('Balance'),
            HistoryColumns.FIAT_VALUE: fiat_title,
            HistoryColumns.FIAT_ACQ_PRICE: fiat_acq_title,
            HistoryColumns.FIAT_CAP_GAINS: fiat_cg_title,
            HistoryColumns.TXID: 'TXID',
        }[section]

    def flags(self, idx):
        extra_flags = Qt.NoItemFlags # type: Qt.ItemFlag
        if idx.column() in self.view.editable_columns:
            extra_flags |= Qt.ItemIsEditable
        return super().flags(idx) | extra_flags

    @staticmethod
    def tx_mined_info_from_tx_item(tx_item):
        tx_mined_info = TxMinedInfo(height=tx_item['height'],
                                    conf=tx_item['confirmations'],
                                    timestamp=tx_item['timestamp'])
        return tx_mined_info