forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ArmoryQt.py
5135 lines (4305 loc) · 222 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
################################################################################
# #
# Copyright (C) 2011-2013, Armory Technologies, Inc. #
# Distributed under the GNU Affero General Public License (AGPL v3) #
# See LICENSE or http://www.gnu.org/licenses/agpl.html #
# #
################################################################################
import hashlib
import random
import time
import os
import sys
import shutil
import math
import threading
import platform
import traceback
import socket
import subprocess
import psutil
import signal
import webbrowser
from datetime import datetime
# PyQt4 Imports
from PyQt4.QtCore import *
from PyQt4.QtGui import *
# Over 20,000 lines of python to help us out
from armoryengine import *
from armorymodels import *
from qtdialogs import *
from qtdefines import *
from armorycolors import Colors, htmlColor, QAPP
import qrc_img_resources
# All the twisted/networking functionality
from twisted.internet.protocol import Protocol, ClientFactory
from twisted.internet.defer import Deferred
from dialogs.toolsDialogs import MessageSigningVerificationDialog
if OS_WINDOWS:
from _winreg import *
class ArmoryMainWindow(QMainWindow):
""" The primary Armory window """
#############################################################################
def __init__(self, parent=None):
super(ArmoryMainWindow, self).__init__(parent)
TimerStart('MainWindowInit')
self.bornOnTime = RightNow()
# 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 - Protoshares Wallet Management [TESTNET]')
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 - Protoshares 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'))
self.setWindowIcon(QIcon(self.iconfile))
self.lblLogoIcon.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
self.netMode = NETWORKMODE.Offline
self.abortLoad = False
self.memPoolInit = False
self.dirtyLastTime = False
self.needUpdateAfterScan = True
self.sweepAfterScanList = []
self.newWalletList = []
self.newZeroConfSinceLastUpdate = []
self.lastBDMState = ['Uninitialized', None]
self.lastSDMState = 'Uninitialized'
self.detectNotSyncQ = [0,0,0,0,0]
self.noSyncWarnYet = True
self.doHardReset = False
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 = {}
# We want to determine whether the user just upgraded to a new version
self.firstLoadNewVersion = False
currVerStr = 'v'+getVersionString(PTSARMORY_VERSION)
if self.settings.hasSetting('LastVersionLoad'):
lastVerStr = self.settings.get('LastVersionLoad')
if not lastVerStr==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 = {}
self.loadWalletsAndSettings()
eulaAgreed = self.getSettingOrSetDefault('Agreed_to_EULA', False)
if not eulaAgreed:
DlgEULA(self,self).exec_()
if not self.abortLoad:
self.setupNetworking()
# setupNetworking 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.doManageSatoshi = \
self.getSettingOrSetDefault('ManageSatoshi', not OS_MACOSX)
# If we're going into online mode, start loading blockchain
if self.doManageSatoshi:
self.startProtosharesdIfNecessary()
else:
self.loadBlockchainIfNecessary()
# Setup system tray and register "protoshares:" URLs with the OS
self.setupSystemTray()
self.setupUriRegistration()
self.extraHeartbeatSpecial = []
self.extraHeartbeatOnline = []
self.extraHeartbeatAlways = []
self.lblArmoryStatus = QRichLabel('<font color=%s>Offline</font> ' %
htmlColor('TextWarn'), doWrap=False)
self.statusBar().insertPermanentWidget(0, self.lblArmoryStatus)
# Keep a persistent printer object for paper backups
self.printer = QPrinter(QPrinter.HighResolution)
self.printer.setPageSize(QPrinter.Letter)
# Table for all the wallets
self.walletModel = AllWalletsDispModel(self)
self.walletsView = QTableView()
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)
if self.usermode == USERMODE.Standard:
initialColResize(self.walletsView, [0, 0.35, 0.2, 0.2])
self.walletsView.hideColumn(0)
else:
initialColResize(self.walletsView, [0.15, 0.30, 0.2, 0.20])
self.connect(self.walletsView, SIGNAL('doubleClicked(QModelIndex)'), \
self.execDlgWalletDetails)
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
# Table to display ledger/activity
self.ledgerTable = []
self.ledgerModel = LedgerDispModelSimple(self.ledgerTable, self, self)
#self.ledgerProxy = LedgerDispSortProxy()
#self.ledgerProxy.setSourceModel(self.ledgerModel)
#self.ledgerProxy.setDynamicSortFilter(False)
self.ledgerView = QTableView()
self.ledgerView.setModel(self.ledgerModel)
self.ledgerView.setSortingEnabled(True)
self.ledgerView.setItemDelegate(LedgerDispDelegate(self))
self.ledgerView.setSelectionBehavior(QTableView.SelectRows)
self.ledgerView.setSelectionMode(QTableView.SingleSelection)
self.ledgerView.verticalHeader().setDefaultSectionSize(sectionSz)
self.ledgerView.verticalHeader().hide()
self.ledgerView.horizontalHeader().setResizeMode(0, QHeaderView.Fixed)
self.ledgerView.horizontalHeader().setResizeMode(3, QHeaderView.Fixed)
self.ledgerView.hideColumn(LEDGERCOLS.isOther)
self.ledgerView.hideColumn(LEDGERCOLS.UnixTime)
self.ledgerView.hideColumn(LEDGERCOLS.WltID)
self.ledgerView.hideColumn(LEDGERCOLS.TxHash)
self.ledgerView.hideColumn(LEDGERCOLS.isCoinbase)
self.ledgerView.hideColumn(LEDGERCOLS.toSelf)
self.ledgerView.hideColumn(LEDGERCOLS.DoubleSpend)
dateWidth = tightSizeStr(self.ledgerView, '_9999-Dec-99 99:99pm__')[0]
nameWidth = tightSizeStr(self.ledgerView, '9'*32)[0]
cWidth = 20 # num-confirm icon width
tWidth = 72 # date icon width
initialColResize(self.ledgerView, [cWidth, 0, dateWidth, tWidth, 0.30, 0.40, 0.3])
self.connect(self.ledgerView, SIGNAL('doubleClicked(QModelIndex)'), \
self.dblClickLedger)
self.ledgerView.setContextMenuPolicy(Qt.CustomContextMenu)
self.ledgerView.customContextMenuRequested.connect(self.showContextMenuLedger)
btnAddWallet = QPushButton("Create Wallet")
btnImportWlt = QPushButton("Import or Restore Wallet")
self.connect(btnAddWallet, SIGNAL('clicked()'), self.createNewWallet)
self.connect(btnImportWlt, SIGNAL('clicked()'), self.execImportWallet)
# Put the Wallet info into it's own little box
lblAvail = QLabel("<b>Available Wallets:</b>")
viewHeader = makeLayoutFrame('Horiz', [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.ledgerView.horizontalHeader(), \
SIGNAL('sortIndicatorChanged(int,Qt::SortOrder)'), \
self.changeLedgerSorting)
# Create the new ledger twice: can't update the ledger up/down
# widgets until we know how many ledger entries there are from
# the first call
def createLedg():
self.createCombinedLedger()
if self.frmLedgUpDown.isVisible():
self.changeNumShow()
self.connect(self.comboWltSelect, SIGNAL('activated(int)'), createLedg)
self.lblTot = QRichLabel('<b>Maximum Funds:</b>', doWrap=False);
self.lblSpd = QRichLabel('<b>Spendable Funds:</b>', doWrap=False);
self.lblUcn = QRichLabel('<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.lblPTS1 = QRichLabel('<b>PTS</b>', doWrap=False)
self.lblPTS2 = QRichLabel('<b>PTS</b>', doWrap=False)
self.lblPTS3 = QRichLabel('<b>PTS</b>', doWrap=False)
self.ttipTot = self.createToolTipWidget( \
'Funds if all current transactions are confirmed. '
'Value appears gray when it is the same as your spendable funds.')
self.ttipSpd = self.createToolTipWidget( 'Funds that can be spent <i>right now</i>')
self.ttipUcn = self.createToolTipWidget( \
'Funds that have less than 6 confirmations, and thus should not '
'be considered <i>yours</i>, yet.')
frmTotals = QFrame()
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.lblPTS1, 0,2)
frmTotalsLayout.addWidget(self.lblPTS2, 1,2)
frmTotalsLayout.addWidget(self.lblPTS3, 2,2)
frmTotalsLayout.addWidget(self.ttipTot, 0,3)
frmTotalsLayout.addWidget(self.ttipSpd, 1,3)
frmTotalsLayout.addWidget(self.ttipUcn, 2,3)
frmTotals.setLayout(frmTotalsLayout)
# Will fill this in when ledgers are created & combined
self.lblLedgShowing = QRichLabel('Showing:', hAlign=Qt.AlignHCenter)
self.lblLedgRange = QRichLabel('', hAlign=Qt.AlignHCenter)
self.lblLedgTotal = QRichLabel('', hAlign=Qt.AlignHCenter)
self.comboNumShow = QComboBox()
for s in self.numShowOpts:
self.comboNumShow.addItem( str(s) )
self.comboNumShow.setCurrentIndex(0)
self.comboNumShow.setMaximumWidth( tightSizeStr(self, '_9999_')[0]+25 )
self.btnLedgUp = QLabelButton('')
self.btnLedgUp.setMaximumHeight(20)
self.btnLedgUp.setPixmap(QPixmap(':/scroll_up_18.png'))
self.btnLedgUp.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self.btnLedgUp.setVisible(False)
self.btnLedgDn = QLabelButton('')
self.btnLedgDn.setMaximumHeight(20)
self.btnLedgDn.setPixmap(QPixmap(':/scroll_down_18.png'))
self.btnLedgDn.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter)
self.connect(self.comboNumShow, SIGNAL('activated(int)'), self.changeNumShow)
self.connect(self.btnLedgUp, SIGNAL('clicked()'), self.clickLedgUp)
self.connect(self.btnLedgDn, SIGNAL('clicked()'), self.clickLedgDn)
frmFilter = makeVertFrame([QLabel('Filter:'), self.comboWltSelect, 'Stretch'])
self.frmLedgUpDown = QFrame()
layoutUpDown = QGridLayout()
layoutUpDown.addWidget(self.lblLedgShowing,0,0)
layoutUpDown.addWidget(self.lblLedgRange, 1,0)
layoutUpDown.addWidget(self.lblLedgTotal, 2,0)
layoutUpDown.addWidget(self.btnLedgUp, 0,1)
layoutUpDown.addWidget(self.comboNumShow, 1,1)
layoutUpDown.addWidget(self.btnLedgDn, 2,1)
layoutUpDown.setVerticalSpacing(2)
self.frmLedgUpDown.setLayout(layoutUpDown)
self.frmLedgUpDown.setFrameStyle(STYLE_SUNKEN)
frmLower = makeHorizFrame([ frmFilter, \
'Stretch', \
self.frmLedgUpDown, \
'Stretch', \
frmTotals])
# Now add the ledger to the bottom of the window
ledgFrame = QFrame()
ledgFrame.setFrameStyle(QFrame.Box|QFrame.Sunken)
ledgLayout = QGridLayout()
#ledgLayout.addWidget(QLabel("<b>Ledger</b>:"), 0,0)
ledgLayout.addWidget(self.ledgerView, 1,0)
ledgLayout.addWidget(frmLower, 2,0)
ledgLayout.setRowStretch(0, 0)
ledgLayout.setRowStretch(1, 1)
ledgLayout.setRowStretch(2, 0)
ledgFrame.setLayout(ledgLayout)
self.tabActivity = QWidget()
self.tabActivity.setLayout(ledgLayout)
# Add the available tabs to the main tab widget
self.MAINTABS = enum('Dashboard','Transactions')
self.mainDisplayTabs.addTab(self.tabDashboard, 'Dashboard')
self.mainDisplayTabs.addTab(self.tabActivity, 'Transactions')
btnSendPts = QPushButton("Send Protoshares")
btnRecvPts = QPushButton("Receive Protoshares")
btnWltProps = QPushButton("Wallet Properties")
btnOfflineTx = QPushButton("Offline Transactions")
self.connect(btnWltProps, SIGNAL('clicked()'), self.execDlgWalletDetails)
self.connect(btnRecvPts, SIGNAL('clicked()'), self.clickReceiveCoins)
self.connect(btnSendPts, SIGNAL('clicked()'), self.clickSendProtoshares)
self.connect(btnOfflineTx,SIGNAL('clicked()'), self.execOfflineTx)
verStr = 'Armory %s-beta / %s' % (getVersionString(PTSARMORY_VERSION), \
UserModeStr(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(btnSendPts)
logoBtnFrame.append(btnRecvPts)
logoBtnFrame.append(btnWltProps)
if self.usermode in (USERMODE.Advanced, USERMODE.Expert):
logoBtnFrame.append(btnOfflineTx)
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.Dashboard)
from twisted.internet import reactor
# Show the appropriate information on the dashboard
self.setDashboardDetails(INIT=True)
##########################################################################
# 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', 'Help')
self.menu = self.menuBar()
self.menusList = []
self.menusList.append( self.menu.addMenu('&File') )
self.menusList.append( self.menu.addMenu('&User') )
self.menusList.append( self.menu.addMenu('&Tools') )
self.menusList.append( self.menu.addMenu('&Addresses') )
self.menusList.append( self.menu.addMenu('&Wallets') )
self.menusList.append( self.menu.addMenu('&Help') )
#self.menusList.append( self.menu.addMenu('&Network') )
def exportTx():
if not TheBDM.getBDMState()=='BlockchainReady':
QMessageBox.warning(self, 'Transactions Unavailable', \
'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('&Export Transactions', exportTx)
actSettings = self.createAction('&Settings', self.openSettings)
actMinimApp = self.createAction('&Minimize Armory', self.minimizeArmory)
actExportLog = self.createAction('Export &Log File', self.exportLogFile)
actCloseApp = self.createAction('&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('&Standard', chngStd, True)
actSetModeAdv = self.createAction('&Advanced', chngAdv, True)
actSetModeDev = self.createAction('&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_()
actOpenSigner = self.createAction('&Message Signing/Verification', openMsgSigning)
if currmode=='Expert':
actOpenTools = self.createAction('&EC Calculator', lambda: DlgECDSACalc(self,self, 1).exec_())
self.menusList[MENUS.Tools].addAction(actOpenSigner)
if currmode=='Expert':
self.menusList[MENUS.Tools].addAction(actOpenTools)
# Addresses
actAddrBook = self.createAction('View &Address Book', self.execAddressBook)
actSweepKey = self.createAction('&Sweep Private Key/Address', self.menuSelectSweepKey)
actImportKey = self.createAction('&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('&Create New Wallet', self.createNewWallet)
actImportWlt = self.createAction('&Import or Restore Wallet', self.execImportWallet)
actAddressBook = self.createAction('View &Address Book', self.execAddressBook)
#actRescanOnly = self.createAction('Rescan Blockchain', self.forceRescanDB)
#actRebuildAll = self.createAction('Rescan with Database Rebuild', self.forceRebuildAndRescan)
self.menusList[MENUS.Wallets].addAction(actCreateNew)
self.menusList[MENUS.Wallets].addAction(actImportWlt)
self.menusList[MENUS.Wallets].addSeparator()
#self.menusList[MENUS.Wallets].addAction(actRescanOnly)
#self.menusList[MENUS.Wallets].addAction(actRebuildAll)
#self.menusList[MENUS.Wallets].addAction(actMigrateSatoshi)
#self.menusList[MENUS.Wallets].addAction(actAddressBook)
execAbout = lambda: DlgHelpAbout(self).exec_()
execVersion = lambda: self.checkForLatestVersion(wasRequested=True)
execTrouble = lambda: webbrowser.open('https://bitcoinarmory.com/troubleshooting/')
actAboutWindow = self.createAction('About Armory', execAbout)
actTroubleshoot = self.createAction('Troubleshooting Armory', execTrouble)
actVersionCheck = self.createAction('Armory Version...', execVersion)
actFactoryReset = self.createAction('Revert All Settings', self.factoryReset)
actClearMemPool = self.createAction('Clear All Unconfirmed', self.clearMemoryPool)
actRescanDB = self.createAction('Rescan Databases', self.rescanNextLoad)
actRebuildDB = self.createAction('Rebuild and Rescan Databases', self.rebuildNextLoad)
self.menusList[MENUS.Help].addAction(actAboutWindow)
self.menusList[MENUS.Help].addAction(actTroubleshoot)
self.menusList[MENUS.Help].addAction(actVersionCheck)
self.menusList[MENUS.Help].addAction(actFactoryReset)
self.menusList[MENUS.Help].addSeparator()
self.menusList[MENUS.Help].addAction(actClearMemPool)
self.menusList[MENUS.Help].addAction(actRescanDB)
self.menusList[MENUS.Help].addAction(actRebuildDB)
# Restore any main-window geometry saved in the settings file
hexgeom = self.settings.get('MainGeometry')
hexledgsz = self.settings.get('MainLedgerCols')
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 len(hexledgsz)>0:
restoreTableView(self.ledgerView, hexledgsz)
self.ledgerView.setColumnWidth(LEDGERCOLS.NumConf, 20)
self.ledgerView.setColumnWidth(LEDGERCOLS.TxDir, 72)
TimerStop('MainWindowInit')
reactor.callLater(0.1, self.execIntroDialog)
reactor.callLater(1, self.Heartbeat)
if CLI_ARGS:
reactor.callLater(1, self.uriLinkClicked, CLI_ARGS[0])
elif not self.firstLoad:
# Don't need to bother the user on the first load with updating
reactor.callLater(0.2, self.checkForLatestVersion)
####################################################
def factoryReset(self):
reply = QMessageBox.information(self,'Revert all Settings?', \
'You are about to revert all Armory settings '
'to the state they were in when Armory was first installed. '
'<br><br>'
'If you click "Yes," Armory will exit after settings are '
'reverted. You will have to manually start Armory again.'
'<br><br>'
'Do you want to continue? ', \
QMessageBox.Yes | QMessageBox.No)
if reply==QMessageBox.Yes:
self.doHardReset = True
self.closeForReal()
####################################################
def clearMemoryPool(self):
touchFile( os.path.join(ARMORY_HOME_DIR, 'clearmempool.txt') )
msg = tr("""
The next time you restart Armory, all unconfirmed transactions will
be cleared allowing you to retry any stuck transactions.""")
if not self.getSettingOrSetDefault('ManageSatoshi', True):
msg += tr("""
<br><br>Make sure you also restart Protoshares-Qt
(or protosharesd) and let it synchronize again before you restart
Armory. Doing so will clear its memory pool, as well""")
QMessageBox.information(self, tr('Memory Pool'), msg, QMessageBox.Ok)
####################################################
def rescanNextLoad(self):
reply = QMessageBox.warning(self, tr('Queue Rescan?'), tr("""
The next time you restart Armory, it will rescan the blockchain
database, and reconstruct your wallet histories from scratch.
The rescan will take 10-60 minutes depending on your system.
<br><br>
Do you wish to force a rescan on the next Armory restart?"""), \
QMessageBox.Yes | QMessageBox.No)
if reply==QMessageBox.Yes:
touchFile( os.path.join(ARMORY_HOME_DIR, 'rescan.txt') )
####################################################
def rebuildNextLoad(self):
reply = QMessageBox.warning(self, tr('Queue Rebuild?'), tr("""
The next time you restart Armory, it will rebuild and rescan
the entire blockchain database. This operation can take between
30 minutes and 4 hours depending on you system speed.
<br><br>
Do you wish to force a rebuild on the next Armory restart?"""), \
QMessageBox.Yes | QMessageBox.No)
if reply==QMessageBox.Yes:
touchFile( os.path.join(ARMORY_HOME_DIR, 'rebuild.txt') )
####################################################
def loadFailedManyTimesFunc(self, nFail):
"""
For now, if the user is having trouble loading the blockchain, all
we do is delete mempool.bin (which is frequently corrupted but not
detected as such. However, we may expand this in the future, if
it's determined that more-complicated things are necessary.
"""
LOGERROR('%d attempts to load blockchain failed. Remove mempool.bin.' % nFail)
mempoolfile = os.path.join(ARMORY_HOME_DIR,'mempool.bin')
if os.path.exists(mempoolfile):
os.remove(mempoolfile)
else:
LOGERROR('File mempool.bin does not exist. Nothing deleted.')
####################################################
def menuSelectImportKey(self):
QMessageBox.information(self, 'Select Wallet', \
'You must import an address into a specific wallet. If '
'you do not want to import the key into any available wallet, '
'it is recommeneded you make a new wallet for this purpose.'
'<br><br>'
'Double-click on the desired wallet from the main window, then '
'click on "Import/Sweep Private Keys" on the bottom-right '
'of the properties window.'
'<br><br>'
'Keys cannot be imported into watching-only wallets, only full '
'wallets.', QMessageBox.Ok)
####################################################
def menuSelectSweepKey(self):
QMessageBox.information(self, 'Select Wallet', \
'You must select a wallet into which funds will be swept. '
'Double-click on the desired wallet from the main window, then '
'click on "Import/Sweep Private Keys" on the bottom-right '
'of the properties window to sweep to that wallet.'
'<br><br>'
'Keys cannot be swept into watching-only wallets, only full '
'wallets.', QMessageBox.Ok)
####################################################
def changeNumShow(self):
prefWidth = self.numShowOpts[self.comboNumShow.currentIndex()]
if prefWidth=='All':
self.currLedgMin = 1;
self.currLedgMax = self.ledgerSize
self.currLedgWidth = -1;
else:
self.currLedgMax = self.currLedgMin + prefWidth - 1
self.currLedgWidth = prefWidth
self.applyLedgerRange()
####################################################
def clickLedgUp(self):
self.currLedgMin -= self.currLedgWidth
self.currLedgMax -= self.currLedgWidth
self.applyLedgerRange()
####################################################
def clickLedgDn(self):
self.currLedgMin += self.currLedgWidth
self.currLedgMax += self.currLedgWidth
self.applyLedgerRange()
####################################################
def applyLedgerRange(self):
if self.currLedgMin < 1:
toAdd = 1 - self.currLedgMin
self.currLedgMin += toAdd
self.currLedgMax += toAdd
if self.currLedgMax > self.ledgerSize:
toSub = self.currLedgMax - self.ledgerSize
self.currLedgMin -= toSub
self.currLedgMax -= toSub
self.currLedgMin = max(self.currLedgMin, 1)
self.btnLedgUp.setVisible(self.currLedgMin!=1)
self.btnLedgDn.setVisible(self.currLedgMax!=self.ledgerSize)
self.createCombinedLedger()
####################################################
def openSettings(self):
LOGDEBUG('openSettings')
dlgSettings = DlgSettings(self, self)
dlgSettings.exec_()
####################################################
def setupSystemTray(self):
LOGDEBUG('setupSystemTray')
# Creating a QSystemTray
self.sysTray = QSystemTrayIcon(self)
self.sysTray.setIcon( QIcon(self.iconfile) )
self.sysTray.setVisible(True)
self.sysTray.setToolTip('Armory' + (' [Testnet]' if USE_TESTNET else ''))
self.connect(self.sysTray, SIGNAL('messageClicked()'), self.bringArmoryToFront)
self.connect(self.sysTray, SIGNAL('activated(QSystemTrayIcon::ActivationReason)'), \
self.sysTrayActivated)
menu = QMenu(self)
def traySend():
self.bringArmoryToFront()
self.clickSendProtoshares()
def trayRecv():
self.bringArmoryToFront()
self.clickReceiveCoins()
actShowArmory = self.createAction('Show Armory', self.bringArmoryToFront)
actSendPts = self.createAction('Send Protoshares', traySend)
actRcvPts = self.createAction('Receive Protoshares', trayRecv)
actClose = self.createAction('Quit Armory', self.closeForReal)
# Create a short menu of options
menu.addAction(actShowArmory)
menu.addAction(actSendPts)
menu.addAction(actRcvPts)
menu.addSeparator()
menu.addAction(actClose)
self.sysTray.setContextMenu(menu)
self.notifyQueue = []
self.notifyBlockedUntil = 0
#############################################################################
@AllowAsync
def registerProtosharesWithFF(self):
#the 3 nodes needed to add to register protoshares as a protocol in FF
rdfschemehandler = 'about=\"urn:scheme:handler:protoshares\"'
rdfscheme = 'about=\"urn:scheme:protoshares\"'
rdfexternalApp = 'about=\"urn:scheme:externalApplication:protoshares\"'
#find mimeTypes.rdf file
home = os.getenv('HOME')
out,err = execAndWait('find %s -type f -name \"mimeTypes.rdf\"' % home)
for rdfs in out.split('\n'):
if rdfs:
try:
FFrdf = open(rdfs, 'r+')
except:
continue
ct = FFrdf.readlines()
rdfsch=-1
rdfsc=-1
rdfea=-1
i=0
#look for the nodes
for line in ct:
if rdfschemehandler in line:
rdfsch=i
elif rdfscheme in line:
rdfsc=i
elif rdfexternalApp in line:
rdfea=i
i+=1
#seek to end of file
FFrdf.seek(-11, 2)
i=0;
#add the missing nodes
if rdfsch == -1:
FFrdf.write(' <RDF:Description RDF:about=\"urn:scheme:handler:protoshares\"\n')
FFrdf.write(' NC:alwaysAsk=\"false\">\n')
FFrdf.write(' <NC:externalApplication RDF:resource=\"urn:scheme:externalApplication:protoshares\"/>\n')
FFrdf.write(' <NC:possibleApplication RDF:resource=\"urn:handler:local:/usr/bin/xdg-open\"/>\n')
FFrdf.write(' </RDF:Description>\n')
i+=1
if rdfsc == -1:
FFrdf.write(' <RDF:Description RDF:about=\"urn:scheme:protoshares\"\n')
FFrdf.write(' NC:value=\"protoshares\">\n')
FFrdf.write(' <NC:handlerProp RDF:resource=\"urn:scheme:handler:protoshares\"/>\n')
FFrdf.write(' </RDF:Description>\n')
i+=1
if rdfea == -1:
FFrdf.write(' <RDF:Description RDF:about=\"urn:scheme:externalApplication:protoshares\"\n')
FFrdf.write(' NC:prettyName=\"xdg-open\"\n')
FFrdf.write(' NC:path=\"/usr/bin/xdg-open\" />\n')
i+=1
if i != 0:
FFrdf.write('</RDF:RDF>\n')
FFrdf.close()
#############################################################################
def setupUriRegistration(self, justDoIt=False):
"""
Setup Armory as the default application for handling protoshares: links
"""
LOGINFO('setupUriRegistration')
if OS_LINUX:
out,err = execAndWait('gconftool-2 --get /desktop/gnome/url-handlers/protoshares/command')
out2,err = execAndWait('xdg-mime query default x-scheme-handler/protoshares')
#check FF protocol association
#checkFF_thread = threading.Thread(target=self.registerProtosharesWithFF)
#checkFF_thread.start()
self.registerProtosharesWithFF(async=True)
def setAsDefault():
LOGINFO('Setting up Armory as default URI handler...')
execAndWait('gconftool-2 -t string -s /desktop/gnome/url-handlers/protoshares/command "python /usr/lib/armory/ArmoryQt.py \"%s\""')
execAndWait('gconftool-2 -s /desktop/gnome/url-handlers/protoshares/needs_terminal false -t bool')
execAndWait('gconftool-2 -t bool -s /desktop/gnome/url-handlers/protoshares/enabled true')
execAndWait('xdg-mime default armory.desktop x-scheme-handler/protoshares')
if ('no value' in out.lower() or 'no value' in err.lower()) and not 'armory.desktop' in out2.lower():
# Silently add Armory if it's never been set before
setAsDefault()
elif (not 'armory' in out.lower() or not 'armory.desktop' in out2.lower()) and not self.firstLoad:
# If another application has it, ask for permission to change it
# Don't bother the user on the first load with it if verification is
# needed. They have enough to worry about with this weird new program...
if not self.getSettingOrSetDefault('DNAA_DefaultApp', False):
reply = MsgBoxWithDNAA(MSGBOX.Question, 'Default URL Handler', \
'Armory is not set as your default application for handling '
'"protoshares:" links. Would you like to use Armory as the '
'default?', 'Do not ask this question again')
if reply[0]==True:
setAsDefault()
if reply[1]==True:
self.writeSetting('DNAA_DefaultApp', True)
elif OS_WINDOWS:
# Check for existing registration (user first, then root, if necessary)
action = 'DoNothing'
modulepathname = '"'
if getattr(sys, 'frozen', False):
app_dir = os.path.dirname(sys.executable)
app_path = os.path.join(app_dir, sys.executable)
elif __file__:
return #running from a .py script, not gonna register URI on Windows
modulepathname += app_path + '" %1'
LOGWARN("running from: %s, key: %s", app_path, modulepathname)
rootKey = 'protoshares\\shell\\open\\command'
try:
userKey = 'Software\\Classes\\' + rootKey
registryKey = OpenKey(HKEY_CURRENT_USER, userKey, 0, KEY_READ)
val,code = QueryValueEx(registryKey, '')
if 'armory' in val.lower():
if val.lower()==modulepathname.lower():
LOGINFO('Armory already registered for current user. Done!')
return
else:
action = 'DoIt' #armory is registered, but to another path
else:
# Already set to something (at least created, which is enough)
action = 'AskUser'
except:
# No user-key set, check if root-key is set
try:
registryKey = OpenKey(HKEY_CLASSES_ROOT, rootKey, 0, KEY_READ)
val,code = QueryValueEx(registryKey, '')
if 'armory' in val.lower():
LOGINFO('Armory already registered at admin level. Done!')
return
else:
# Root key is set (or at least created, which is enough)
action = 'AskUser'
except:
action = 'DoIt'
dontAsk = self.getSettingOrSetDefault('DNAA_DefaultApp', False)
dontAskDefault = self.getSettingOrSetDefault('AlwaysArmoryURI', False)
print dontAsk, justDoIt, dontAskDefault
if justDoIt:
LOGINFO('URL-register: just doing it')
action = 'DoIt'
elif dontAsk and dontAskDefault:
LOGINFO('URL-register: user wants to do it by default')
action = 'DoIt'
elif action=='AskUser' and not self.firstLoad and not dontAsk:
# If another application has it, ask for permission to change it
# Don't bother the user on the first load with it if verification is
# needed. They have enough to worry about with this weird new program...
reply = MsgBoxWithDNAA(MSGBOX.Question, 'Default URL Handler', \
'Armory is not set as your default application for handling '
'"protoshares:" links. Would you like to use Armory as the '
'default?', 'Do not ask this question again')
if reply[1]==True:
LOGINFO('URL-register: do not ask again: always %s', str(reply[0]))
self.writeSetting('DNAA_DefaultApp', True)
self.writeSetting('AlwaysArmoryURI', reply[0])
if reply[0]==True:
action = 'DoIt'
else:
LOGINFO('User requested not to use Armory as URI handler')
return
# Finally, do it if we're supposed to!
LOGINFO('URL-register action: %s', action)
if action=='DoIt':
LOGINFO('Registering Armory for current user')
baseDir = app_dir
regKeys = []
regKeys.append(['Software\\Classes\\protoshares', '', 'URL:protoshares Protocol'])
regKeys.append(['Software\\Classes\\protoshares', 'URL Protocol', ""])
regKeys.append(['Software\\Classes\\protoshares\\shell', '', None])
regKeys.append(['Software\\Classes\\protoshares\\shell\\open', '', None])
regKeys.append(['Software\\Classes\\protoshares\\shell\\open\\command', '', \