/
main_window.py
2723 lines (2348 loc) · 110 KB
/
main_window.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ElectrumSV - lightweight Bitcoin client
# Copyright (C) 2012 thomasv@gitorious
# Copyright (C) 2019-2020 The ElectrumSV Developers
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import asyncio
import base64
from collections import Counter
import csv
from decimal import Decimal
from functools import partial
import json
import os
import shutil
import threading
import time
from typing import Callable, Iterable, List, Tuple, Optional
import weakref
import webbrowser
from bitcoinx import PublicKey, hash_to_hex_str
from PyQt5.QtCore import pyqtSignal, Qt, QSize, QStringListModel, QTimer, QUrl, QRect
from PyQt5.QtGui import QKeySequence, QCursor, QDesktopServices
from PyQt5.QtWidgets import (
QPushButton, QMainWindow, QSizePolicy, QShortcut, QFileDialog, QMenuBar,
QMessageBox, QGridLayout, QLineEdit, QLabel, QComboBox, QHBoxLayout,
QVBoxLayout, QWidget, QCompleter, QMenu, QTreeWidgetItem, QTextEdit,
QInputDialog, QToolBar, QAction, QPlainTextEdit, QTreeView, QDialog
)
import electrumsv
from electrumsv import bitcoin, commands, paymentrequest, qrscanner, util
from electrumsv.app_state import app_state
from electrumsv.bitcoin import (COIN, is_address_valid, address_from_string,
script_template_to_string)
from electrumsv.constants import DATABASE_EXT, RECEIVING_SUBPATH, TxFlags, PaymentState
from electrumsv.exceptions import NotEnoughFunds, UserCancelled, ExcessiveFee
from electrumsv.i18n import _
from electrumsv.keystore import Hardware_KeyStore
from electrumsv.logs import logs
from electrumsv.network import broadcast_failure_reason
from electrumsv.networks import Net
from electrumsv.storage import WalletStorage
from electrumsv.transaction import (Transaction, txdict_from_str, tx_output_to_display_text,
XTxOutput)
from electrumsv.util import (
format_time, format_satoshis, format_satoshis_plain, bh2u, format_fee_satoshis,
get_update_check_dates, get_identified_release_signers, profiler, get_wallet_name_from_path,
)
from electrumsv.version import PACKAGE_VERSION
from electrumsv.wallet import AbstractAccount, UTXO, Wallet
from electrumsv.wallet_database.tables import KeyInstanceRow
import electrumsv.web as web
from .amountedit import AmountEdit, BTCAmountEdit, MyLineEdit
from .contact_list import ContactList, edit_contact_dialog
from . import dialogs
from .qrcodewidget import QRCodeWidget, QRDialog
from .qrtextedit import ShowQRTextEdit
from .util import (
MessageBoxMixin, ColorScheme, HelpLabel, expiration_values, ButtonsLineEdit,
WindowModalDialog, Buttons, CopyCloseButton, MyTreeWidget, EnterButton,
WaitingDialog, ChoicesLayout, OkButton, WWLabel, read_QIcon,
CloseButton, CancelButton, text_dialog, filename_field,
update_fixed_tree_height, UntrustedMessageDialog, protected,
can_show_in_file_explorer, show_in_file_explorer, create_new_wallet,
FormSectionWidget
)
from .wallet_api import WalletAPI
logger = logs.get_logger("mainwindow")
class ElectrumWindow(QMainWindow, MessageBoxMixin):
payment_request_ok_signal = pyqtSignal()
payment_request_error_signal = pyqtSignal()
notify_transactions_signal = pyqtSignal()
new_fx_quotes_signal = pyqtSignal()
new_fx_history_signal = pyqtSignal()
network_signal = pyqtSignal(str, object)
history_updated_signal = pyqtSignal()
network_status_signal = pyqtSignal()
account_created_signal = pyqtSignal(int)
account_change_signal = pyqtSignal(int)
keys_updated_signal = pyqtSignal(object, object, object)
keys_created_signal = pyqtSignal(object, object, object)
transaction_state_signal = pyqtSignal(object, object, object, object, object)
transaction_added_signal = pyqtSignal(object, object, object)
transaction_deleted_signal = pyqtSignal(object, object, object)
def __init__(self, wallet: Wallet):
QMainWindow.__init__(self)
self._api = WalletAPI(self)
self.logger = logger
self.config = app_state.config
self._wallet = wallet
self._account: Optional[AbstractAccount] = wallet.get_default_account()
self._account_id: Optional[int] = (self._account.get_id() if self._account is not None
else None)
self.network = app_state.daemon.network
self.contacts = wallet.contacts
self.app = app_state.app
self.cleaned_up = False
self.is_max = False
self.payment_request = None
self.checking_accounts = False
self.qr_window = None
self.not_enough_funds = False
self.require_fee_update = False
self.tx_notifications: Tuple[Transaction, AbstractAccount] = []
self.tx_notify_timer = None
self.tx_dialogs = []
self.tl_windows = []
self.create_status_bar()
self.need_update = threading.Event()
self.fee_unit = self.config.get('fee_unit', 0)
self.completions = QStringListModel()
self._accounts_view = self._create_accounts_view()
self._tab_widget = tabs = self._accounts_view.get_tab_widget()
self._create_tabs()
tabs.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.setCentralWidget(self._accounts_view)
# Some tabs may want to be refreshed to show current state when selected.
def on_tab_changed(to_tab_index):
current_tab = self._tab_widget.currentWidget()
if current_tab is self.coinsplitting_tab:
self.coinsplitting_tab.update_layout()
self._tab_widget.currentChanged.connect(on_tab_changed)
if self.config.get("is_maximized"):
self.showMaximized()
self.init_menubar()
self.init_toolbar()
wrtabs = weakref.proxy(tabs)
QShortcut(QKeySequence("Ctrl+W"), self, self.close)
QShortcut(QKeySequence("Ctrl+Q"), self, self.close)
QShortcut(QKeySequence("Ctrl+R"), self, self.update_wallet)
QShortcut(QKeySequence("Ctrl+PgUp"), self,
lambda: wrtabs.setCurrentIndex((wrtabs.currentIndex() - 1)%wrtabs.count()))
QShortcut(QKeySequence("Ctrl+PgDown"), self,
lambda: wrtabs.setCurrentIndex((wrtabs.currentIndex() + 1)%wrtabs.count()))
for i in range(wrtabs.count()):
QShortcut(QKeySequence("Alt+" + str(i + 1)), self,
lambda i=i: wrtabs.setCurrentIndex(i))
self.network_status_signal.connect(self._update_network_status)
self.payment_request_ok_signal.connect(self.payment_request_ok)
self.payment_request_error_signal.connect(self.payment_request_error)
self.notify_transactions_signal.connect(self.notify_transactions)
self.history_view.setFocus(True)
# Link wallet synchronisation to throttled UI updates.
self._wallet_sync_event = app_state.async_.event()
self._monitor_wallet_network_status_tasks = []
for account in self._wallet.get_accounts():
task = app_state.async_.spawn(self._monitor_wallet_network_status, account)
self._monitor_wallet_network_status_tasks.append(task)
self.network_status_task = app_state.async_.spawn(self._maintain_network_status)
# network callbacks
if self.network:
self.network_signal.connect(self.on_network_qt)
interests = ['updated', 'new_transaction', 'status', 'banner', 'verified',
'on_header_backfill']
# To avoid leaking references to "self" that prevent the
# window from being GC-ed when closed, callbacks should be
# methods of this class only, and specifically not be
# partials, lambdas or methods of subobjects. Hence...
self.network.register_callback(self.on_network, interests)
# set initial message
if self.network.main_server:
self.console.showMessage(self.network.main_server.state.banner)
self.network.register_callback(self.on_quotes, ['on_quotes'])
self.network.register_callback(self._on_history, ['on_history'])
self.new_fx_quotes_signal.connect(self.on_fx_quotes)
self.new_fx_history_signal.connect(self.on_fx_history)
self._wallet.register_callback(self._on_account_created, ['on_account_created'])
self._wallet.register_callback(self._on_keys_updated, ['on_keys_updated'])
self._wallet.register_callback(self._on_keys_created, ['on_keys_created'])
self._wallet.register_callback(self._on_transaction_state_change,
['transaction_state_change'])
self._wallet.register_callback(self._on_transaction_added, ['transaction_added'])
self._wallet.register_callback(self._on_transaction_deleted, ['transaction_deleted'])
self.load_wallet()
self.app.timer.timeout.connect(self.timer_actions)
def _create_tabs(self) -> None:
tabs = self._tab_widget
self.send_tab = self.create_send_tab()
self.receive_tab = self.create_receive_tab()
self.keys_tab = self.create_keys_tab()
self.utxo_tab = self.create_utxo_tab()
self.console_tab = self.create_console_tab()
self.contacts_tab = self.create_contacts_tab()
self.coinsplitting_tab = self.create_coinsplitting_tab()
tabs.addTab(self.create_history_tab(), read_QIcon("tab_history.png"), _('History'))
tabs.addTab(self.create_transaction_tab(), read_QIcon("icons8-transaction-list-96.png"),
_('Transactions'))
tabs.addTab(self.send_tab, read_QIcon("tab_send.png"), _('Send'))
tabs.addTab(self.receive_tab, read_QIcon("tab_receive.png"), _('Receive'))
self._add_optional_tab(tabs, self.keys_tab, read_QIcon("tab_addresses.png"),
_("&Keys"), "keys")
self._add_optional_tab(tabs, self.utxo_tab, read_QIcon("tab_coins.png"),
_("Co&ins"), "utxo")
self._add_optional_tab(tabs, self.contacts_tab, read_QIcon("tab_contacts.png"),
_("Con&tacts"), "contacts")
self._add_optional_tab(tabs, self.console_tab, read_QIcon("tab_console.png"),
_("Con&sole"), "console")
self._add_optional_tab(tabs, self.coinsplitting_tab, read_QIcon("tab_coins.png"),
_("Coin Splitting"), "coinsplitter", True)
def _add_optional_tab(self, tabs, tab, icon, description, name, default=False):
tab.tab_icon = icon
tab.tab_description = description
tab.tab_pos = len(tabs)
tab.tab_name = name
if self.config.get('show_{}_tab'.format(name), default):
tabs.addTab(tab, icon, description.replace("&", ""))
def _on_transaction_state_change(self, event_name: str, wallet_path: str, account_id: int,
tx_hash: bytes, old_state: TxFlags, new_state: TxFlags) -> None:
self.transaction_state_signal.emit(wallet_path, account_id, tx_hash, old_state, new_state)
def _on_transaction_added(self, event_name: str, wallet_path: str, account_id: int,
tx_hash: bytes) -> None:
self.transaction_added_signal.emit(wallet_path, account_id, tx_hash)
def _on_transaction_deleted(self, event_name: str, wallet_path: str, account_id: int,
tx_hash: bytes) -> None:
self.transaction_deleted_signal.emit(wallet_path, account_id, tx_hash)
def _on_account_created(self, event_name: str, new_account_id: int) -> None:
if self._account_id is None:
self._account_id = new_account_id
self._account = self._wallet.get_account(new_account_id)
# NOTE(rt12) single-account At this time we disallow more than one account.
self._add_account_action.setDisabled(True)
self._add_account_action.setToolTip("Accounts are limited to one at this time.")
self._bind_account(self._account)
task = app_state.async_.spawn(self._monitor_wallet_network_status, self._account)
self._monitor_wallet_network_status_tasks.append(task)
self.on_account_changed(new_account_id)
self.account_created_signal.emit(new_account_id)
def _on_keys_created(self, event_name: str, wallet_path: str, account_id: int,
keys: Iterable[KeyInstanceRow]) -> None:
self.keys_created_signal.emit(wallet_path, account_id, keys)
def _on_keys_updated(self, event_name: str, wallet_name: str, account_id: int,
keys: Iterable[KeyInstanceRow]) -> None:
# logger.debug("_on_keys_updated %r", keys)
self.keys_updated_signal.emit(wallet_name, account_id, keys)
def _on_history(self, b):
self.new_fx_history_signal.emit()
def on_fx_history(self):
self.history_view.update_tx_headers()
self.history_view.update_tx_list()
# inform things like address_dialog that there's a new history
self.history_updated_signal.emit()
def on_quotes(self, b):
self.new_fx_quotes_signal.emit()
def on_fx_quotes(self):
self.update_status()
# Refresh edits with the new rate
edit = self.fiat_send_e if self.fiat_send_e.is_last_edited else self.amount_e
edit.textEdited.emit(edit.text())
if self._account_id is not None:
edit = (self.fiat_receive_e
if self.fiat_receive_e.is_last_edited else self.receive_amount_e)
edit.textEdited.emit(edit.text())
# History tab needs updating if it used spot
if app_state.fx.history_used_spot:
self.history_view.update_tx_list()
self.history_updated_signal.emit()
def on_account_changed(self, new_account_id: int) -> None:
self.history_view.update_tx_list()
self.utxo_list.update()
self.need_update.set()
# Once GUI has been initialized check if we want to announce something since the
# callback has been called before the GUI was initialized
self.notify_transactions()
# update menus
self.update_buttons_on_seed()
self.update_receive_tab()
self.clear_receive_tab()
self.history_updated_signal.emit()
self.console.updateNamespace({
'account': (self._wallet.get_account(new_account_id) if new_account_id is not None
else None),
})
self.account_change_signal.emit(new_account_id)
def toggle_tab(self, tab):
show = self._tab_widget.indexOf(tab) == -1
self.config.set_key('show_{}_tab'.format(tab.tab_name), show)
item_text = (_("Hide") if show else _("Show")) + " " + tab.tab_description
tab.menu_action.setText(item_text)
if show:
# Find out where to place the tab
index = len(self._tab_widget)
for i in range(len(self._tab_widget)):
try:
if tab.tab_pos < self._tab_widget.widget(i).tab_pos:
index = i
break
except AttributeError:
pass
self._tab_widget.insertTab(index, tab, tab.tab_icon,
tab.tab_description.replace("&", ""))
else:
i = self._tab_widget.indexOf(tab)
self._tab_widget.removeTab(i)
def push_top_level_window(self, window):
'''Used for e.g. tx dialog box to ensure new dialogs are appropriately
parented. This used to be done by explicitly providing the parent
window, but that isn't something hardware wallet prompts know.'''
self.tl_windows.append(window)
def pop_top_level_window(self, window):
self.tl_windows.remove(window)
def top_level_window(self):
'''Do the right thing in the presence of tx dialog windows'''
override = self.tl_windows[-1] if self.tl_windows else None
return self.top_level_window_recurse(override)
def is_hidden(self):
return self.isMinimized() or self.isHidden()
def show_or_hide(self):
if self.is_hidden():
self.bring_to_top()
else:
self.hide()
def bring_to_top(self):
self.show()
self.raise_()
def on_exception(self, exception):
if not isinstance(exception, UserCancelled):
self.logger.exception("")
self.show_error(str(exception))
def on_error(self, exc_info):
self.on_exception(exc_info[1])
def on_network(self, event, *args):
if event == 'updated':
self.need_update.set()
elif event == 'new_transaction':
tx, account = args
if self._wallet.get_account(account.get_id()) is not None:
self.tx_notifications.append((tx, account))
self.notify_transactions_signal.emit()
self.need_update.set()
elif event == 'on_header_backfill':
self.history_view.update()
elif event in ['status', 'banner', 'verified']:
# Handle in GUI thread
self.network_signal.emit(event, args)
else:
self.logger.debug("unexpected network message event='%s' args='%s'", event, args)
def on_network_qt(self, event, args=None):
# Handle a network message in the GUI thread
if event == 'status':
self.update_status()
elif event == 'banner':
self.console.showMessage(self.network.main_server.state.banner)
elif event == 'verified':
self.history_view.update_tx_item(*args[1:])
else:
self.logger.debug("unexpected network_qt signal event='%s' args='%s'", event, args)
def load_wallet(self) -> None:
wallet = self._wallet
self.logger = logs.get_logger(f"mainwindow[{wallet.name()}]")
self.init_geometry()
self.update_recently_visited(wallet.get_storage_path())
self.update_console()
self._tab_widget.show()
if self.config.get('hide_gui') and self.app.tray.isVisible():
self.hide()
else:
self.show()
self._update_window_title()
if self._account_id is not None:
self.on_account_changed(self._account_id)
self._bind_account(self._account)
def _bind_account(self, account: AbstractAccount) -> None:
self._wallet.create_gui_handler(self, account)
def init_geometry(self):
winpos = self._wallet.get_storage().get("winpos-qt")
if winpos is None:
return
try:
screen = self.app.desktop().screenGeometry()
assert screen.contains(QRect(*winpos))
self.setGeometry(*winpos)
except Exception:
self.logger.exception("using default geometry")
self.setGeometry(100, 100, 840, 400)
def _update_window_title(self):
title = f'ElectrumSV {PACKAGE_VERSION} ({Net.NAME}) - {self._wallet.name()}'
self.setWindowTitle(title)
# TODO: ACCOUNTS: This requires more nuance, in terms of showing which are watching only
# when we get to the multi-account stage.
for account in self._wallet.get_accounts():
if self.warn_if_watching_only(account):
break
def warn_if_watching_only(self, account: AbstractAccount) -> bool:
if account.is_watching_only():
msg = ' '.join([
_("This account is watching-only."),
_("This means you will not be able to spend Bitcoin SV with it."),
_("Make sure you own the seed phrase or the private keys, "
"before you request Bitcoin SV to be sent to this account.")
])
self.show_warning(msg, title=_('Information'))
return True
return False
def _backup_wallet(self):
path = self._wallet.get_storage_path()
wallet_folder = os.path.dirname(path)
filename, __ = QFileDialog.getSaveFileName(
self, _('Enter a filename for the copy of your wallet'), wallet_folder)
if not filename:
return
new_path = os.path.join(wallet_folder, filename)
new_path = WalletStorage.canonical_path(new_path)
if new_path.casefold() != path.casefold():
try:
# Copy file contents
shutil.copyfile(path, new_path)
# Copy file attributes if possible
# (not supported on targets like Flatpak documents)
try:
shutil.copystat(path, new_path)
except (IOError, os.error):
pass
self.show_message(_("A copy of your wallet file was created in")
+" '%s'" % str(new_path), title=_("Wallet backup created"))
except (IOError, os.error) as reason:
self.show_critical(_("ElectrumSV was unable to copy your wallet file "
"to the specified location.") + "\n" + str(reason),
title=_("Unable to create backup"))
def update_recently_visited(self, filename):
recent = self.config.get('recently_open', [])
if filename in recent:
recent.remove(filename)
filename = os.path.normpath(filename)
if filename in recent:
recent.remove(filename)
recent.insert(0, filename)
recent = [path for path in recent if os.path.exists(path)][:10]
self.config.set_key('recently_open', recent)
self.recently_visited_menu.clear()
wallet_names = [get_wallet_name_from_path(path) for path in recent]
counts = Counter(wallet_names)
pairs = ((wallet_name if counts[wallet_name] == 1 else path, path)
for wallet_name, path in zip(wallet_names, recent))
for menu_text, path in pairs:
self.recently_visited_menu.addAction(menu_text, partial(self.app.new_window, path))
self.recently_visited_menu.setEnabled(bool(pairs))
def _open_wallet(self) -> None:
try:
wallet_folder = self.config.get_preferred_wallet_dirpath()
except FileNotFoundError as e:
self.show_error(str(e))
return
if not os.path.exists(wallet_folder):
wallet_folder = None
filename, __ = QFileDialog.getOpenFileName(self, "Select your wallet file", wallet_folder)
if not filename:
return
self.app.new_window(filename)
def _new_wallet(self) -> None:
try:
wallet_folder = self.config.get_preferred_wallet_dirpath()
except FileNotFoundError as e:
self.show_error(str(e))
return
create_filepath = create_new_wallet(self, wallet_folder)
if create_filepath is not None:
self.app.start_new_window(create_filepath + DATABASE_EXT, None)
def init_menubar(self) -> None:
menubar = QMenuBar()
file_menu = menubar.addMenu(_("&File"))
self.recently_visited_menu = file_menu.addMenu(_("&Recently open"))
file_menu.addAction(_("&Open"), self._open_wallet).setShortcut(QKeySequence.Open)
file_menu.addAction(_("&New"), self._new_wallet).setShortcut(QKeySequence.New)
file_menu.addAction(_("&Save Copy"), self._backup_wallet).setShortcut(QKeySequence.SaveAs)
file_menu.addSeparator()
file_menu.addAction(_("&Quit"), self.close)
wallet_menu = menubar.addMenu(_("&Wallet"))
wallet_menu.addAction(_("&Information"), self._show_wallet_information)
wallet_menu.addSeparator()
self.password_menu = wallet_menu.addAction(_("&Password"), self.change_password_dialog)
wallet_menu.addSeparator()
contacts_menu = wallet_menu.addMenu(_("Contacts"))
contacts_menu.addAction(_("&New"), partial(edit_contact_dialog, self._api))
invoices_menu = wallet_menu.addMenu(_("Invoices"))
invoices_menu.addAction(_("Import"), self._import_invoices)
hist_menu = wallet_menu.addMenu(_("&History"))
hist_menu.addAction("Export", self.export_history_dialog)
wallet_menu.addSeparator()
wallet_menu.addAction(_("Find"), self.toggle_search).setShortcut(QKeySequence("Ctrl+F"))
def add_toggle_action(view_menu, tab) -> None:
is_shown = self._tab_widget.indexOf(tab) > -1
item_name = (_("Hide") if is_shown else _("Show")) + " " + tab.tab_description
tab.menu_action = view_menu.addAction(item_name, lambda: self.toggle_tab(tab))
view_menu = menubar.addMenu(_("&View"))
add_toggle_action(view_menu, self.keys_tab)
add_toggle_action(view_menu, self.utxo_tab)
add_toggle_action(view_menu, self.contacts_tab)
add_toggle_action(view_menu, self.coinsplitting_tab)
add_toggle_action(view_menu, self.console_tab)
tools_menu = menubar.addMenu(_("&Tools"))
tools_menu.addAction(_("Preferences"), self.preferences_dialog)
tools_menu.addAction(_("&Network"), lambda: self.app.show_network_dialog(self))
tools_menu.addSeparator()
tools_menu.addAction(_("&Sign/verify message"), self.sign_verify_message)
tools_menu.addAction(_("&Encrypt/decrypt message"), self.encrypt_message)
tools_menu.addSeparator()
paytomany_menu = tools_menu.addAction(_("&Pay to many"), self.paytomany)
raw_transaction_menu = tools_menu.addMenu(_("&Load transaction"))
raw_transaction_menu.addAction(_("&From file"), self.do_process_from_file)
raw_transaction_menu.addAction(_("&From text"), self.do_process_from_text)
raw_transaction_menu.addAction(_("&From the blockchain"), self.do_process_from_txid)
raw_transaction_menu.addAction(_("&From QR code"), self.do_process_from_qrcode)
self.raw_transaction_menu = raw_transaction_menu
help_menu = menubar.addMenu(_("&Help"))
help_menu.addAction(_("&About"), self.show_about)
help_menu.addAction(_("&Check for updates"), self.show_update_check)
help_menu.addAction(_("&Official website"), lambda: webbrowser.open("http://electrumsv.io"))
help_menu.addSeparator()
help_menu.addAction(_("Documentation"),
lambda: webbrowser.open("http://electrumsv.readthedocs.io/")
).setShortcut(QKeySequence.HelpContents)
help_menu.addAction(_("&Report Bug"), self.show_report_bug)
help_menu.addSeparator()
help_menu.addAction(_("&Donate to server"), self.donate_to_server)
self.setMenuBar(menubar)
def _import_invoices(self) -> None:
if self.invoice_list is not None:
self.invoice_list.import_invoices()
def init_toolbar(self):
self.toolbar = toolbar = QToolBar(self)
icon_size = self.app.dpi / 5.8
toolbar.setMovable(False)
toolbar.setIconSize(QSize(icon_size, icon_size))
toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
self._add_account_action = QAction(read_QIcon("icons8-add-folder-80.png"),
_("Add Account"), self)
self._add_account_action.triggered.connect(self.add_account)
toolbar.addAction(self._add_account_action)
# NOTE(rt12) single-account At this time we disallow more than one account.
self._add_account_action.setDisabled(len(self._wallet.get_accounts()) > 0)
self._add_account_action.setToolTip("Accounts are limited to one at this time.")
# make_payment_action = QAction(read_QIcon("icons8-initiate-money-transfer-80.png"),
# _("Make Payment"), self)
# make_payment_action.triggered.connect(self.new_payment)
# toolbar.addAction(make_payment_action)
spacer = QWidget(self)
spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
spacer.setVisible(True)
self.spacer_action = toolbar.addWidget(spacer)
log_action = QAction(read_QIcon("icons8-moleskine-80.png"), _("Log Viewer"), self)
log_action.triggered.connect(self.app.show_log_viewer)
toolbar.addAction(log_action)
network_action = QAction(read_QIcon("network.png"), _("Network"), self)
network_action.triggered.connect(lambda: self.app.show_network_dialog(self))
toolbar.addAction(network_action)
preferences_action = QAction(read_QIcon("preferences.png"), _("Preferences"), self)
preferences_action.triggered.connect(self.preferences_dialog)
toolbar.addAction(preferences_action)
self._update_check_state = "default"
update_action = QAction(
read_QIcon("icons8-available-updates-80-blue"), _("Update Check"), self)
def _update_show_menu(checked: bool = False):
self._update_menu.exec(QCursor.pos())
update_action.triggered.connect(_update_show_menu)
self._update_action = update_action
toolbar.addAction(update_action)
self._update_check_toolbar_update()
toolbar.insertSeparator(update_action)
self.addToolBar(toolbar)
self.setUnifiedTitleAndToolBarOnMac(True)
def add_toolbar_action(self, action: QAction) -> None:
self.toolbar.insertAction(self.spacer_action, action)
def _update_check_toolbar_update(self):
update_check_state = "default"
check_result = self.config.get('last_update_check')
stable_version = "?"
if check_result is not None:
# The latest stable release date, the date of the build we are using.
stable_result = check_result["stable"]
stable_signers = get_identified_release_signers(stable_result)
if stable_signers:
release_date, current_date = get_update_check_dates(stable_result["date"])
if release_date > current_date:
if time.time() - release_date.timestamp() < 24 * 60 * 60:
update_check_state = "update-present-immediate"
else:
update_check_state = "update-present-prolonged"
stable_version = stable_result["version"]
def _on_check_for_updates(checked: bool=False):
self.show_update_check()
def _on_view_pending_update(checked: bool=False):
QDesktopServices.openUrl(QUrl("https://electrumsv.io/download.html"))
menu = QMenu()
self._update_menu = menu
self._update_check_action = menu.addAction(
_("Check for Updates"), _on_check_for_updates)
if update_check_state == "default":
icon_path = "icons8-available-updates-80-blue"
icon_text = _("Updates")
tooltip = _("Check for Updates")
menu.setDefaultAction(self._update_check_action)
elif update_check_state == "update-present-immediate":
icon_path = "icons8-available-updates-80-yellow"
icon_text = f"{stable_version}"
tooltip = _("A newer version of ElectrumSV is available, and "+
"was released on {0:%c}").format(release_date)
self._update_view_pending_action = menu.addAction(
_("View Pending Update"), _on_view_pending_update)
menu.setDefaultAction(self._update_view_pending_action)
elif update_check_state == "update-present-prolonged":
icon_path = "icons8-available-updates-80-red"
icon_text = f"{stable_version}"
tooltip = _("A newer version of ElectrumSV is available, and "+
"was released on {0:%c}").format(release_date)
self._update_view_pending_action = menu.addAction(
_("View Pending Update"), _on_view_pending_update)
menu.setDefaultAction(self._update_view_pending_action)
# Apply the update state.
self._update_action.setMenu(menu)
self._update_action.setIcon(read_QIcon(icon_path))
self._update_action.setText(icon_text)
self._update_action.setToolTip(tooltip)
self._update_check_state = update_check_state
def on_update_check(self, success, result):
if success:
stable_result = result["stable"]
stable_signers = get_identified_release_signers(stable_result)
if stable_signers:
# The latest stable release date, the date of the build we are using.
stable_date_string = stable_result["date"]
release_date, current_date = get_update_check_dates(stable_date_string)
if release_date > current_date:
self.app.tray.showMessage(
"ElectrumSV",
_("A new version of ElectrumSV, version {}, is available for download")
.format(stable_result["version"]),
read_QIcon("electrum_dark_icon"), 20000)
self._update_check_toolbar_update()
def add_account(self) -> None:
from . import account_wizard
from importlib import reload
reload(account_wizard)
wizard_window = account_wizard.AccountWizard(self)
result = wizard_window.run()
if result != QDialog.Accepted:
# Clean up?
return
def new_payment(self) -> None:
from . import payment
from importlib import reload
reload(payment)
self.w = payment.PaymentWindow(self._api, parent=self)
self.w.show()
def donate_to_server(self):
server = self.network.main_server
addr = server.state.donation_address
if is_address_valid(addr):
addr = address_from_string(addr)
self.pay_to_URI(web.create_URI(addr, 0, _('Donation for {}').format(server.host)))
else:
self.show_error(_('The server {} has not provided a valid donation address')
.format(server))
def show_about(self):
QMessageBox.about(self, "ElectrumSV",
_("Version")+" %s" % PACKAGE_VERSION + "\n\n" +
_("ElectrumSV's focus is speed, with low resource usage and simplifying "
"Bitcoin SV. Startup times are instant because it operates in "
"conjunction with high-performance servers that handle the most complicated "
"parts of the Bitcoin SV system." + "\n\n" +
_("Uses icons from the Icons8 icon pack (icons8.com).")))
def show_update_check(self):
from . import update_check
update_check.UpdateCheckDialog()
def show_report_bug(self):
msg = ' '.join([
_("Please report any bugs as issues on github:<br/>"),
"<a href=\"https://github.com/ElectrumSV/ElectrumSV/issues"
"\">https://github.com/ElectrumSV/ElectrumSV/issues</a><br/><br/>",
_("Before reporting a bug, upgrade to the most recent version of ElectrumSV "
"(latest release or git HEAD), and include the version number in your report."),
_("Try to explain not only what the bug is, but how it occurs.")
])
self.show_message(msg, title="ElectrumSV - " + _("Reporting Bugs"))
last_notify_tx_time = 0.0
notify_tx_rate = 30.0
def notify_tx_cb(self):
n_ok = 0
if self.network and self.network.is_connected():
num_txns = len(self.tx_notifications)
if num_txns:
# Combine the transactions
total_amount = 0
for tx, account in self.tx_notifications:
if tx:
v = account.get_transaction_delta(tx.hash())
if v:
total_amount += v
n_ok += 1
if n_ok:
self.logger.debug("Notifying GUI %d tx", n_ok)
if n_ok > 1:
self.notify(_("{} new transactions received: Total amount received "
"in the new transactions {}")
.format(n_ok, self.format_amount_and_units(total_amount)))
else:
self.notify(_("New transaction received: {}").format(
self.format_amount_and_units(total_amount)))
self.tx_notifications = list()
self.last_notify_tx_time = time.time() if n_ok else self.last_notify_tx_time
if self.tx_notify_timer:
self.tx_notify_timer.stop()
self.tx_notify_timer = None
def notify_transactions(self):
if self.tx_notify_timer or not len(self.tx_notifications) or self.cleaned_up:
# common case: extant notify timer -- we already enqueued to notify. So bail
# and wait for timer to handle it.
return
elapsed = time.time() - self.last_notify_tx_time
if elapsed < self.notify_tx_rate:
# spam control. force tx notify popup to not appear more often than every 30
# seconds by enqueing the request for a timer to handle it sometime later
self.tx_notify_timer = QTimer(self)
self.tx_notify_timer.setSingleShot(True)
self.tx_notify_timer.timeout.connect(self.notify_tx_cb)
when = (self.notify_tx_rate - elapsed)
self.logger.debug("Notify spam control: will notify GUI of %d new tx's in %f seconds",
len(self.tx_notifications), when)
self.tx_notify_timer.start(when * 1e3) # time in ms
else:
# it's been a while since we got a tx notify -- so do it immediately (no timer
# necessary)
self.notify_tx_cb()
def notify(self, message):
self.app.tray.showMessage("ElectrumSV", message,
read_QIcon("electrum_dark_icon"), 20000)
# custom wrappers for getOpenFileName and getSaveFileName, that remember the path
# selected by the user
def getOpenFileName(self, title, filter = ""):
directory = self.config.get('io_dir', os.path.expanduser('~'))
fileName, __ = QFileDialog.getOpenFileName(self, title, directory, filter)
if fileName and directory != os.path.dirname(fileName):
self.config.set_key('io_dir', os.path.dirname(fileName), True)
return fileName
def getOpenFileNames(self, title, filter = ""):
directory = self.config.get('io_dir', os.path.expanduser('~'))
fileNames, __ = QFileDialog.getOpenFileNames(self, title, directory, filter)
if fileNames and directory != os.path.dirname(fileNames[0]):
self.config.set_key('io_dir', os.path.dirname(fileNames[0]), True)
return fileNames
def getSaveFileName(self, title, filename, filter = ""):
directory = self.config.get('io_dir', os.path.expanduser('~'))
path = os.path.join( directory, filename )
fileName, __ = QFileDialog.getSaveFileName(self, title, path, filter)
if fileName and directory != os.path.dirname(fileName):
self.config.set_key('io_dir', os.path.dirname(fileName), True)
return fileName
def timer_actions(self):
# Note this runs in the GUI thread
if self.need_update.is_set():
self.need_update.clear()
self.update_wallet()
# resolve aliases (used to be used for openalias)
self.payto_e.resolve()
# update fee
if self.require_fee_update:
self.do_update_fee()
self.require_fee_update = False
def format_amount(self, x, is_diff=False, whitespaces=False):
return format_satoshis(x, app_state.num_zeros, app_state.decimal_point,
is_diff=is_diff, whitespaces=whitespaces)
def format_amount_and_units(self, amount):
text = self.format_amount(amount) + ' ' + app_state.base_unit()
if app_state.fx and app_state.fx.is_enabled():
x = app_state.fx.format_amount_and_units(amount)
if text and x:
text += ' (%s)'%x
return text
def get_amount_and_units(self, amount: int) -> Tuple[str, str]:
bitcoin_text = self.format_amount(amount) + ' ' + app_state.base_unit()
if app_state.fx and app_state.fx.is_enabled():
fiat_text = app_state.fx.format_amount_and_units(amount)
else:
fiat_text = ''
return bitcoin_text, fiat_text
def format_fee_rate(self, fee_rate: int) -> str:
return format_fee_satoshis(fee_rate/1000, app_state.num_zeros) + ' sat/B'
def connect_fields(self, window, btc_e, fiat_e, fee_e):
def edit_changed(edit):
if edit.follows:
return
edit.setStyleSheet(ColorScheme.DEFAULT.as_stylesheet())
fiat_e.is_last_edited = (edit == fiat_e)
amount = edit.get_amount()
rate = app_state.fx.exchange_rate() if app_state.fx else None
if rate is None or amount is None:
if edit is fiat_e:
btc_e.setText("")
if fee_e:
fee_e.setText("")
else:
fiat_e.setText("")
else:
if edit is fiat_e:
btc_e.follows = True
btc_e.setAmount(int(amount / Decimal(rate) * COIN))
btc_e.setStyleSheet(ColorScheme.BLUE.as_stylesheet())
btc_e.follows = False
if fee_e:
window.update_fee()
else:
fiat_e.follows = True
fiat_e.setText(app_state.fx.ccy_amount_str(
amount * Decimal(rate) / COIN, False))
fiat_e.setStyleSheet(ColorScheme.BLUE.as_stylesheet())
fiat_e.follows = False
btc_e.follows = False
fiat_e.follows = False
fiat_e.textChanged.connect(partial(edit_changed, fiat_e))
btc_e.textChanged.connect(partial(edit_changed, btc_e))
fiat_e.is_last_edited = False
async def _monitor_wallet_network_status(self, account: AbstractAccount) -> None:
while True:
await account.progress_event.wait()
account.progress_event.clear()
self._wallet_sync_event.set()
async def _maintain_network_status(self) -> None:
while True:
await self._wallet_sync_event.wait()
self.network_status_signal.emit()
# Throttle updates
await asyncio.sleep(1.0)
def _update_network_status(self) -> None:
"Update the network status portion of the status bar."
text = _("Offline")
if self.network:
request_count = 0
response_count = 0
for account in self._wallet.get_accounts():
if account.request_count > account.response_count:
request_count += account.request_count
response_count += account.response_count
else:
account.request_count = 0
account.response_count = 0
if request_count > response_count:
text = _("Synchronizing...")
text += f' {response_count:,d}/{request_count:,d}'
else:
server_height = self.network.get_server_height()
if server_height == 0: