-
Notifications
You must be signed in to change notification settings - Fork 82
/
main_dlg.py
executable file
·1919 lines (1704 loc) · 91.5 KB
/
main_dlg.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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Bertrand256
# Created on: 2017-03
import subprocess
import simplejson
import base64
import binascii
import datetime
import json
import os
import platform
import re
import sys
import threading
import time
import ssl
from functools import partial
from typing import Optional, Tuple, Dict, Callable
import bitcoin
import logging
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtCore import QSize, pyqtSlot, QEventLoop, QMutex, QWaitCondition, QUrl, Qt
from PyQt5.QtGui import QFont, QIcon, QDesktopServices
from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QFileDialog, QMenu, QMainWindow, QPushButton, QStyle, QInputDialog, QApplication, \
QHBoxLayout
from PyQt5.QtWidgets import QMessageBox
import reg_masternode_dlg
from bip44_wallet import find_wallet_address, Bip44Wallet
from cmd_console_dlg import CmdConsoleDlg
from common import CancelException
from config_dlg import ConfigDlg
from find_coll_tx_dlg import ListCollateralTxsDlg
import about_dlg
import app_cache
import dash_utils
import hw_pass_dlg
import hw_pin_dlg
import wallet_dlg
import app_utils
from initialize_hw_dlg import HwInitializeDlg
from masternode_details import WdgMasternodeDetails
from proposals_dlg import ProposalsDlg
from app_config import AppConfig, MasternodeConfig, APP_NAME_SHORT
from app_defs import PROJECT_URL, HWType, get_note_url
from dash_utils import bip32_path_n_to_string
from dashd_intf import DashdInterface, DashdIndexException
from hw_common import HardwareWalletCancelException, HardwareWalletPinException, HwSessionInfo
import hw_intf
from hw_setup_dlg import HwSetupDlg
from psw_cache import SshPassCache
from sign_message_dlg import SignMessageDlg
from wnd_utils import WndUtils
from ui import ui_main_dlg
class MainWindow(QMainWindow, WndUtils, ui_main_dlg.Ui_MainWindow):
update_status_signal = QtCore.pyqtSignal(str, str) # signal for updating status text from inside thread
def __init__(self, app_dir):
QMainWindow.__init__(self)
WndUtils.__init__(self, None)
ui_main_dlg.Ui_MainWindow.__init__(self)
self.hw_client = None
self.finishing = False
self.config = AppConfig()
self.config.init(app_dir)
WndUtils.set_app_config(self, self.config)
self.dashd_intf = DashdInterface(window=None,
on_connection_initiated_callback=self.show_connection_initiated,
on_connection_failed_callback=self.show_connection_failed,
on_connection_successful_callback=self.show_connection_successful,
on_connection_disconnected_callback=self.show_connection_disconnected)
self.hw_session = HwSessionInfo(
self.get_hw_client,
self.connect_hardware_wallet,
self.disconnect_hardware_wallet,
self.config,
dashd_intf=self.dashd_intf)
self.remote_app_params = {}
self.dashd_info = {}
self.is_dashd_syncing = False
self.dashd_connection_ok = False
self.connecting_to_dashd = False
self.curMasternode = None
self.editing_enabled = False
self.recent_config_files = []
# load most recently used config files from the data cache
mru_cf = app_cache.get_value('MainWindow_ConfigFileMRUList', default_value=[], type=list)
if isinstance(mru_cf, list):
for file_name in mru_cf:
if os.path.exists(file_name):
self.recent_config_files.append(file_name)
self.cmd_console_dlg = None
self.setupUi()
ssl._create_default_https_context = ssl._create_unverified_context
def setupUi(self):
ui_main_dlg.Ui_MainWindow.setupUi(self, self)
SshPassCache.set_parent_window(self)
app_cache.restore_window_size(self)
self.inside_setup_ui = True
self.dashd_intf.window = self
self.closeEvent = self.closeEvent
self.show_hide_trezor_emulator()
self.lblStatus1 = QtWidgets.QLabel(self)
self.lblStatus1.setAutoFillBackground(False)
self.lblStatus1.setOpenExternalLinks(True)
self.lblStatus1.setOpenExternalLinks(True)
self.statusBar.addPermanentWidget(self.lblStatus1, 1)
self.lblStatus1.setText('')
self.lblStatus2 = QtWidgets.QLabel(self)
self.statusBar.addPermanentWidget(self.lblStatus2, 2)
self.lblStatus2.setText('')
self.lblStatus2.setOpenExternalLinks(True)
self.show_connection_disconnected()
self.setStatus2Text('<b>HW status:</b> idle', 'black')
# set stylesheet for editboxes, supporting different colors for read-only and edting mode
self.styleSheet = "QLineEdit{background-color: white} QLineEdit:read-only{background-color: lightgray}"
self.setStyleSheet(self.styleSheet)
self.setIcon(self.action_save_config_file, 'save.png')
self.setIcon(self.action_check_network_connection, "link-check.png")
self.setIcon(self.action_open_settings_window, "gear.png")
self.setIcon(self.action_open_proposals_window, "thumbs-up-down.png")
self.setIcon(self.action_test_hw_connection, "hw-test.png")
self.setIcon(self.action_disconnect_hw, "hw-disconnect.png")
self.setIcon(self.action_run_trezor_emulator, "hw-emulator.png")
self.setIcon(self.action_transfer_funds_for_any_address, "wallet.png")
self.setIcon(self.action_sign_message_for_cur_mn, "sign@32px.png")
self.setIcon(self.action_hw_configuration, "hw.png")
self.setIcon(self.action_hw_initialization_recovery, "recover.png")
# icons will not be visible in menu
self.action_save_config_file.setIconVisibleInMenu(False)
self.action_check_network_connection.setIconVisibleInMenu(False)
self.action_open_settings_window.setIconVisibleInMenu(False)
self.action_open_proposals_window.setIconVisibleInMenu(False)
self.action_test_hw_connection.setIconVisibleInMenu(False)
self.action_disconnect_hw.setIconVisibleInMenu(False)
self.action_run_trezor_emulator.setIconVisibleInMenu(False)
self.action_transfer_funds_for_any_address.setIconVisibleInMenu(False)
self.action_sign_message_for_cur_mn.setIconVisibleInMenu(False)
self.action_hw_configuration.setIconVisibleInMenu(False)
self.action_hw_initialization_recovery.setIconVisibleInMenu(False)
# register dialog-type actions:
self.addAction(self.action_gen_mn_priv_key_uncompressed)
self.addAction(self.action_gen_mn_priv_key_compressed)
# add masternodes' info to the combobox
self.curMasternode = None
self.wdg_masternode = WdgMasternodeDetails(self, self.app_config, self.dashd_intf)
l = self.frmMasternodeDetails.layout()
l.insertWidget(0, self.wdg_masternode)
self.wdg_masternode.name_modified.connect(self.on_mn_name_modified)
self.wdg_masternode.data_changed.connect(self.on_mn_data_changed)
self.deterministic_mns = {}
self.mns_user_refused_updating = {}
# after loading whole configuration, reset 'modified' variable
try:
self.config.read_from_file(hw_session=self.hw_session, create_config_file=True)
except Exception as e:
raise
self.display_window_title()
self.dashd_intf.initialize(self.config)
self.update_edit_controls_state()
self.setMessage("", None)
self.run_thread(self, self.check_for_updates_thread, (False,))
if self.config.app_config_file_name and os.path.exists(self.config.app_config_file_name):
self.add_item_to_config_files_mru_list(self.config.app_config_file_name)
self.update_config_files_mru_menu_items()
self.inside_setup_ui = False
self.configuration_to_ui()
logging.info('Finished setup of the main dialog.')
def closeEvent(self, event):
app_cache.save_window_size(self)
self.finishing = True
if self.dashd_intf:
self.dashd_intf.disconnect()
if self.config.is_modified():
if self.queryDlg('Configuration modified. Save?',
buttons=QMessageBox.Yes | QMessageBox.No,
default_button=QMessageBox.Yes, icon=QMessageBox.Information) == QMessageBox.Yes:
self.save_configuration()
self.config.close()
def showEvent(self, QShowEvent):
width = max(self.wdg_masternode.get_max_left_label_width(), self.lblMasternodeStatus.width())
self.lblMasternodeStatus.setFixedWidth(width)
self.wdg_masternode.set_left_label_width(width)
self.cboMasternodes.setFixedHeight(self.btnNewMn.height())
def get_hw_client(self):
return self.hw_client
def configuration_to_ui(self):
"""
Show the information read from configuration file on the user interface.
:return:
"""
# add masternodes data to the combobox
self.curMasternode = None
self.cboMasternodes.clear()
for mn in self.config.masternodes:
self.cboMasternodes.addItem(mn.name, mn)
if self.config.masternodes:
# get last masternode selected
idx = app_cache.get_value('MainWindow_CurMasternodeIndex', 0, int)
if idx >= len(self.config.masternodes):
idx = 0
self.curMasternode = self.config.masternodes[idx]
self.display_masternode_config(True)
else:
self.curMasternode = None
self.wdg_masternode.set_masternode(self.curMasternode)
self.action_open_log_file.setText = 'Open log file (%s)' % self.config.log_file
if self.app_config.deterministic_mns_enabled:
self.btnMigrateToDMN.show()
else:
self.btnMigrateToDMN.hide()
self.update_edit_controls_state()
def load_configuration_from_file(self, file_name: str, ask_save_changes = True) -> None:
"""
Load configuration from a file.
:param file_name: A name of the configuration file to be loaded into the application.
"""
if self.config.is_modified() and ask_save_changes:
ret = self.queryDlg('Current configuration has been modified. Save?',
buttons=QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel,
default_button=QMessageBox.Yes, icon=QMessageBox.Warning)
if ret == QMessageBox.Yes:
self.save_configuration()
elif ret == QMessageBox.Cancel:
self.update_config_files_mru_menu_items()
return
try:
self.disconnect_hardware_wallet()
dash_network_sav = self.config.dash_network
self.config.read_from_file(hw_session=self.hw_session, file_name=file_name)
self.editing_enabled = False
self.configuration_to_ui()
self.dashd_intf.reload_configuration()
self.config.modified = False
file_name = self.config.app_config_file_name
if file_name:
self.add_item_to_config_files_mru_list(file_name)
self.update_config_files_mru_menu_items()
if dash_network_sav != self.config.dash_network:
self.disconnect_hardware_wallet()
self.display_window_title()
except CancelException:
self.update_config_files_mru_menu_items()
def add_item_to_config_files_mru_list(self, file_name: str) -> None:
"""
Add a file name to the list of recently open config files. This list acts as a source for
the 'Open Recent' menu subitems. This method is called after each successful loading configuration
from the 'file_name' config file.
:param file_name: A name of the file to be added to the list.
"""
if file_name:
try:
if file_name in self.recent_config_files:
idx = self.recent_config_files.index(file_name)
del self.recent_config_files[idx]
self.recent_config_files.insert(0, file_name)
else:
self.recent_config_files.insert(0, file_name)
app_cache.set_value('MainWindow_ConfigFileMRUList', self.recent_config_files)
except Exception as e:
logging.warning(str(e))
def update_config_files_mru_menu_items(self):
app_utils.update_mru_menu_items(self.recent_config_files, self.action_open_recent_files,
self.on_config_file_mru_action_triggered,
self.config.app_config_file_name,
self.on_config_file_mru_clear_triggered)
def show_hide_trezor_emulator(self):
enabled = False
self.action_run_trezor_emulator.setVisible(enabled)
def on_config_file_mru_action_triggered(self, file_name: str) -> None:
""" Triggered by clicking one of the subitems of the 'Open Recent' menu item. Each subitem is
related to one of recently openend configuration files.
:param file_name: A config file name accociated with the menu action clicked.
"""
if file_name != self.config.app_config_file_name:
self.load_configuration_from_file(file_name)
def on_config_file_mru_clear_triggered(self):
"""Clear items in the recent config files menu."""
self.recent_config_files.clear()
app_cache.set_value('MainWindow_ConfigFileMRUList', self.recent_config_files)
self.update_config_files_mru_menu_items()
def display_window_title(self):
"""
Display main window title, which is composed of the application name, nick of the creator and
the name of the current configuration file. This method is executed after each successful loading
of the configuration file.
"""
app_version_part = ' (v' + self.config.app_version + ')' if self.config.app_version else ''
if self.config.dash_network == 'TESTNET':
testnet_part = ' [TESTNET]'
else:
testnet_part = ''
if self.config.app_config_file_name:
cfg_file_name = self.config.app_config_file_name
if cfg_file_name:
home_dir = os.path.expanduser('~')
if cfg_file_name.find(home_dir) == 0:
cfg_file_name = '~' + cfg_file_name[len(home_dir):]
else:
cfg_file_name = cfg_file_name
cfg_file_name_part = ' - ' + cfg_file_name if cfg_file_name else ''
else:
cfg_file_name_part = ' <UNNAMED>'
if self.config.config_file_encrypted:
encrypted_part = ' (Encrypted)'
else:
encrypted_part = ''
title = f'{APP_NAME_SHORT}{app_version_part}{testnet_part}{cfg_file_name_part}{encrypted_part}'
self.setWindowTitle(title)
@pyqtSlot(bool)
def on_action_load_config_file_triggered(self, checked):
if self.config.app_config_file_name:
dir = os.path.dirname(self.config.app_config_file_name)
else:
dir = self.config.data_dir
file_name = self.open_config_file_query(dir, self)
if file_name:
if os.path.exists(file_name):
self.load_configuration_from_file(file_name)
else:
WndUtils.errorMsg(f'File \'{file_name}\' does not exist.')
def save_configuration(self, file_name: str = None):
self.config.save_to_file(hw_session=self.hw_session, file_name=file_name)
file_name = self.config.app_config_file_name
if file_name:
self.add_item_to_config_files_mru_list(file_name)
self.update_config_files_mru_menu_items()
self.display_window_title()
self.editing_enabled = self.config.is_modified()
self.wdg_masternode.set_edit_mode(self.editing_enabled )
self.update_edit_controls_state()
@pyqtSlot(bool)
def on_action_save_config_file_triggered(self, checked):
self.save_configuration()
@pyqtSlot(bool)
def on_action_save_config_file_as_triggered(self, checked):
if self.config.app_config_file_name:
dir = os.path.dirname(self.config.app_config_file_name)
else:
dir = self.config.data_dir
file_name = self.save_config_file_query(dir, self)
if file_name:
self.save_configuration(file_name)
@pyqtSlot(bool)
def on_action_open_log_file_triggered(self, checked):
if os.path.exists(self.config.log_file):
ret = QDesktopServices.openUrl(QUrl("file:///%s" % self.config.log_file))
if not ret:
self.warnMsg('Could not open "%s" file in a default OS application.' % self.config.log_file)
@pyqtSlot(bool)
def on_action_check_for_updates_triggered(self, checked, force_check=True):
if self.config.check_for_updates:
self.run_thread(self, self.check_for_updates_thread, (force_check,))
@pyqtSlot(bool)
def on_action_command_console_triggered(self, checked):
if not self.cmd_console_dlg:
self.cmd_console_dlg = CmdConsoleDlg(self, self.app_config)
self.cmd_console_dlg.exec_()
def load_remote_params(self):
try:
import urllib.request
response = urllib.request.urlopen(
'https://raw.githubusercontent.com/Bertrand256/dash-masternode-tool/master/app-params.json')
contents = response.read()
app_remote_params = simplejson.loads(contents)
return app_remote_params
except Exception:
logging.exception('Error while loading app-params.json')
return {}
def check_for_updates_thread(self, ctrl, force_check):
"""
Thread function checking whether there is a new version of the application on Github page.
:param ctrl: thread control structure (not used here)
:param cur_date_str: Current date string - it will be saved in the cache file as the date of the
last-version-check date.
:param force_check: True if version-check has been invoked by the user, not the app itself.
:return: None
"""
try:
self.remote_app_params = self.load_remote_params()
if self.remote_app_params:
remote_version_str = self.remote_app_params.get("appCurrentVersion")
if remote_version_str:
remote_ver = app_utils.version_str_to_number(remote_version_str)
local_ver = app_utils.version_str_to_number(self.config.app_version)
if remote_ver > local_ver:
if sys.platform == 'win32':
item_name = 'win'
no_bits = platform.architecture()[0].replace('bit', '')
if no_bits == '32':
item_name += '32'
else:
item_name += '64'
elif sys.platform == 'darwin':
item_name = 'mac'
else:
item_name = 'linux'
exe_url = ''
exe_down = self.remote_app_params.get('exeDownloads')
if exe_down:
exe_url = exe_down.get(item_name)
if exe_url:
msg = "New version (" + remote_version_str + ') available: <a href="' + exe_url + '">download</a>.'
else:
msg = "New version (" + remote_version_str + ') available. Go to the project website: <a href="' + \
PROJECT_URL + '">open</a>.'
self.setMessage(msg, 'green')
else:
if force_check:
self.setMessage("You have the latest version of %s." % APP_NAME_SHORT, 'green')
elif force_check:
self.setMessage("Could not read the remote version number.", 'orange')
except Exception:
logging.exception('Exception occurred')
def display_masternode_config(self, set_mn_list_index):
if self.curMasternode and set_mn_list_index:
self.cboMasternodes.setCurrentIndex(self.config.masternodes.index(self.curMasternode))
self.lblMnStatus.setText('')
@pyqtSlot(bool)
def on_action_open_settings_window_triggered(self):
dash_network_sav = self.config.dash_network
hw_type_sav = self.config.hw_type
dlg = ConfigDlg(self, self.config)
res = dlg.exec_()
if res and dlg.get_is_modified():
self.config.configure_cache()
self.dashd_intf.reload_configuration()
if dash_network_sav != self.config.dash_network or hw_type_sav != self.config.hw_type:
self.disconnect_hardware_wallet()
self.display_window_title()
self.update_edit_controls_state()
del dlg
@pyqtSlot(bool)
def on_action_about_app_triggered(self):
ui = about_dlg.AboutDlg(self, self.config.app_version)
ui.exec_()
def show_connection_initiated(self):
"""Shows status information related to a initiated process of connection to a dash RPC. """
self.setStatus1Text('<b>RPC network status:</b> trying %s...' % self.dashd_intf.get_active_conn_description(), 'black')
def show_connection_failed(self):
"""Shows status information related to a failed connection attempt. There can be more attempts to connect
to another nodes if there are such in configuration."""
self.setStatus1Text('<b>RPC network status:</b> failed connection to %s' % self.dashd_intf.get_active_conn_description(), 'red')
def show_connection_successful(self):
"""Shows status information after successful connetion to a Dash RPC node."""
self.setStatus1Text('<b>RPC network status:</b> OK (%s)' % self.dashd_intf.get_active_conn_description(), 'green')
def show_connection_disconnected(self):
"""Shows status message related to disconnection from Dash RPC node."""
self.setStatus1Text('<b>RPC network status:</b> not connected', 'black')
def checkDashdConnection(self, wait_for_check_finish=False, call_on_check_finished=None):
"""
Connects do dash daemon if not connected before and returnes if it was successful.
:param wait_for_check_finish: True if function is supposed to wait until connection check is finished (process
is executed in background)
:param call_on_check_finished: ref to function to be called after connection test (successful or unsuccessful)
is finished
"""
# if wait_for_check_finish is True, we have to process QT events while waiting for thread to terminate to
# avoid deadlocking of functions: connect_thread and connect_finished
if wait_for_check_finish:
event_loop = QEventLoop(self)
else:
event_loop = None
def wait_for_synch_finished_thread(ctrl):
"""
Thread waiting for dash daemon to finish synchronizing.
"""
mtx = QMutex()
cond = QWaitCondition()
try:
logging.info('wait_for_synch_finished_thread')
mtx.lock()
while not ctrl.finish:
synced = self.dashd_intf.issynchronized()
if synced:
self.is_dashd_syncing = False
self.show_connection_successful()
break
mnsync = self.dashd_intf.mnsync()
self.setMessage('Dashd is synchronizing: AssetID: %s, AssetName: %s' %
(str(mnsync.get('AssetID', '')),
str(mnsync.get('AssetName', ''))
), style='{background-color:rgb(255,128,0);color:white;padding:3px 5px 3px 5px; border-radius:3px}')
cond.wait(mtx, 5000)
self.setMessage('')
except Exception as e:
self.is_dashd_syncing = False
self.dashd_connection_ok = False
self.setMessage(str(e),
style='{background-color:red;color:white;padding:3px 5px 3px 5px; border-radius:3px}')
finally:
mtx.unlock()
self.wait_for_dashd_synced_thread = None
def connect_thread(ctrl):
"""
Test connection to dash network inside a thread to avoid blocking GUI.
:param ctrl: control structure to communicate with WorkerThread object (not used here)
"""
try:
synced = self.dashd_intf.issynchronized()
self.dashd_info = self.dashd_intf.getinfo(verify_node=True)
self.dashd_connection_ok = True
if not synced:
logging.info("dashd not synced")
if not self.is_dashd_syncing and not (hasattr(self, 'wait_for_dashd_synced_thread') and
self.wait_for_dashd_synced_thread is not None):
self.is_dashd_syncing = True
self.wait_for_dashd_synced_thread = self.run_thread(self, wait_for_synch_finished_thread, (),
on_thread_finish=connect_finished)
else:
self.is_dashd_syncing = False
self.setMessage('')
except Exception as e:
err = str(e)
if not err:
err = 'Connect error: %s' % type(e).__name__
self.is_dashd_syncing = False
self.dashd_connection_ok = False
self.show_connection_failed()
self.setMessage(err,
style='{background-color:red;color:white;padding:3px 5px 3px 5px; border-radius:3px}')
def connect_finished():
"""
Called after thread terminates.
"""
del self.check_conn_thread
self.check_conn_thread = None
self.connecting_to_dashd = False
if call_on_check_finished:
call_on_check_finished()
if event_loop:
event_loop.exit()
if self.config.is_config_complete():
if not hasattr(self, 'check_conn_thread') or self.check_conn_thread is None:
if hasattr(self, 'wait_for_dashd_synced_thread') and self.wait_for_dashd_synced_thread is not None:
if call_on_check_finished is not None:
# if a thread waiting for dashd to finish synchronizing is running, call the callback function
call_on_check_finished()
else:
self.connecting_to_dashd = True
self.check_conn_thread = self.run_thread(self, connect_thread, (),
on_thread_finish=connect_finished)
if wait_for_check_finish:
event_loop.exec()
else:
# configuration is not complete
logging.warning("config not complete")
self.is_dashd_syncing = False
self.dashd_connection_ok = False
@pyqtSlot(bool)
def on_action_check_network_connection_triggered(self):
self.connect_dash_network()
def connect_dash_network(self):
def connection_test_finished():
self.action_check_network_connection.setEnabled(True)
self.btnBroadcastMn.setEnabled(True)
self.btnRefreshMnStatus.setEnabled(True)
self.action_transfer_funds_for_any_address.setEnabled(True)
if self.dashd_connection_ok:
self.show_connection_successful()
if self.is_dashd_syncing:
self.infoMsg('Connection successful, but Dash daemon is synchronizing.')
else:
self.infoMsg('Connection successful.')
else:
if self.dashd_intf.last_error_message:
self.errorMsg('Connection error: ' + self.dashd_intf.last_error_message)
else:
self.errorMsg('Connection error')
if self.config.is_config_complete():
self.action_check_network_connection.setEnabled(False)
self.btnBroadcastMn.setEnabled(False)
self.btnRefreshMnStatus.setEnabled(False)
# disable all actions that utilize dash network
self.action_transfer_funds_for_any_address.setEnabled(False)
self.checkDashdConnection(call_on_check_finished=connection_test_finished)
else:
# configuration not complete: show config window
self.errorMsg("There are no (enabled) connections to an RPC node in your configuration.")
def setStatus1Text(self, text, color):
def set_status(text, color):
self.lblStatus1.setText(text)
if not color:
color = 'black'
self.lblStatus1.setStyleSheet('QLabel{color: ' + color + ';margin-right:20px;margin-left:8px}')
if threading.current_thread() != threading.main_thread():
self.call_in_main_thread(set_status, text, color)
else:
set_status(text, color)
def setStatus2Text(self, text, color):
def set_status(text, color):
self.lblStatus2.setText(text)
if not color:
color = 'black'
self.lblStatus2.setStyleSheet('QLabel{color: ' + color + '}')
if threading.current_thread() != threading.main_thread():
self.call_in_main_thread(set_status, text, color)
else:
set_status(text, color)
def setMessage(self, text, color=None, style=None):
"""
Display message in the app message area.
:param text: Text to be displayed. If Text is empty, message area will be hidden.
:param color: Color of thext.
"""
def set_message(text, color, style):
left, top, right, bottom = self.layMessage.getContentsMargins()
if not text:
self.lblMessage.setVisible(False)
self.layMessage.setContentsMargins(left, top, right, 0)
else:
self.lblMessage.setVisible(True)
self.lblMessage.setText(text)
self.layMessage.setContentsMargins(left, top, right, 4)
if color:
style = '{color:%s}' % color
if style:
self.lblMessage.setStyleSheet('QLabel%s' % style)
if threading.current_thread() != threading.main_thread():
self.call_in_main_thread(set_message, text, color, style)
else:
set_message(text, color, style)
def getHwName(self):
if self.config.hw_type == HWType.trezor:
return 'Trezor'
elif self.config.hw_type == HWType.keepkey:
return 'KeepKey'
elif self.config.hw_type == HWType.ledger_nano_s:
return 'Ledger Nano S'
else:
return 'Unknown HW Type'
def connect_hardware_wallet(self) -> Optional[object]:
"""
Connects to hardware wallet if not connected before.
:return: Reference to hw client or None if not connected.
"""
ret = None
if self.hw_client:
cur_hw_type = hw_intf.get_hw_type(self.hw_client)
if self.config.hw_type != cur_hw_type:
self.on_action_disconnect_hw_triggered()
if not self.hw_client:
try:
try:
logging.info('Connecting to a hardware wallet device. self: ' + str(self))
self.hw_client = hw_intf.connect_hw(hw_session=self.hw_session,
device_id=None,
passphrase_encoding=self.config.hw_keepkey_psw_encoding,
hw_type=self.config.hw_type)
if self.config.dash_network == 'TESTNET':
# check if Dash testnet is supported by this hardware wallet
found_testnet_support = False
if self.config.hw_type in (HWType.trezor, HWType.keepkey):
try:
path = dash_utils.get_default_bip32_base_path(self.config.dash_network)
path += "/0'/0/0"
path_n = dash_utils.bip32_path_string_to_n(path)
addr = self.hw_client.get_address('Dash Testnet', path_n, False)
if dash_utils.validate_address(addr, self.config.dash_network):
found_testnet_support = True
except Exception as e:
if str(e).find('Invalid coin name') < 0:
logging.exception('Failed when looking for Dash testnet support')
elif self.config.hw_type == HWType.ledger_nano_s:
addr = hw_intf.get_address(self.hw_session,
dash_utils.get_default_bip32_path(self.config.dash_network))
if dash_utils.validate_address(addr, self.config.dash_network):
found_testnet_support = False
if not found_testnet_support:
url = get_note_url('DMT0002')
msg = f'Your hardware wallet device does not support Dash TESTNET ' \
f'(<a href="{url}">see details</a>).'
self.errorMsg(msg)
try:
self.disconnect_hardware_wallet()
except Exception:
pass
self.setStatus2Text(msg, 'red')
return
logging.info('Connected to a hardware wallet')
self.setStatus2Text('<b>HW status:</b> connected to %s' % hw_intf.get_hw_label(self.hw_client),
'green')
self.update_edit_controls_state()
except HardwareWalletCancelException:
raise
except Exception as e:
try:
self.disconnect_hardware_wallet()
except Exception:
pass
logging.info('Could not connect to a hardware wallet')
self.setStatus2Text('<b>HW status:</b> cannot connect to %s device' % self.getHwName(), 'red')
self.errorMsg(str(e))
ret = self.hw_client
except HardwareWalletCancelException:
raise
except HardwareWalletPinException as e:
self.errorMsg(e.msg)
if self.hw_client:
self.hw_client.clear_session()
self.update_edit_controls_state()
except OSError as e:
logging.exception('Exception occurred')
self.errorMsg('Cannot open %s device.' % self.getHwName())
self.update_edit_controls_state()
except Exception as e:
logging.exception('Exception occurred')
self.errorMsg(str(e))
if self.hw_client:
self.hw_client.init_device()
self.update_edit_controls_state()
else:
ret = self.hw_client
return ret
def btnConnectTrezorClick(self):
self.connect_hardware_wallet()
@pyqtSlot(bool)
def on_action_test_hw_connection_triggered(self):
self.connect_hardware_wallet()
self.update_edit_controls_state()
if self.hw_client:
try:
if self.config.hw_type in (HWType.trezor, HWType.keepkey):
features = self.hw_client.features
# hw_intf.ping(self.hw_session, 'Hello, press the button', button_protection=False,
# pin_protection=features.pin_protection,
# passphrase_protection=features.passphrase_protection)
self.infoMsg('Connection to %s device (%s) successful.' %
(self.getHwName(), hw_intf.get_hw_label(self.hw_client)))
elif self.config.hw_type == HWType.ledger_nano_s:
self.infoMsg('Connection to %s device successful.' %
(self.getHwName(),))
except HardwareWalletCancelException:
if self.hw_client:
self.hw_client.init_device()
def disconnect_hardware_wallet(self) -> None:
if self.hw_client:
hw_intf.disconnect_hw(self.hw_client)
del self.hw_client
self.hw_client = None
self.setStatus2Text('<b>HW status:</b> idle', 'black')
self.update_edit_controls_state()
@pyqtSlot(bool)
def on_action_disconnect_hw_triggered(self):
self.disconnect_hardware_wallet()
@pyqtSlot(bool)
def on_btnNewMn_clicked(self):
self.newMasternodeConfig(copy_values_from_current=False)
@pyqtSlot(bool)
def on_btnDeleteMn_clicked(self):
if self.curMasternode:
msg = QMessageBox()
msg.setIcon(QMessageBox.Warning)
msg.setText('Do you really want to delete current masternode configuration?')
msg.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msg.setDefaultButton(QMessageBox.No)
retval = msg.exec_()
if retval == QMessageBox.No:
return
self.config.masternodes.remove(self.curMasternode)
self.cboMasternodes.removeItem(self.cboMasternodes.currentIndex())
self.config.modified = True
self.update_edit_controls_state()
@pyqtSlot(bool)
def on_btnDuplicateMn_clicked(self):
self.newMasternodeConfig(copy_values_from_current=True)
@pyqtSlot(bool)
def on_btnEditMn_clicked(self):
self.editing_enabled = True
self.wdg_masternode.set_edit_mode(self.editing_enabled )
self.update_edit_controls_state()
@pyqtSlot(bool)
def on_btnCancelEditingMn_clicked(self, checked):
if self.config.is_modified():
if WndUtils.queryDlg('Configuration modified. Discard changes?',
buttons=QMessageBox.Yes | QMessageBox.Cancel,
default_button=QMessageBox.Cancel, icon=QMessageBox.Warning) == QMessageBox.Yes:
# reload the configuration (we don't keep the old values)
sel_mn_idx = self.app_config.masternodes.index(self.curMasternode)
# reload the configuration from file
self.load_configuration_from_file(self.config.app_config_file_name, ask_save_changes=False)
self.editing_enabled = False
if sel_mn_idx >= 0 and sel_mn_idx < len(self.config.masternodes):
self.curMasternode = self.config.masternodes[sel_mn_idx]
self.display_masternode_config(sel_mn_idx)
self.wdg_masternode.set_edit_mode(self.editing_enabled)
self.update_edit_controls_state()
return
else:
self.editing_enabled = False
self.wdg_masternode.set_edit_mode(self.editing_enabled)
self.update_edit_controls_state()
def scan_hw_for_bip32_paths(self, addresses) -> Tuple[Dict[str, str], bool]:
"""
Scans hardware wallet for bip32 paths of all Dash addresses passed in the addresses list.
:param addresses: list of Dash addresses to scan
:return: Tuple[Dict[str <dash address>, str <bip32 path>], bool <True if user cancelled scanning>]
"""
paths_found = []
user_cancelled = False
raise Exception('Temporarily not available') # todo: implement a new method based on bip44 wallet
def scan_for_bip32_thread(ctrl, addresses):
"""
Function run inside a thread which purpose is to scan hawrware wallet
for a bip32 paths with given Dash addresses.
:param cfg: Thread dialog configuration object.
:param addresses: list of Dash addresses to find bip32 path
:return:
"""
paths_found = 0
paths_checked = 0
found_adresses = {}
user_cancelled = False
ctrl.dlg_config_fun(dlg_title="Scanning hardware wallet...", show_progress_bar=False)
if self.hw_client:
address_n = dash_utils.get_default_bip32_base_path_n(self.config.dash_network) + [None, 0, None]
db_cur = self.config.db_intf.get_cursor()
try:
for addr_to_find_bip32 in addresses:
if not found_adresses.get(addr_to_find_bip32):
# check 10 addresses of account 0 (44'/5'/0'/0), then 10 addreses
# of account 1 (44'/5'/1'/0) and so on until 9th account.
# if not found, then check next 10 addresses of account 0 (44'/5'/0'/0)
# and so on; we assume here, that user rather puts collaterals
# under first addresses of subsequent accounts than under far addresses
# of the first account; if so, following iteration shuld be faster
found = False
if ctrl.finish:
break
for tenth_nr in range(0, 10):
if ctrl.finish:
break
for account_nr in range(0, 10):
if ctrl.finish:
break
for index in range(0, 10):
if ctrl.finish:
break
address_n[2] = account_nr + 0x80000000
address_n[4] = (tenth_nr * 10) + index
cur_bip32_path = bip32_path_n_to_string(address_n)
ctrl.display_msg_fun(
'<b>Scanning hardware wallet for BIP32 paths, please wait...</b><br><br>'
'Paths scanned: <span style="color:black">%d</span><br>'
'Keys found: <span style="color:green">%d</span><br>'
'Current path: <span style="color:blue">%s</span><br>'
% (paths_checked, paths_found, cur_bip32_path))
# todo: use Bip44Wallet to scan addresses
# addr_of_cur_path = hw_intf.get_address_ext(
# self.hw_session, address_n, db_cur, self.config.hw_encrypt_string,
# self.config.hw_decrypt_string)
# paths_checked += 1
# if addr_to_find_bip32 == addr_of_cur_path:
# found_adresses[addr_to_find_bip32] = cur_bip32_path
# found = True
# paths_found += 1
# break
# elif not found_adresses.get(addr_of_cur_path, None) and \
# addr_of_cur_path in addresses:
# # address of current bip32 path is in the search list
# found_adresses[addr_of_cur_path] = cur_bip32_path
if found:
break
if found:
break
finally:
if db_cur.connection.total_changes > 0:
self.config.db_intf.commit()
self.config.db_intf.release_cursor()
if ctrl.finish:
user_cancelled = True
return found_adresses, user_cancelled
try:
self.connect_hardware_wallet()
self.config.initialize_hw_encryption(self.hw_session)
if self.hw_client:
paths_found, user_cancelled = self.run_thread_dialog(scan_for_bip32_thread, (addresses,), True,
buttons=[{'std_btn': QtWidgets.QDialogButtonBox.Cancel}],
center_by_window=self)
except Exception:
logging.exception('Unhandled exception while converting address to bip32 path.')
raise
return paths_found, user_cancelled
@pyqtSlot(bool)
def on_action_import_masternode_conf_triggered(self, checked):
"""
Imports masternodes configuration from masternode.conf file.