forked from goatpig/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArmoryQt.py
executable file
·6004 lines (4969 loc) · 251 KB
/
ArmoryQt.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/python
# -*- coding: UTF-8 -*-
##############################################################################
# #
# Copyright (C) 2011-2015, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
# Copyright (C) 2016-17, goatpig #
# Distributed under the MIT license #
# See LICENSE-MIT or https://opensource.org/licenses/MIT #
# #
##############################################################################
import gettext
from copy import deepcopy
from datetime import datetime
import hashlib
import logging
import math
import os
import platform
import random
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time
import traceback
import glob
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import psutil
import CppBlockUtils as Cpp
from armorycolors import Colors, htmlColor, QAPP
from armoryengine.ALL import *
from armoryengine.Block import PyBlock
from armoryengine.Decorators import RemoveRepeatingExtensions
from armoryengine.PyBtcWalletRecovery import WalletConsistencyCheck
from SDM import SatoshiDaemonManager
from ui.QtExecuteSignal import QtExecuteSignal
# Setup translations
translator = QTranslator(QAPP)
app_dir = "./"
try:
app_dir = os.path.dirname(os.path.realpath(__file__))
except:
if OS_WINDOWS and getattr(sys, 'frozen', False):
app_dir = os.path.dirname(sys.executable)
translator.load(GUI_LANGUAGE, os.path.join(app_dir, "lang/"))
QAPP.installTranslator(translator)
from armorymodels import *
from jasvet import verifySignature
import qrc_img_resources
from qtdefines import *
from qtdialogs import *
from ui.MultiSigDialogs import DlgSelectMultiSigOption, DlgLockboxManager, \
DlgMergePromNotes, DlgCreatePromNote, DlgImportAsciiBlock
from ui.Wizards import WalletWizard, TxWizard
from ui.toolsDialogs import MessageSigningVerificationDialog
from dynamicImport import MODULE_PATH_KEY, ZIP_EXTENSION, getModuleList, importModule,\
verifyZipSignature, MODULE_ZIP_STATUS, INNER_ZIP_FILENAME,\
MODULE_ZIP_STATUS_KEY, getModuleListNoZip, dynamicImportNoZip
import tempfile
# Set URL handler to warn before opening url
handler = URLHandler()
QDesktopServices.setUrlHandler("http", handler.handleURL)
QDesktopServices.setUrlHandler("https", handler.handleURL)
# Load our framework with OS X-specific code.
if OS_MACOSX:
import ArmoryMac
# HACK ALERT: Qt has a bug in OS X where the system font settings will override
# the app's settings when a window is activated (e.g., Armory starts, the user
# switches to another app, and then switches back to Armory). There is a
# workaround, as used by TeXstudio and other programs.
# https://bugreports.qt-project.org/browse/QTBUG-5469 - Bug discussion.
# http://sourceforge.net/p/texstudio/bugs/594/?page=1 - Fix is mentioned.
# http://pyqt.sourceforge.net/Docs/PyQt4/qapplication.html#setDesktopSettingsAware
# - Mentions that this must be called before the app (QAPP) is created.
QApplication.setDesktopSettingsAware(False)
if OS_WINDOWS:
from _winreg import *
MODULES_ZIP_DIR_NAME = 'modules'
class ArmoryMainWindow(QMainWindow):
""" The primary Armory window """
#############################################################################
def __init__(self, parent=None, splashScreen=None):
super(ArmoryMainWindow, self).__init__(parent)
self.isShuttingDown = False
# Load the settings file
self.settingsPath = CLI_OPTIONS.settingsPath
self.settings = SettingsFile(self.settingsPath)
# SETUP THE WINDOWS DECORATIONS
self.lblLogoIcon = QLabel()
if USE_TESTNET:
self.setWindowTitle('Armory - Bitcoin Wallet Management [TESTNET] dlgMain')
self.iconfile = ':/armory_icon_green_32x32.png'
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_green_h56.png'))
if Colors.isDarkBkgd:
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_white_text_green_h56.png'))
elif USE_REGTEST:
self.setWindowTitle('Armory - Bitcoin Wallet Management [REGTEST] dlgMain')
self.iconfile = ':/armory_icon_green_32x32.png'
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_green_h56.png'))
if Colors.isDarkBkgd:
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_white_text_green_h56.png'))
else:
self.setWindowTitle('Armory - Bitcoin Wallet Management')
self.iconfile = ':/armory_icon_32x32.png'
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_h44.png'))
if Colors.isDarkBkgd:
self.lblLogoIcon.setPixmap(QPixmap(':/armory_logo_white_text_h56.png'))
# OS X requires some Objective-C code if we're switching to the testnet
# (green) icon. We should also use a larger icon. Otherwise, Info.plist
# takes care of everything.
if not OS_MACOSX:
self.setWindowIcon(QIcon(self.iconfile))
else:
if USE_TESTNET or USE_REGTEST:
self.iconfile = ':/armory_icon_green_fullres.png'
ArmoryMac.MacDockIconHandler.instance().setMainWindow(self)
ArmoryMac.MacDockIconHandler.instance().setIcon(QIcon(self.iconfile))
self.lblLogoIcon.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.netMode = NETWORKMODE.Offline
self.abortLoad = False
self.memPoolInit = False
self.needUpdateAfterScan = True
self.sweepAfterScanList = []
self.newWalletList = []
self.newZeroConfSinceLastUpdate = []
self.lastSDMStr = ""
self.doShutdown = False
self.downloadDict = {}
self.notAvailErrorCount = 0
self.satoshiVerWarnAlready = False
self.satoshiLatestVer = None
self.latestVer = {}
self.downloadDict = {}
self.satoshiHomePath = None
self.satoshiExeSearchPath = None
self.initSyncCircBuff = []
self.latestVer = {}
self.lastVersionsTxtHash = ''
self.dlgCptWlt = None
self.wasSynchronizing = False
self.entropyAccum = []
self.allLockboxes = []
self.lockboxIDMap = {}
self.cppLockboxWltMap = {}
self.broadcasting = {}
self.nodeStatus = None
self.numHeartBeat = 0
# Error and exit on both regtest and testnet
if USE_TESTNET and USE_REGTEST:
DlgRegAndTest(self, self).exec_()
# Full list of notifications, and notify IDs that should trigger popups
# when sending or receiving.
self.changelog = []
self.downloadLinks = {}
self.almostFullNotificationList = {}
self.notifyOnSend = set()
self.notifyonRecv = set()
self.versionNotification = {}
self.notifyIgnoreLong = []
self.notifyIgnoreShort = []
self.maxPriorityID = None
self.satoshiVersions = ['',''] # [curr, avail]
self.armoryVersions = [getVersionString(BTCARMORY_VERSION), '']
self.tempModulesDirName = None
self.internetStatus = None
self.lockboxLedgModel = None
#delayed URI parsing dict
self.delayedURIData = {}
self.delayedURIData['qLen'] = 0
#Setup the signal to spawn progress dialogs from the main thread
self.connect(self, SIGNAL('initTrigger') , self.initTrigger)
self.connect(self, SIGNAL('execTrigger'), self.execTrigger)
self.connect(self, SIGNAL('checkForNegImports'), self.checkForNegImports)
'''
With Qt, all GUI operations need to happen in the main thread. If
the GUI operation is triggered from another thread, it needs to
emit a Qt signal, so that Qt can schedule the operation in the main
thread. QtExecuteSignal is a utility class that handles the signaling
and delaying/threading of execution
'''
self.signalExecution = QtExecuteSignal(self)
#push model BDM notify signal
def cppNotifySignal(action, arglist):
self.signalExecution.executeMethod(\
self.handleCppNotification, action, arglist)
TheBDM.registerCppNotification(cppNotifySignal)
# We want to determine whether the user just upgraded to a new version
self.firstLoadNewVersion = False
currVerStr = 'v'+getVersionString(BTCARMORY_VERSION)
if self.settings.hasSetting('LastVersionLoad'):
lastVerStr = self.settings.get('LastVersionLoad')
if not lastVerStr==currVerStr:
LOGINFO('First load of new version: %s', currVerStr)
self.firstLoadNewVersion = True
self.settings.set('LastVersionLoad', currVerStr)
# Because dynamically retrieving addresses for querying transaction
# comments can be so slow, I use this txAddrMap to cache the mappings
# between tx's and addresses relevant to our wallets. It really only
# matters for massive tx with hundreds of outputs -- but such tx do
# exist and this is needed to accommodate wallets with lots of them.
self.txAddrMap = {}
def updateProgress(val):
if splashScreen is not None:
splashScreen.updateProgress(val)
self.loadWalletsAndSettings(updateProgress)
eulaAgreed = self.getSettingOrSetDefault('Agreed_to_EULA', False)
if not eulaAgreed:
DlgEULA(self,self).exec_()
armoryengine.ArmoryUtils.DEFAULT_ADDR_TYPE = \
self.getSettingOrSetDefault('Default_ReceiveType', 'P2PKH')
if not self.abortLoad:
self.acquireProcessMutex()
# acquireProcessMutex may have set this flag if something went wrong
if self.abortLoad:
LOGWARN('Armory startup was aborted. Closing.')
os._exit(0)
# We need to query this once at the beginning, to avoid having
# strange behavior if the user changes the setting but hasn't
# restarted yet...
self.doAutoBitcoind = \
self.getSettingOrSetDefault('ManageSatoshi', not OS_MACOSX)
# This is a list of alerts that the user has chosen to no longer
# be notified about
alert_str = str(self.getSettingOrSetDefault('IgnoreAlerts', ""))
if alert_str == "":
alerts = []
else:
alerts = alert_str.split(",")
self.ignoreAlerts = {int(s):True for s in alerts}
# Setup system tray and register "bitcoin:" URLs with the OS
self.setupSystemTray()
self.setupUriRegistration()
self.heartbeatCount = 0
self.extraHeartbeatSpecial = []
self.extraHeartbeatAlways = []
self.extraHeartbeatOnline = []
self.extraNewTxFunctions = []
self.extraNewBlockFunctions = []
self.extraShutdownFunctions = []
self.extraGoOnlineFunctions = []
self.oneTimeScanAction = {}
self.walletDialogDict = {}
self.lblArmoryStatus = QRichLabel_AutoToolTip(self.tr('<font color=%1>Offline</font> ').arg(htmlColor('TextWarn')), doWrap=False)
self.statusBar().insertPermanentWidget(0, self.lblArmoryStatus)
# Table for all the wallets
self.walletModel = AllWalletsDispModel(self)
self.walletsView = QTableView(self)
w,h = tightSizeNChar(self.walletsView, 55)
viewWidth = 1.2*w
sectionSz = 1.3*h
viewHeight = 4.4*sectionSz
self.walletsView.setModel(self.walletModel)
self.walletsView.setSelectionBehavior(QTableView.SelectRows)
self.walletsView.setSelectionMode(QTableView.SingleSelection)
self.walletsView.verticalHeader().setDefaultSectionSize(sectionSz)
self.walletsView.setMinimumSize(viewWidth, viewHeight)
self.walletsView.setItemDelegate(AllWalletsCheckboxDelegate(self))
self.walletsView.horizontalHeader().setResizeMode(0, QHeaderView.Fixed)
self.walletsView.hideColumn(0)
if self.usermode == USERMODE.Standard:
initialColResize(self.walletsView, [20, 0, 0.35, 0.2, 0.2])
else:
initialColResize(self.walletsView, [20, 0.15, 0.30, 0.2, 0.20])
if self.settings.hasSetting('LastFilterState'):
if self.settings.get('LastFilterState')==4:
self.walletsView.showColumn(0)
self.connect(self.walletsView, SIGNAL('doubleClicked(QModelIndex)'),
self.execDlgWalletDetails)
self.connect(self.walletsView, SIGNAL('clicked(QModelIndex)'),
self.execClickRow)
self.walletsView.setColumnWidth(WLTVIEWCOLS.Visible, 20)
w,h = tightSizeNChar(GETFONT('var'), 100)
# Prepare for tableView slices (i.e. "Showing 1 to 100 of 382", etc)
self.numShowOpts = [100,250,500,1000,'All']
self.sortLedgOrder = Qt.AscendingOrder
self.sortLedgCol = 0
self.currLedgMin = 1
self.currLedgMax = 100
self.currLedgWidth = 100
btnAddWallet = QPushButton(self.tr("Create Wallet"))
btnImportWlt = QPushButton(self.tr("Import or Restore Wallet"))
self.connect(btnAddWallet, SIGNAL('clicked()'), self.startWalletWizard)
self.connect(btnImportWlt, SIGNAL('clicked()'), self.execImportWallet)
# Put the Wallet info into it's own little box
lblAvail = QLabel(self.tr("<b>Available Wallets:</b>"))
viewHeader = makeLayoutFrame(HORIZONTAL, [lblAvail, \
'Stretch', \
btnAddWallet, \
btnImportWlt, ])
wltFrame = QFrame()
wltFrame.setFrameStyle(QFrame.Box|QFrame.Sunken)
wltLayout = QGridLayout()
wltLayout.addWidget(viewHeader, 0,0, 1,3)
wltLayout.addWidget(self.walletsView, 1,0, 1,3)
wltFrame.setLayout(wltLayout)
# Make the bottom 2/3 a tabwidget
self.mainDisplayTabs = QTabWidget()
# Put the labels into scroll areas just in case window size is small.
self.tabDashboard = QWidget()
self.setupDashboard()
# Combo box to filter ledger display
self.comboWltSelect = QComboBox()
self.populateLedgerComboBox()
self.connect(self.comboWltSelect, SIGNAL('activated(int)'),
self.changeWltFilter)
self.lblTot = QRichLabel(self.tr('<b>Maximum Funds:</b>'), doWrap=False);
self.lblSpd = QRichLabel(self.tr('<b>Spendable Funds:</b>'), doWrap=False);
self.lblUcn = QRichLabel(self.tr('<b>Unconfirmed:</b>'), doWrap=False);
self.lblTotalFunds = QRichLabel('-'*12, doWrap=False)
self.lblSpendFunds = QRichLabel('-'*12, doWrap=False)
self.lblUnconfFunds = QRichLabel('-'*12, doWrap=False)
self.lblTotalFunds.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblSpendFunds.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblUnconfFunds.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblTot.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblSpd.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblUcn.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
self.lblBTC1 = QRichLabel('<b>BTC</b>', doWrap=False)
self.lblBTC2 = QRichLabel('<b>BTC</b>', doWrap=False)
self.lblBTC3 = QRichLabel('<b>BTC</b>', doWrap=False)
self.ttipTot = self.createToolTipWidget( self.tr(
'Funds if all current transactions are confirmed. '
'Value appears gray when it is the same as your spendable funds.'))
self.ttipSpd = self.createToolTipWidget( self.tr('Funds that can be spent <i>right now</i>'))
self.ttipUcn = self.createToolTipWidget( self.tr(
'Funds that have less than 6 confirmations, and thus should not '
'be considered <i>yours</i>, yet.'))
self.frmTotals = QFrame()
self.frmTotals.setFrameStyle(STYLE_NONE)
frmTotalsLayout = QGridLayout()
frmTotalsLayout.addWidget(self.lblTot, 0,0)
frmTotalsLayout.addWidget(self.lblSpd, 1,0)
frmTotalsLayout.addWidget(self.lblUcn, 2,0)
frmTotalsLayout.addWidget(self.lblTotalFunds, 0,1)
frmTotalsLayout.addWidget(self.lblSpendFunds, 1,1)
frmTotalsLayout.addWidget(self.lblUnconfFunds, 2,1)
frmTotalsLayout.addWidget(self.lblBTC1, 0,2)
frmTotalsLayout.addWidget(self.lblBTC2, 1,2)
frmTotalsLayout.addWidget(self.lblBTC3, 2,2)
frmTotalsLayout.addWidget(self.ttipTot, 0,3)
frmTotalsLayout.addWidget(self.ttipSpd, 1,3)
frmTotalsLayout.addWidget(self.ttipUcn, 2,3)
self.frmTotals.setLayout(frmTotalsLayout)
# Add the available tabs to the main tab widget
self.MAINTABS = enum('Dash','Ledger')
self.mainDisplayTabs.addTab(self.tabDashboard, self.tr('Dashboard'))
##########################################################################
if not CLI_OPTIONS.disableModules:
if USE_TESTNET or USE_REGTEST:
self.loadArmoryModulesNoZip()
# Armory Modules are diabled on main net. If enabled it uses zip files to
# contain the modules
# else:
# self.loadArmoryModules()
##########################################################################
self.lbDialog = None
btnSendBtc = QPushButton(self.tr("Send Bitcoins"))
btnRecvBtc = QPushButton(self.tr("Receive Bitcoins"))
btnWltProps = QPushButton(self.tr("Wallet Properties"))
btnOfflineTx = QPushButton(self.tr("Offline Transactions"))
btnMultisig = QPushButton(self.tr("Lockboxes (Multi-Sig)"))
self.connect(btnWltProps, SIGNAL('clicked()'), self.execDlgWalletDetails)
self.connect(btnRecvBtc, SIGNAL('clicked()'), self.clickReceiveCoins)
self.connect(btnSendBtc, SIGNAL('clicked()'), self.clickSendBitcoins)
self.connect(btnOfflineTx,SIGNAL('clicked()'), self.execOfflineTx)
self.connect(btnMultisig, SIGNAL('clicked()'), self.browseLockboxes)
verStr = 'Armory %s / %s' % (getVersionString(BTCARMORY_VERSION),
UserModeStr(self, self.usermode))
lblInfo = QRichLabel(verStr, doWrap=False)
lblInfo.setFont(GETFONT('var',10))
lblInfo.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
logoBtnFrame = []
logoBtnFrame.append(self.lblLogoIcon)
logoBtnFrame.append(btnSendBtc)
logoBtnFrame.append(btnRecvBtc)
logoBtnFrame.append(btnWltProps)
if self.usermode in (USERMODE.Advanced, USERMODE.Expert):
logoBtnFrame.append(btnOfflineTx)
if self.usermode in (USERMODE.Expert,):
logoBtnFrame.append(btnMultisig)
logoBtnFrame.append(lblInfo)
logoBtnFrame.append('Stretch')
btnFrame = makeVertFrame(logoBtnFrame, STYLE_SUNKEN)
logoWidth=220
btnFrame.sizeHint = lambda: QSize(logoWidth*1.0, 10)
btnFrame.setMaximumWidth(logoWidth*1.2)
btnFrame.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
layout = QGridLayout()
layout.addWidget(btnFrame, 0, 0, 1, 1)
layout.addWidget(wltFrame, 0, 1, 1, 1)
layout.addWidget(self.mainDisplayTabs, 1, 0, 1, 2)
layout.setRowStretch(0, 1)
layout.setRowStretch(1, 5)
# Attach the layout to the frame that will become the central widget
mainFrame = QFrame()
mainFrame.setLayout(layout)
self.setCentralWidget(mainFrame)
self.setMinimumSize(750,500)
# Start the user at the dashboard
self.mainDisplayTabs.setCurrentIndex(self.MAINTABS.Dash)
##########################################################################
# Set up menu and actions
#MENUS = enum('File', 'Wallet', 'User', "Tools", "Network")
currmode = self.getSettingOrSetDefault('User_Mode', 'Advanced')
MENUS = enum('File', 'User', 'Tools', 'Addresses', 'Wallets', \
'MultiSig', 'Help')
self.menu = self.menuBar()
self.menusList = []
self.menusList.append( self.menu.addMenu(self.tr('&File')) )
self.menusList.append( self.menu.addMenu(self.tr('&User')) )
self.menusList.append( self.menu.addMenu(self.tr('&Tools')) )
self.menusList.append( self.menu.addMenu(self.tr('&Addresses')) )
self.menusList.append( self.menu.addMenu(self.tr('&Wallets')) )
self.menusList.append( self.menu.addMenu(self.tr('&MultiSig')) )
self.menusList.append( self.menu.addMenu(self.tr('&Help')) )
#self.menusList.append( self.menu.addMenu('&Network') )
def exportTx():
if not TheBDM.getState()==BDM_BLOCKCHAIN_READY:
QMessageBox.warning(self, self.tr('Transactions Unavailable'),
self.tr('Transaction history cannot be collected until Armory is '
'in online mode. Please try again when Armory is online. '),
QMessageBox.Ok)
return
else:
DlgExportTxHistory(self,self).exec_()
actExportTx = self.createAction(self.tr('&Export Transactions...'), exportTx)
actSettings = self.createAction(self.tr('&Settings...'), self.openSettings)
actMinimApp = self.createAction(self.tr('&Minimize Armory'), self.minimizeArmory)
actExportLog = self.createAction(self.tr('Export &Log File...'), self.exportLogFile)
actCloseApp = self.createAction(self.tr('&Quit Armory'), self.closeForReal)
self.menusList[MENUS.File].addAction(actExportTx)
self.menusList[MENUS.File].addAction(actSettings)
self.menusList[MENUS.File].addAction(actMinimApp)
self.menusList[MENUS.File].addAction(actExportLog)
self.menusList[MENUS.File].addAction(actCloseApp)
def chngStd(b):
if b: self.setUserMode(USERMODE.Standard)
def chngAdv(b):
if b: self.setUserMode(USERMODE.Advanced)
def chngDev(b):
if b: self.setUserMode(USERMODE.Expert)
modeActGrp = QActionGroup(self)
actSetModeStd = self.createAction(self.tr('&Standard'), chngStd, True)
actSetModeAdv = self.createAction(self.tr('&Advanced'), chngAdv, True)
actSetModeDev = self.createAction(self.tr('&Expert'), chngDev, True)
modeActGrp.addAction(actSetModeStd)
modeActGrp.addAction(actSetModeAdv)
modeActGrp.addAction(actSetModeDev)
self.menusList[MENUS.User].addAction(actSetModeStd)
self.menusList[MENUS.User].addAction(actSetModeAdv)
self.menusList[MENUS.User].addAction(actSetModeDev)
LOGINFO('Usermode: %s', currmode)
self.firstModeSwitch=True
if currmode=='Standard':
self.usermode = USERMODE.Standard
actSetModeStd.setChecked(True)
elif currmode=='Advanced':
self.usermode = USERMODE.Advanced
actSetModeAdv.setChecked(True)
elif currmode=='Expert':
self.usermode = USERMODE.Expert
actSetModeDev.setChecked(True)
def openMsgSigning():
MessageSigningVerificationDialog(self,self).exec_()
def openBlindBroad():
if not TheSDM.satoshiIsAvailable():
QMessageBox.warning(self, self.tr("Not Online"), self.tr(
'Bitcoin Core is not available, so Armory will not be able '
'to broadcast any transactions for you.'), QMessageBox.Ok)
return
DlgBroadcastBlindTx(self,self).exec_()
actOpenSigner = self.createAction(self.tr('&Message Signing/Verification...'), openMsgSigning)
if currmode=='Expert':
actOpenTools = self.createAction(self.tr('&EC Calculator...'), lambda: DlgECDSACalc(self,self, 1).exec_())
actBlindBroad = self.createAction(self.tr('&Broadcast Raw Transaction...'), openBlindBroad)
self.menusList[MENUS.Tools].addAction(actOpenSigner)
if currmode=='Expert':
self.menusList[MENUS.Tools].addAction(actOpenTools)
self.menusList[MENUS.Tools].addAction(actBlindBroad)
def mkprom():
if not TheBDM.getState()==BDM_BLOCKCHAIN_READY:
QMessageBox.warning(self, self.tr('Offline'), self.tr(
'Armory is currently offline, and cannot determine what funds are '
'available for Simulfunding. Please try again when Armory is in '
'online mode.'), QMessageBox.Ok)
else:
DlgCreatePromNote(self, self).exec_()
def msrevsign():
title = self.tr('Import Multi-Spend Transaction')
descr = self.tr(
'Import a signature-collector text block for review and signing. '
'It is usually a block of text with "TXSIGCOLLECT" in the first line, '
'or a <i>*.sigcollect.tx</i> file.')
ftypes = ['Signature Collectors (*.sigcollect.tx)']
dlgImport = DlgImportAsciiBlock(self, self, title, descr, ftypes,
UnsignedTransaction)
dlgImport.exec_()
if dlgImport.returnObj:
DlgMultiSpendReview(self, self, dlgImport.returnObj).exec_()
simulMerge = lambda: DlgMergePromNotes(self, self).exec_()
actMakeProm = self.createAction(self.tr('Simulfund &Promissory Note'), mkprom)
actPromCollect = self.createAction(self.tr('Simulfund &Collect && Merge'), simulMerge)
actMultiSpend = self.createAction(self.tr('Simulfund &Review && Sign'), msrevsign)
if not self.usermode==USERMODE.Expert:
self.menusList[MENUS.MultiSig].menuAction().setVisible(False)
# Addresses
actAddrBook = self.createAction(self.tr('View &Address Book...'), self.execAddressBook)
actSweepKey = self.createAction(self.tr('&Sweep Private Key/Address...'), self.menuSelectSweepKey)
actImportKey = self.createAction(self.tr('&Import Private Key/Address...'), self.menuSelectImportKey)
self.menusList[MENUS.Addresses].addAction(actAddrBook)
if not currmode=='Standard':
self.menusList[MENUS.Addresses].addAction(actImportKey)
self.menusList[MENUS.Addresses].addAction(actSweepKey)
actCreateNew = self.createAction(self.tr('&Create New Wallet'), self.startWalletWizard)
actImportWlt = self.createAction(self.tr('&Import or Restore Wallet'), self.execImportWallet)
actAddressBook = self.createAction(self.tr('View &Address Book'), self.execAddressBook)
actRecoverWlt = self.createAction(self.tr('&Fix Damaged Wallet'), self.RecoverWallet)
self.menusList[MENUS.Wallets].addAction(actCreateNew)
self.menusList[MENUS.Wallets].addAction(actImportWlt)
self.menusList[MENUS.Wallets].addSeparator()
self.menusList[MENUS.Wallets].addAction(actRecoverWlt)
execAbout = lambda: DlgHelpAbout(self).exec_()
actAboutWindow = self.createAction(self.tr('&About Armory...'), execAbout)
actClearMemPool = self.createAction(self.tr('Clear All Unconfirmed'), self.clearMemoryPool)
actRescanDB = self.createAction(self.tr('Rescan Databases'), self.rescanNextLoad)
actRebuildDB = self.createAction(self.tr('Rebuild and Rescan Databases'), self.rebuildNextLoad)
actRescanBalance = self.createAction(self.tr('Rescan Balance'), self.rescanBalanceNextLoad)
actFactoryReset = self.createAction(self.tr('Factory Reset'), self.factoryReset)
self.menusList[MENUS.Help].addAction(actAboutWindow)
self.menusList[MENUS.Help].addSeparator()
self.menusList[MENUS.Help].addSeparator()
self.menusList[MENUS.Help].addAction(actClearMemPool)
self.menusList[MENUS.Help].addAction(actRescanBalance)
self.menusList[MENUS.Help].addAction(actRescanDB)
self.menusList[MENUS.Help].addAction(actRebuildDB)
self.menusList[MENUS.Help].addAction(actFactoryReset)
execMSHack = lambda: DlgSelectMultiSigOption(self,self).exec_()
execBrowse = lambda: DlgLockboxManager(self,self).exec_()
actMultiHacker = self.createAction(self.tr('Multi-Sig Lockboxes'), execMSHack)
actBrowseLockboxes = self.createAction(self.tr('Lockbox &Manager...'), execBrowse)
#self.menusList[MENUS.MultiSig].addAction(actMultiHacker)
self.menusList[MENUS.MultiSig].addAction(actBrowseLockboxes)
self.menusList[MENUS.MultiSig].addAction(actMakeProm)
self.menusList[MENUS.MultiSig].addAction(actPromCollect)
self.menusList[MENUS.MultiSig].addAction(actMultiSpend)
self.startBlockchainProcessingInitialization()
# Restore any main-window geometry saved in the settings file
hexgeom = self.settings.get('MainGeometry')
hexwltsz = self.settings.get('MainWalletCols')
if len(hexgeom)>0:
geom = QByteArray.fromHex(hexgeom)
self.restoreGeometry(geom)
if len(hexwltsz)>0:
restoreTableView(self.walletsView, hexwltsz)
if DO_WALLET_CHECK:
self.checkWallets()
self.blkReceived = RightNow()
self.setDashboardDetails()
self.execIntroDialog()
#reactor.callLater(1, self.Heartbeat)
if self.getSettingOrSetDefault('MinimizeOnOpen', False) and not CLI_ARGS:
LOGINFO('MinimizeOnOpen is True')
self.minimizeArmory()
if CLI_ARGS:
self.signalExecution.callLater(1, self.uriLinkClicked, CLI_ARGS[0])
if OS_MACOSX:
self.macNotifHdlr = ArmoryMac.MacNotificationHandler()
# Now that construction of the UI is done
# Check for warnings to be displayed
# This is true if and only if the command line has a data dir that doesn't exist
# and can't be created.
if not CLI_OPTIONS.datadir in [ARMORY_HOME_DIR, DEFAULT]:
QMessageBox.warning(self, self.tr('Default Data Directory'), self.tr(
'Armory is using the default data directory because '
'the data directory specified in the command line could '
'not be found nor created.'), QMessageBox.Ok)
# This is true if and only if the command line has a database dir that doesn't exist
# and can't be created.
elif not CLI_OPTIONS.armoryDBDir in [ARMORY_DB_DIR, DEFAULT]:
QMessageBox.warning(self, self.tr('Default Database Directory'), self.tr(
'Armory is using the default database directory because '
'the database directory specified in the command line could '
'not be found nor created.'), QMessageBox.Ok)
# This is true if and only if the command line has a bitcoin dir that doesn't exist
#if not CLI_OPTIONS.satoshiHome in [BTC_HOME_DIR, DEFAULT]:
# QMessageBox.warning(self, self.tr('Bitcoin Directory'), self.tr(
# 'Armory is using the default Bitcoin directory because '
# 'the Bitcoin directory specified in the command line could '
# 'not be found.'), QMessageBox.Ok)
if not self.getSettingOrSetDefault('DNAA_DeleteLevelDB', False) and \
os.path.exists(os.path.join(ARMORY_DB_DIR, LEVELDB_BLKDATA)):
reply = MsgBoxWithDNAA(self, self, MSGBOX.Question, self.tr('Delete Old DB Directory'),
self.tr('Armory detected an older version Database. '
'Do you want to delete the old database? Choose yes if '
'do not think that you will revert to an older version of Armory.'), self.tr('Do not ask this question again'))
if reply[0]==True:
shutil.rmtree(os.path.join(ARMORY_DB_DIR, LEVELDB_BLKDATA))
shutil.rmtree(os.path.join(ARMORY_DB_DIR, LEVELDB_HEADERS))
if reply[1]==True:
self.writeSetting('DNAA_DeleteLevelDB', True)
self.signalExecution.callLater(1, self.walletTimeoutCheck)
####################################################
def getWatchingOnlyWallets(self):
result = []
for wltID in self.walletIDList:
if self.walletMap[wltID].watchingOnly:
result.append(wltID)
return result
####################################################
def changeWltFilter(self):
if self.netMode == NETWORKMODE.Offline:
return
currIdx = max(self.comboWltSelect.currentIndex(), 0)
currText = unicode(self.comboWltSelect.currentText()).lower()
if currText.lower().startswith('custom filter'):
self.walletsView.showColumn(0)
#self.walletsView.resizeColumnToContents(0)
else:
self.walletsView.hideColumn(0)
if currIdx != 4:
for i in range(0, len(self.walletVisibleList)):
self.walletVisibleList[i] = False
# If a specific wallet is selected, just set that and you're done
if currIdx > 4:
self.walletVisibleList[currIdx-7] = True
self.setWltSetting(self.walletIDList[currIdx-7], 'LedgerShow', True)
else:
# Else we walk through the wallets and flag the particular ones
typelist = [[wid, determineWalletType(self.walletMap[wid], self)[0]] \
for wid in self.walletIDList]
for i,winfo in enumerate(typelist):
wid,wtype = winfo[:]
if currIdx==0:
# My wallets
doShow = wtype in [WLTTYPES.Offline,WLTTYPES.Crypt,WLTTYPES.Plain]
self.walletVisibleList[i] = doShow
self.setWltSetting(wid, 'LedgerShow', doShow)
elif currIdx==1:
# Offline wallets
doShow = winfo[1] in [WLTTYPES.Offline]
self.walletVisibleList[i] = doShow
self.setWltSetting(wid, 'LedgerShow', doShow)
elif currIdx==2:
# Others' Wallets
doShow = winfo[1] in [WLTTYPES.WatchOnly]
self.walletVisibleList[i] = doShow
self.setWltSetting(wid, 'LedgerShow', doShow)
elif currIdx==3:
# All Wallets
self.walletVisibleList[i] = True
self.setWltSetting(wid, 'LedgerShow', True)
self.mainLedgerCurrentPage = 1
self.PageLineEdit.setText(unicode(self.mainLedgerCurrentPage))
self.wltIDList = []
for i,vis in enumerate(self.walletVisibleList):
if vis:
wltid = self.walletIDList[i]
if self.walletMap[wltid].isEnabled:
self.wltIDList.append(wltid)
TheBDM.bdv().updateWalletsLedgerFilter(self.wltIDList)
############################################################################
def loadArmoryModulesNoZip(self):
"""
This method checks for any .py files in the exec directory
"""
moduleDir = os.path.join(GetExecDir(), MODULES_ZIP_DIR_NAME)
if not moduleDir or not os.path.exists(moduleDir):
return
LOGWARN('Attempting to load modules from: %s' % MODULES_ZIP_DIR_NAME)
# This call does not eval any code in the modules. It simply
# loads the python files as raw chunks of text so we can
# check hashes and signatures
modMap = getModuleListNoZip(moduleDir)
for moduleName,infoMap in modMap.iteritems():
module = dynamicImportNoZip(moduleDir, moduleName, globals())
plugObj = module.PluginObject(self)
if not hasattr(plugObj,'getTabToDisplay') or \
not hasattr(plugObj,'tabName'):
LOGERROR('Module is malformed! No tabToDisplay or tabName attrs')
QMessageBox.critmoduleName(self, self.tr("Bad Module"), self.tr(
'The module you attempted to load (%1) is malformed. It is '
'missing attributes that are needed for Armory to load it. '
'It will be skipped.').arg(moduleName), QMessageBox.Ok)
continue
verPluginInt = getVersionInt(readVersionString(plugObj.maxVersion))
verArmoryInt = getVersionInt(BTCARMORY_VERSION)
if verArmoryInt >verPluginInt:
reply = QMessageBox.warning(self, self.tr("Outdated Module"), self.tr(
'Module "%1" is only specified to work up to Armory version %2. '
'You are using Armory version %3. Please remove the module if '
'you experience any problems with it, or contact the maintainer '
'for a new version. '
'<br><br> '
'Do you want to continue loading the module?').arg(moduleName),
QMessageBox.Yes | QMessageBox.No)
if not reply==QMessageBox.Yes:
continue
# All plugins should have "tabToDisplay" and "tabName" attributes
LOGWARN('Adding module to tab list: "' + plugObj.tabName + '"')
self.mainDisplayTabs.addTab(plugObj.getTabToDisplay(), plugObj.tabName)
# Also inject any extra methods that will be
injectFuncList = [ \
['injectHeartbeatAlwaysFunc', 'extraHeartbeatAlways'],
['injectHeartbeatOnlineFunc', 'extraHeartbeatOnline'],
['injectGoOnlineFunc', 'extraGoOnlineFunctions'],
['injectNewTxFunc', 'extraNewTxFunctions'],
['injectNewBlockFunc', 'extraNewBlockFunctions'],
['injectShutdownFunc', 'extraShutdownFunctions'] ]
# Add any methods
for plugFuncName,funcListName in injectFuncList:
if not hasattr(plugObj, plugFuncName):
continue
if not hasattr(self, funcListName):
LOGERROR('Missing an ArmoryQt list variable: %s' % funcListName)
continue
LOGINFO('Found module function: %s' % plugFuncName)
funcList = getattr(self, funcListName)
plugFunc = getattr(plugObj, plugFuncName)
funcList.append(plugFunc)
############################################################################
def loadArmoryModules(self):
"""
This method checks for any .zip files in the modules directory
"""
modulesZipDirPath = os.path.join(GetExecDir(), MODULES_ZIP_DIR_NAME)
if modulesZipDirPath and os.path.exists(modulesZipDirPath):
self.tempModulesDirName = tempfile.mkdtemp('modules')
# This call does not eval any code in the modules. It simply
# loads the python files as raw chunks of text so we can
# check hashes and signatures
modMap = getModuleList(modulesZipDirPath)
for moduleName,infoMap in modMap.iteritems():
moduleZipPath = os.path.join(modulesZipDirPath, infoMap[MODULE_PATH_KEY])
if infoMap[MODULE_ZIP_STATUS_KEY] == MODULE_ZIP_STATUS.Invalid:
reply = QMessageBox.warning(self, self.tr("Invalid Module"), self.tr(
'Armory detected the following module which is '
'<font color=%1><b>invalid</b></font>:'
'<br><br>'
' <b>Module Name:</b> %2<br>'
' <b>Module Path:</b> %3<br>'
'<br><br>'
'Armory will only run a module from a zip file that '
'has the required stucture.').arg(htmlColor('TextRed'), moduleName, moduleZipPath), QMessageBox.Ok)
elif not USE_TESTNET and not USE_REGTEST and infoMap[MODULE_ZIP_STATUS_KEY] == MODULE_ZIP_STATUS.Unsigned:
reply = QMessageBox.warning(self, self.tr("UNSIGNED Module"), self.tr(
'Armory detected the following module which '
'<font color="%1"><b>has not been signed by Armory</b></font> and may be dangerous: '
'<br><br>'
' <b>Module Name:</b> %2<br>'
' <b>Module Path:</b> %3<br>'
'<br><br>'
'Armory will not allow you to run this module.').arg(htmlColor('TextRed'), moduleName, moduleZipPath), QMessageBox.Ok)
else:
ZipFile(moduleZipPath).extract(INNER_ZIP_FILENAME, self.tempModulesDirName)
ZipFile(os.path.join(self.tempModulesDirName,INNER_ZIP_FILENAME)).extractall(self.tempModulesDirName)
plugin = importModule(self.tempModulesDirName, moduleName, globals())
plugObj = plugin.PluginObject(self)
if not hasattr(plugObj,'getTabToDisplay') or \
not hasattr(plugObj,'tabName'):
LOGERROR('Module is malformed! No tabToDisplay or tabName attrs')
QMessageBox.critmoduleName(self, self.tr("Bad Module"), self.tr(
'The module you attempted to load (%1) is malformed. It is '
'missing attributes that are needed for Armory to load it. '
'It will be skipped.').arg(moduleName), QMessageBox.Ok)
continue
verPluginInt = getVersionInt(readVersionString(plugObj.maxVersion))
verArmoryInt = getVersionInt(BTCARMORY_VERSION)
if verArmoryInt >verPluginInt:
reply = QMessageBox.warning(self, self.tr("Outdated Module"), self.tr(
'Module %1 is only specified to work up to Armory version %2. '
'You are using Armory version %3. Please remove the module if '
'you experience any problems with it, or contact the maintainer '
'for a new version.'
'<br><br>'
'Do you want to continue loading the module?').arg(moduleName, plugObj.maxVersion, getVersionString(BTCARMORY_VERSION)),
QMessageBox.Yes | QMessageBox.No)
if not reply==QMessageBox.Yes:
continue
# All plugins should have "tabToDisplay" and "tabName" attributes
LOGWARN('Adding module to tab list: "' + plugObj.tabName + '"')
self.mainDisplayTabs.addTab(plugObj.getTabToDisplay(), plugObj.tabName)
# Also inject any extra methods that will be
injectFuncList = [ \
['injectHeartbeatAlwaysFunc', 'extraHeartbeatAlways'],
['injectHeartbeatOnlineFunc', 'extraHeartbeatOnline'],
['injectGoOnlineFunc', 'extraGoOnlineFunctions'],
['injectNewTxFunc', 'extraNewTxFunctions'],
['injectNewBlockFunc', 'extraNewBlockFunctions'],
['injectShutdownFunc', 'extraShutdownFunctions'] ]
# Add any methods
for plugFuncName,funcListName in injectFuncList:
if not hasattr(plugObj, plugFuncName):
continue
if not hasattr(self, funcListName):
LOGERROR('Missing an ArmoryQt list variable: %s' % funcListName)
continue
LOGINFO('Found module function: %s' % plugFuncName)
funcList = getattr(self, funcListName)
plugFunc = getattr(plugObj, plugFuncName)
funcList.append(plugFunc)
############################################################################
def factoryReset(self):
"""
reply = QMessageBox.information(self,'Factory Reset', \
'You are about to revert all Armory settings '
'to the state they were in when Armory was first installed. '