Ejemplo n.º 1
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
Ejemplo n.º 2
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
Ejemplo n.º 3
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
Ejemplo n.º 4
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
Ejemplo n.º 5
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