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
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) if not is_lightning else QVariant('') 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, 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' 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