forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 174
/
armorymodels.py
executable file
·1571 lines (1296 loc) · 59.1 KB
/
armorymodels.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
##############################################################################
# #
# 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-2024, goatpig #
# Distributed under the MIT license #
# See LICENSE-MIT or https://opensource.org/licenses/MIT #
# #
##############################################################################
from os import path
import os
import platform
import sys
from copy import deepcopy
from qtpy import QtCore, QtGui, QtWidgets
from armoryengine.ArmoryUtils import enum, coin2str, binary_to_hex, \
int_to_hex, CPP_TXOUT_SCRIPT_NAMES, CPP_TXOUT_MULTISIG, \
CPP_TXIN_SCRIPT_NAMES, ADDRBYTE, P2SHBYTE
from armoryengine.UserAddressUtils import getDisplayStringForScriptImpl
from armoryengine.Transaction import UnsignedTransaction, \
getTxInScriptType
from armoryengine.MultiSigUtils import calcLockboxID
from armoryengine.Timer import TimeThisFunction
from armoryengine.BDM import TheBDM, BDM_BLOCKCHAIN_READY
from armoryengine.CppBridge import TheBridge
from armoryengine.AddressUtils import Hash160ToScrAddr, addrStr_to_hash160, \
scrAddr_to_addrStr
from armoryengine.Settings import TheSettings
from armorycolors import Colors
from qtdialogs.qtdefines import determineWalletType, WLTTYPES, \
GETFONT, CHANGE_ADDR_DESCR_STRING
from qtdialogs.ArmoryDialog import ArmoryDialog
WLTVIEWCOLS = enum('Visible', 'ID', 'Name', 'Secure', 'Bal')
LEDGERCOLS = enum('NumConf', 'UnixTime', 'DateStr', 'TxDir', 'WltName', 'Comment', \
'Amount', 'isOther', 'WltID', 'TxHash', 'isCoinbase', 'toSelf', \
'optInRBF', 'isChainedZC')
ADDRESSCOLS = enum('ChainIdx', 'Address', 'Comment', 'NumTx', 'Balance')
ADDRBOOKCOLS = enum('Address', 'WltID', 'NumSent', 'Comment')
TXINCOLS = enum('WltID', 'Sender', 'Btc', 'OutPt', 'OutIdx', 'FromBlk', \
'ScrType', 'Sequence', 'Script', 'AddrStr')
TXOUTCOLS = enum('WltID', 'Recip', 'Btc', 'ScrType', 'Script', 'AddrStr')
PROMCOLS = enum('PromID', 'Label', 'PayAmt', 'FeeAmt')
PAGE_LOAD_OFFSET = 10
################################################################################
class AllWalletsDispModel(QtCore.QAbstractTableModel):
# The columns enumeration
def __init__(self, mainWindow):
super(AllWalletsDispModel, self).__init__()
self.main = mainWindow
def rowCount(self, index=QtCore.QModelIndex()):
return len(self.main.walletMap)
def columnCount(self, index=QtCore.QModelIndex()):
return 5
def data(self, index, role=QtCore.Qt.DisplayRole):
bdmState = TheBDM.getState()
COL = WLTVIEWCOLS
row,col = index.row(), index.column()
wlt = self.main.walletMap[self.main.walletIDList[row]]
wltID = wlt.uniqueIDB58
if role==QtCore.Qt.DisplayRole:
if col==COL.Visible:
return self.main.walletVisibleList[row]
elif col==COL.ID:
return str(wltID)
elif col==COL.Name:
return str(wlt.labelName.ljust(32))
elif col==COL.Secure:
wtype,typestr = determineWalletType(wlt, self.main)
return str(typestr)
elif col==COL.Bal:
if not bdmState==BDM_BLOCKCHAIN_READY:
return str('(...)')
if wlt.isEnabled == True:
bal = wlt.getBalance('Total')
if bal==-1:
return str('(...)')
else:
dispStr = coin2str(bal, maxZeros=2)
return str(dispStr)
else:
dispStr = 'Scanning: %d%%' % (self.main.walletSideScanProgress[wltID])
return str(dispStr)
elif role==QtCore.Qt.TextAlignmentRole:
if col in (COL.ID, COL.Name):
return int(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
elif col in (COL.Secure,):
return int(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
elif col in (COL.Bal,):
if not bdmState==BDM_BLOCKCHAIN_READY:
return int(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
else:
return int(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
elif role==QtCore.Qt.BackgroundColorRole:
t = determineWalletType(wlt, self.main)[0]
if t==WLTTYPES.WatchOnly:
return Colors.TblWltOther
elif t==WLTTYPES.Offline:
return Colors.TblWltOffline
else:
return Colors.TblWltMine
elif role==QtCore.Qt.FontRole:
if col==COL.Bal:
return GETFONT('Fixed')
return None
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
colLabels = ['', self.tr('ID'), self.tr('Wallet Name'), self.tr('Security'), self.tr('Balance')]
if role==QtCore.Qt.DisplayRole:
if orientation==QtCore.Qt.Horizontal:
return colLabels[section]
elif role==QtCore.Qt.TextAlignmentRole:
return int(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
def flags(self, index, role=QtCore.Qt.DisplayRole):
if role == QtCore.Qt.DisplayRole:
wlt = self.main.walletMap[self.main.walletIDList[index.row()]]
rowFlag = QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable
if wlt.isEnabled is False:
return QtCore.Qt.ItemFlags()
return rowFlag
def reset(self):
self.beginResetModel()
self.endResetModel()
################################################################################
class AllWalletsCheckboxDelegate(QtWidgets.QStyledItemDelegate):
"""
Taken from http://stackoverflow.com/a/3366899/1610471
"""
EYESIZE = 20
def __init__(self, parent=None):
super(AllWalletsCheckboxDelegate, self).__init__(parent)
#############################################################################
def paint(self, painter, option, index):
bgcolor = QtGui.QPalette().color(
QtGui.QPalette.Active, QtGui.QPalette.Window)
if option.state & QtWidgets.QStyle.State_Selected:
bgcolor = QtWidgets.QApplication.palette().highlight().color()
if index.column() == WLTVIEWCOLS.Visible:
isVisible = index.model().data(index)
image=None
painter.fillRect(option.rect, bgcolor)
if isVisible:
image = QtGui.QImage('./img/visible2.png').scaled(self.EYESIZE,self.EYESIZE)
pixmap = QtGui.QPixmap.fromImage(image)
painter.drawPixmap(option.rect, pixmap)
else:
QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
#############################################################################
def sizeHint(self, option, index):
if index.column()==WLTVIEWCOLS.Visible:
return QtCore.QSize(self.EYESIZE,self.EYESIZE)
return QtWidgets.QStyledItemDelegate.sizeHint(self, option, index)
################################################################################
class TableEntry():
def __init__(self, rawData, id=-1, table=[]):
self.rawData = rawData
self.id = id
self.table = table
################################################################################
class LedgerDispModelSimple(QtCore.QAbstractTableModel):
""" Displays an Nx10 table of pre-formatted/processed ledger entries """
def __init__(self, ledgerTable, parent=None, main=None, isLboxModel=False):
super(LedgerDispModelSimple, self).__init__()
self.parent = parent
self.main = main
self.isLboxModel = isLboxModel
self.bottomPage = TableEntry(None, 1, [])
self.currentPage = TableEntry(None, 0, [])
self.topPage = TableEntry(None, -1, [])
self.getPageLedger = None
self.convertLedger = None
self.ledger = ledgerTable
self.ledgerDelegateId = None
def rowCount(self, index=QtCore.QModelIndex()):
return len(self.ledger)
def columnCount(self, index=QtCore.QModelIndex()):
return 13
def data(self, index, role=QtCore.Qt.DisplayRole):
COL = LEDGERCOLS
row,col = index.row(), index.column()
rowData = self.ledger[row]
nConf = rowData[LEDGERCOLS.NumConf]
wltID = rowData[LEDGERCOLS.WltID]
wlt = self.main.walletMap.get(wltID)
optInRBF = rowData[LEDGERCOLS.optInRBF]
isChainedZC = rowData[LEDGERCOLS.isChainedZC]
amount = float(rowData[LEDGERCOLS.Amount])
toSelf = rowData[LEDGERCOLS.toSelf]
flagged = (optInRBF) and amount < 0 or toSelf
highlighted = optInRBF or isChainedZC
if wlt:
wtype = determineWalletType(self.main.walletMap[wltID], self.main)[0]
else:
wtype = WLTTYPES.WatchOnly
if role==QtCore.Qt.DisplayRole:
return str(rowData[col])
elif role==QtCore.Qt.TextAlignmentRole:
if col in (COL.NumConf, COL.TxDir):
return int(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
elif col in (COL.Comment, COL.DateStr):
return int(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
elif col in (COL.Amount,):
return int(QtCore.Qt.AlignRight | QtCore.Qt.AlignVCenter)
elif role==QtCore.Qt.DecorationRole:
pass
elif role==QtCore.Qt.BackgroundColorRole:
if optInRBF is True:
if flagged:
return Colors.myRBF
else:
return Colors.optInRBF
elif isChainedZC is True:
return Colors.chainedZC
elif wtype==WLTTYPES.WatchOnly:
return Colors.TblWltOther
elif wtype==WLTTYPES.Offline:
return Colors.TblWltOffline
else:
return Colors.TblWltMine
elif role==QtCore.Qt.ForegroundRole:
if highlighted:
return Colors.HighlightFG
elif nConf < 2:
return Colors.TextNoConfirm
elif nConf <= 4:
return Colors.TextSomeConfirm
if col==COL.Amount:
toSelf = rowData[COL.toSelf]
if toSelf:
return Colors.Mid
amt = float(rowData[COL.Amount])
if amt>0: return Colors.TextGreen
elif amt<0: return Colors.TextRed
else: return Colors.Foreground
elif role==QtCore.Qt.FontRole:
if col==COL.Amount:
f = GETFONT('Fixed')
f.setWeight(QtGui.QFont.Bold)
return f
elif role==QtCore.Qt.ToolTipRole:
if col in (COL.NumConf, COL.DateStr):
nConf = rowData[COL.NumConf]
isCB = rowData[COL.isCoinbase]
isConfirmed = (nConf>119 if isCB else nConf>5)
if isConfirmed:
return self.tr('Transaction confirmed!\n(%d confirmations)' % nConf)
else:
tooltipStr = ''
if isCB:
tooltipStr = self.tr('%d/120 confirmations' & nConf)
tooltipStr += ( self.tr('\n\nThis is a "generation" transaction from\n'
'Bitcoin mining. These transactions take\n'
'120 confirmations (approximately one day)\n'
'before they are available to be spent.'))
elif flagged:
tooltipStr = self.tr("You have create this transaction as RBF (Replaceable By Fee).<br><br>"
"This means you have the opportunity to bump the fee on this transaction"
" if it fails to confirm quickly enough.<br><br>"
"To bump the fee, right click on the ledger entry and pick <u>\"Bump the fee\"</u>")
elif optInRBF:
tooltipStr = self.tr("This transaction has been RBF flagged (Replaceable By Fee)<br><br>"
"It means the network will accept and broadcast a double spend of"
" the underlying outputs as long as the double spend pays a higher fee.<br><br>"
"Do not consider a RBF transaction as a valid payment until it receives"
" at least 1 confirmation.")
elif isChainedZC:
tooltipStr = self.tr("This transaction spends ZC (zero confirmation) outputs<br><br>"
"Transactions built on top of yet to confirm transactions are at"
" risk of being invalidated for as long as the parent transaction"
" remains unconfirmed.<br><br>"
"It is recommended to wait for at least 1 confirmation before"
" accepting these as valid payment.")
else:
tooltipStr = self.tr('%d/6 confirmations' % rowData[COL.NumConf])
tooltipStr += self.tr( '\n\nFor small transactions, 2 or 3 '
'confirmations is usually acceptable. '
'For larger transactions, you should '
'wait for 6 confirmations before '
'trusting that the transaction is valid.')
return str(tooltipStr)
if col==COL.TxDir:
#toSelf = self.index(index.row(), COL.toSelf).data().toBool()
toSelf = rowData[COL.toSelf]
if toSelf:
return self.tr('Bitcoins sent and received by the same wallet')
else:
txdir = rowData[COL.TxDir]
if rowData[COL.isCoinbase]:
return self.tr('You mined these Bitcoins!')
if float(txdir.strip())<0:
return self.tr('Bitcoins sent')
else:
return self.tr('Bitcoins received')
if col==COL.Amount:
if TheSettings.get('DispRmFee'):
return self.tr('The net effect on the balance of this wallet '
'<b>not including transaction fees.</b> '
'You can change this behavior in the Armory '
'preferences window.')
else:
return self.tr('The net effect on the balance of this wallet, '
'including transaction fees.')
return None
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
COL = LEDGERCOLS
if role==QtCore.Qt.DisplayRole:
if orientation==QtCore.Qt.Horizontal:
if section==COL.NumConf: return None
if section==COL.DateStr: return str(self.tr('Date'))
if section==COL.WltName: return str(self.tr('Lockbox')) if self.isLboxModel else str(self.tr('Wallet'))
if section==COL.Comment: return str(self.tr('Comments'))
if section==COL.TxDir: return None
if section==COL.Amount: return str(self.tr('Amount'))
if section==COL.isOther: return str(self.tr('Other Owner'))
if section==COL.WltID: return str(self.tr('Wallet ID'))
if section==COL.TxHash: return str(self.tr('Tx Hash (LE)'))
elif role==QtCore.Qt.TextAlignmentRole:
return int(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
def setLedgerDelegateId(self, delegateId):
if len(delegateId) == 0:
raise Exception("empty delegate id")
self.ledgerDelegateId = delegateId
def setConvertLedgerMethod(self, method):
self.convertLedger = method
def getMoreData(self, atBottom):
#return 0 if self.ledger didn't change
if atBottom == True:
#Try to grab the next page. If it throws, there is no more data
#so we can simply return
try:
newLedger = TheBridge.getHistoryPageForDelegate(\
self.ledgerDelegateId, self.bottomPage.id +1)
toTable = self.convertLedger(newLedger)
except:
return 0
self.previousOffset = -len(self.topPage.table)
#get the length of the ledger we're not dumping
prevPageCount = len(self.currentPage.table) + \
len(self.bottomPage.table)
#Swap pages downwards
self.topPage = deepcopy(self.currentPage)
self.currentPage = deepcopy(self.bottomPage)
self.bottomPage.id += 1
self.bottomPage.table = toTable
#figure out the bottom of the previous view in
#relation with the new one
pageCount = prevPageCount + len(self.bottomPage.table)
if pageCount == 0:
ratio = 0
else:
ratio = float(prevPageCount) / float(pageCount)
else:
try:
newLedger = TheBridge.getHistoryPageForDelegate(\
self.delegateId, self.topPage.id -1)
toTable = self.convertLedger(newLedger)
except:
return 0
self.previousOffset = len(self.topPage.table)
prevPageCount = len(self.currentPage.table) + \
len(self.topPage.table)
self.bottomPage = deepcopy(self.currentPage)
self.currentPage = deepcopy(self.topPage)
self.topPage.rawData = newLedger
self.topPage.id -= 1
self.topPage.table = toTable
pageCount = prevPageCount + len(self.topPage.table)
ratio = 1 - float(prevPageCount) / float(pageCount)
#call reset, which will pull the missing ledgerTable from C++
self.reset()
return ratio
def reset(self, hard=False):
#if either top or current page is index 0, update it
#also if any of the pages has no ledger, pull and convert it
super(QtCore.QAbstractTableModel, self).beginResetModel()
if hard == True:
self.topPage.id = -1
self.topPage.table = []
self.currentPage.id = 0
self.currentPage.table = []
self.bottomPage.id = 1
self.bottomPage.table = []
if self.topPage.id == 0 or not self.topPage.table:
try:
self.topPage.rawData = TheBridge.service.getHistoryPageForDelegate(
self.ledgerDelegateId, self.topPage.id)
toTable = self.convertLedger(self.topPage.rawData)
self.topPage.table = toTable
except:
pass
if self.currentPage.id == 0 or not self.currentPage.table:
self.currentPage.rawData = TheBridge.service.getHistoryPageForDelegate(
self.ledgerDelegateId, self.currentPage.id)
toTable = self.convertLedger(self.currentPage.rawData)
self.currentPage.table = toTable
if not self.bottomPage.table:
try:
self.bottomPage.rawData = TheBridge.service.getHistoryPageForDelegate(
self.ledgerDelegateId, self.bottomPage.id)
toTable = self.convertLedger(self.bottomPage.rawData)
self.bottomPage.table = toTable
except:
pass
self.ledger = []
self.ledger.extend(self.topPage.table)
self.ledger.extend(self.currentPage.table)
self.ledger.extend(self.bottomPage.table)
super(QtCore.QAbstractTableModel, self).endResetModel()
def centerAtHeight(self, blk):
#return the index for that block height in the new ledger
centerId = self.ledgerDelegate.getPageIdForBlockHeight(blk)
self.bottomPage = TableEntry(centerId +1, [])
self.currentPage = TableEntry(centerId, [])
self.topPage = TableEntry(centerId -1, [])
self.reset()
blockDiff = 2**32
blockReturn = 0
for leID in range(0, len(self.ledger)):
block = TheBDM.getTopBlockHeight() - self.ledger[leID][0] -1
diff = abs(block - blk)
if blockDiff >= diff :
blockDiff = diff
blockReturn = leID
return blockReturn
def updateIndexComment(self, index, comment):
#this allows the code to update comments without the need
#to reload the entire model
row = index.row()
rowData = self.ledger[row]
rowData[LEDGERCOLS.Comment] = comment
def getRawDataEntry(self, filter):
def filterRawData(rawDataList, filter):
for rawData in rawDataList:
if filter(rawData):
return rawData
return None
if self.bottomPage.rawData:
result = filterRawData(self.bottomPage.rawData.ledger, filter)
if result:
return result
if self.currentPage.rawData:
result = filterRawData(self.currentPage.rawData.ledger, filter)
if result:
return result
if self.topPage.rawData:
result = filterRawData(self.topPage.rawData.ledger, filter)
if result:
return result
return None
################################################################################
class CalendarDialog(ArmoryDialog):
def __init__(self, parent, main):
super(CalendarDialog, self).__init__(parent, main)
self.parent = parent
self.main = main
self.calendarWidget = QCalendarWidget(self)
self.layout = QtWidgets.QGridLayout()
self.layout.addWidget(self.calendarWidget, 0, 0)
self.setLayout(self.layout)
self.adjustSize()
self.calendarWidget.selectionChanged.connect(self.accept)
################################################################################
class ArmoryBlockAndDateSelector(QtCore.QObject):
hideIt = QtCore.Signal()
def __init__(self, parent, main, controlFrame):
super(ArmoryBlockAndDateSelector, self).__init__()
self.parent = parent
self.main = main
self.ledgerDelegate = None
self.Height = 0
self.Width = 0
self.Block = 0
self.Date = 0
self.isExpanded = False
self.doHide = False
self.isEditingBlockHeight = False
self.frmBlockAndDate = QtWidgets.QFrame()
self.frmBlockAndDateLayout = QtWidgets.QGridLayout()
self.frmBlockAndDateLayout.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignBottom)
self.lblBlock = QtWidgets.QLabel(self.main.tr("<a href=edtBlock>Block:</a>"))
self.lblBlock.linkActivated.connect(self.linkClicked)
self.lblBlock.adjustSize()
self.lblBlockValue = QtWidgets.QLabel("")
self.lblBlockValue.adjustSize()
self.lblDate = QtWidgets.QLabel(self.main.tr("<a href=edtDate>Date:</a>"))
self.lblDate.linkActivated.connect(self.linkClicked)
self.lblDate.adjustSize()
self.lblDateValue = QtWidgets.QLabel("")
self.lblDateValue.adjustSize()
self.lblTop = QtWidgets.QLabel(self.main.tr("<a href=goToTop>Top</a>"))
self.lblTop.linkActivated.connect(self.goToTop)
self.lblTop.adjustSize()
self.calendarDlg = CalendarDialog(self.parent, self.main)
self.edtBlock = QtWidgets.QLineEdit()
edtFontMetrics = self.edtBlock.fontMetrics()
fontRect = edtFontMetrics.boundingRect("00000000")
self.edtBlock.setFixedWidth(fontRect.width())
self.edtBlock.setVisible(False)
self.edtBlock.editingFinished.connect(self.blkEditingFinished)
self.frmBlock = QtWidgets.QFrame()
self.frmBlockLayout = QtWidgets.QGridLayout()
self.frmBlockLayout.addWidget(self.lblBlock, 0, 0)
self.frmBlockLayout.addWidget(self.lblBlockValue, 0, 1)
self.frmBlockLayout.addWidget(self.edtBlock, 0, 1)
self.frmBlockLayout.addWidget(self.lblTop, 0, 2)
self.frmBlock.setLayout(self.frmBlockLayout)
self.frmBlock.adjustSize()
self.frmBlockAndDateLayout.addWidget(self.lblBlock, 0, 0)
self.frmBlockAndDateLayout.addWidget(self.lblBlockValue, 0, 1)
self.frmBlockAndDateLayout.addWidget(self.edtBlock, 0, 1)
self.frmBlockAndDateLayout.addWidget(self.lblTop, 0, 2)
self.frmBlockAndDateLayout.addWidget(self.lblDate, 1, 0)
self.frmBlockAndDateLayout.addWidget(self.lblDateValue, 1, 1)
self.frmBlockAndDate.setLayout(self.frmBlockAndDateLayout)
self.frmBlockAndDate.setBackgroundRole(QtGui.QPalette.Window)
self.frmBlockAndDate.setAutoFillBackground(True)
self.frmBlockAndDate.setFrameStyle(QtWidgets.QFrame.Panel | QtWidgets.QFrame.Raised)
self.frmBlockAndDate.setVisible(False)
self.frmBlockAndDate.setMouseTracking(True)
self.frmBlockAndDate.leaveEvent = self.triggerHideBlockAndDate
self.frmBlockAndDate.enterEvent = self.resetHideBlockAndDate
self.dateBlockSelectButton = QtWidgets.QPushButton('Goto')
self.dateBlockSelectButton.setStyleSheet('QtWidgets.QPushButton { font-size : 10px }')
self.dateBlockSelectButton.setMaximumSize(60, 20)
self.dateBlockSelectButton.clicked.connect(self.showBlockDateController)
self.frmLayout = QtWidgets.QGridLayout()
self.frmLayout.addWidget(self.dateBlockSelectButton)
self.frmLayout.addWidget(self.frmBlockAndDate)
self.frmLayout.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignTop)
self.frmLayout.setMargin(0)
self.hideIt.connect(self.hideBlockAndDate)
self.dateBlockSelectButton.setVisible(True)
controlFrame.setLayout(self.frmLayout)
def linkClicked(self, link):
if link == 'edtBlock':
self.editBlockHeight()
elif link == 'edtDate':
self.editDate()
def updateLabel(self, block):
self.Block = block
try:
self.Date = TheBridge.getBlockTimeByHeight(block)
datefmt = self.main.getPreferredDateFormat()
dateStr = unixTimeToFormatStr(self.Date, datefmt)
except:
dateStr = "N/A"
self.lblBlockValue.setText(str(block) )
self.lblBlockValue.adjustSize()
self.lblDateValue.setText(dateStr)
self.lblDateValue.adjustSize()
self.frmBlockAndDate.adjustSize()
if self.isExpanded == True:
fontRect = self.frmBlockAndDate.geometry()
else:
fontRect = self.dateBlockSelectButton.geometry()
self.Width = fontRect.width()
self.Height = fontRect.height()
def getLayoutSize(self):
return QtCore.QSize(self.Width, self.Height)
def pressEvent(self, mEvent):
if mEvent.button() == QtCore.Qt.LeftButton:
self.lblClicked()
def showBlockDateController(self):
self.isExpanded = True
self.dateBlockSelectButton.setVisible(False)
self.frmBlockAndDate.setVisible(True)
self.updateLabel(self.Block)
def prepareToHideThread(self):
self.doHide = True
time.sleep(1)
self.hiteIt.emit()
def triggerHideBlockAndDate(self, mEvent):
hideThread = PyBackgroundThread(self.prepareToHideThread)
hideThread.start()
def hideBlockAndDate(self):
if self.isExpanded == True and self.doHide == True:
self.frmBlockAndDate.setVisible(False)
self.dateBlockSelectButton.setVisible(True)
self.isExpanded = False
self.updateLabel(self.Block)
def resetHideBlockAndDate(self, mEvent):
self.doHide = False
def editBlockHeight(self):
if self.isEditingBlockHeight == False:
self.edtBlock.setText(self.lblBlockValue.text())
self.lblBlockValue.setVisible(False)
self.edtBlock.setVisible(True)
self.isEditingBlockHeight = True
self.frmBlockAndDate.adjustSize()
else:
self.lblBlockValue.setVisible(True)
self.edtBlock.setVisible(False)
self.isEditingBlockHeight = False
self.frmBlockAndDate.adjustSize()
def editDate(self):
if self.isEditingBlockHeight == True:
self.editBlockHeight()
if self.calendarDlg.exec_() == True:
self.dateChanged()
def blkEditingFinished(self):
try:
blk = int(self.edtBlock.text())
self.Block = self.ledgerDelegate.getBlockInVicinity(blk)
self.Date = TheBDM.bdv().getBlockTimeByHeight(self.Block)
except:
pass
self.editBlockHeight()
self.updateLabel(self.Block)
self.parent.emit(SIGNAL('centerView'), self.Block)
def dateChanged(self):
try:
ddate = self.calendarDlg.calendarWidget.selectedDate().toPyDate()
self.Date = int(time.mktime(ddate.timetuple()))
self.Block = TheBDM.bdv().getClosestBlockHeightForTime(self.Date)
except:
pass
self.updateLabel(self.Block)
self.parent.emit(SIGNAL('centerView'), self.Block)
def goToTop(self):
if self.isEditingBlockHeight == True:
self.editBlockHeight()
self.parent.emit(SIGNAL('goToTop'))
def hide(self):
self.dateBlockSelectButton.setVisible(False)
def show(self):
if self.isExpanded == False:
self.dateBlockSelectButton.setVisible(True)
################################################################################
class ArmoryTableView(QtWidgets.QTableView):
#centerViewSignal = QtCore.Signal()
#goToTopSignal = QtCore.Signal()
def __init__(self, parent, main, controlFrame):
super(ArmoryTableView, self).__init__(parent)
self.parent = parent
self.main = main
self.BlockAndDateSelector = ArmoryBlockAndDateSelector(self, self.main, controlFrame)
self.verticalScrollBar().rangeChanged.connect(self.scrollBarRangeChanged)
self.vBarRatio = 0
self.verticalScrollBar().setVisible(False)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.prevIndex = -1
#self.centerViewSignal.connect(self.centerViewAtBlock)
#self.goToTopSignal.connect(self.goToTop)
def verticalScrollbarValueChanged(self, dx):
if dx > self.verticalScrollBar().maximum() - PAGE_LOAD_OFFSET:
#at the bottom of the scroll area
ratio = self.ledgerModel.getMoreData(True)
if ratio != 0:
self.vBarRatio = ratio
elif dx < PAGE_LOAD_OFFSET:
#at the top of the scroll area
ratio = self.ledgerModel.getMoreData(False)
if ratio != 0:
self.vBarRatio = ratio
self.updateBlockAndDateLabel()
def setModel(self, model):
super(ArmoryTableView, self).setModel(model)
self.ledgerModel = model
if model is not None:
self.BlockAndDateSelector.ledgerDelegate = self.ledgerModel.ledgerDelegate
def scrollBarRangeChanged(self, rangeMin, rangeMax):
pos = int(self.vBarRatio * rangeMax)
self.verticalScrollBar().setValue(pos)
self.updateBlockAndDateLabel()
def selectionChanged(self, itemSelected, itemDeselected):
if itemSelected.last().bottom() +2 >= len(self.ledgerModel.ledger):
ratio = self.ledgerModel.getMoreData(True)
if ratio != 0:
self.vBarRatio = ratio
elif itemSelected.last().top() -2 <= 0:
ratio = self.ledgerModel.getMoreData(False)
if ratio != 0:
self.vBarRatio = ratio
super(ArmoryTableView, self).selectionChanged(itemSelected, itemDeselected)
self.updateBlockAndDateLabel()
def moveCursor(self, action, modifier):
self.prevIndex = self.currentIndex().row()
if action == QAbstractItemView.MoveUp:
if self.currentIndex().row() > 0:
return self.ledgerModel.index(self.currentIndex().row() -1, 0)
elif action == QAbstractItemView.MoveDown:
if self.currentIndex().row() < self.ledgerModel.rowCount() -1:
return self.ledgerModel.index(self.currentIndex().row() +1, 0)
return self.currentIndex()
def reset(self):
#save the previous selection
super(ArmoryTableView, self).reset()
if self.prevIndex != -1:
self.setCurrentIndex(\
self.ledgerModel.index(self.ledgerModel.previousOffset + self.prevIndex, 0))
self.updateBlockAndDateLabel()
def centerViewAtBlock(self, Blk):
itemIndex = self.ledgerModel.centerAtHeight(Blk)
self.vBarRatio = float(itemIndex) / float(self.ledgerModel.rowCount())
self.verticalScrollBar().setValue(\
self.vBarRatio * self.verticalScrollBar().maximum())
def updateBlockAndDateLabel(self):
try:
sbMax = self.verticalScrollBar().maximum()
if sbMax == 0:
self.BlockAndDateSelector.hide()
else:
self.BlockAndDateSelector.show()
ratio = float(self.verticalScrollBar().value()) \
/ float(self.verticalScrollBar().maximum())
leID = int(ratio * float(self.ledgerModel.rowCount()))
block = TheBDM.getTopBlockHeight() - self.ledgerModel.ledger[leID][0] +1
self.BlockAndDateSelector.updateLabel(block)
except:
pass
def goToTop(self):
self.ledgerModel.reset(True)
self.vBarRatio = 0
self.verticalScrollBar().setValue(0)
################################################################################
class LedgerDispSortProxy(QtCore.QSortFilterProxyModel):
"""
Acts as a proxy that re-maps indices to the table view so that data
appears sorted, without actually touching the model
"""
def lessThan(self, idxLeft, idxRight):
COL = LEDGERCOLS
thisCol = self.sortColumn()
def getDouble(idx, col):
return float(self.sourceModel().ledger[idx.row()][col])
def getInt(idx, col):
return int(self.sourceModel().ledger[idx.row()][col])
#LEDGERCOLS = enum('NumConf', 'UnixTime', 'DateStr', 'TxDir', 'WltName', 'Comment', \
#'Amount', 'isOther', 'WltID', 'TxHash', 'toSelf', 'DoubleSpend')
if thisCol==COL.NumConf:
lConf = getInt(idxLeft, COL.NumConf)
rConf = getInt(idxRight, COL.NumConf)
if lConf==rConf:
tLeft = getDouble(idxLeft, COL.UnixTime)
tRight = getDouble(idxRight, COL.UnixTime)
return (tLeft<tRight)
return (lConf>rConf)
if thisCol==COL.DateStr:
tLeft = getDouble(idxLeft, COL.UnixTime)
tRight = getDouble(idxRight, COL.UnixTime)
return (tLeft<tRight)
if thisCol==COL.Amount:
btcLeft = getDouble(idxLeft, COL.Amount)
btcRight = getDouble(idxRight, COL.Amount)
return (abs(btcLeft) < abs(btcRight))
else:
return super(LedgerDispSortProxy, self).lessThan(idxLeft, idxRight)
################################################################################
class LedgerDispDelegate(QtWidgets.QStyledItemDelegate):
COL = LEDGERCOLS
def __init__(self, parent=None):
super(LedgerDispDelegate, self).__init__(parent)
def paint(self, painter, option, index):
bgcolor = QtGui.QPalette().color(
QtGui.QPalette.Active, QtGui.QPalette.Window)
if option.state & QtWidgets.QStyle.State_Selected:
bgcolor = QtWidgets.QApplication.palette().highlight().color()
isCoinbase = False
if index.model().index(index.row(), self.COL.isCoinbase).data() == "True":
isCoinbase = True
toSelf = False
if index.model().index(index.row(), self.COL.toSelf).data() == "True":
toSelf = True
if index.column() == self.COL.NumConf:
nConf = int(index.model().data(index))
image=None
if isCoinbase:
if nConf<120:
effectiveNConf = int(6*float(nConf)/120.)
image = QtGui.QImage('./img/conf%dt_nonum.png'%effectiveNConf)
else:
image = QtGui.QImage('./img/conf6t.png')
else:
if nConf<6:
image = QtGui.QImage('./img/conf%dt.png'%nConf)
else:
image = QtGui.QImage('./img/conf6t.png')
painter.fillRect(option.rect, bgcolor)
pixmap = QtGui.QPixmap.fromImage(image)
#pixmap.scaled(70, 30, QtCore.Qt.KeepAspectRatio)
painter.drawPixmap(option.rect, pixmap)
elif index.column() == self.COL.TxDir:
# This is frustrating... QVariant doesn't support 64-bit ints
# So I have to pass the amt as string, then convert here to long
image = QtGui.QImage()
# isCoinbase still needs to be flagged in the C++ utils
if isCoinbase:
image = QtGui.QImage('./img/moneyCoinbase.png')
elif toSelf:
image = QtGui.QImage('./img/moneySelf.png')
else:
txdir = str(index.model().data(index)).strip()
if txdir[0].startswith('-'):
image = QtGui.QImage('./img/moneyOut.png')
else:
image = QtGui.QImage('./img/moneyIn.png')
painter.fillRect(option.rect, bgcolor)
pixmap = QtGui.QPixmap.fromImage(image)
#pixmap.scaled(70, 30, QtCore.Qt.KeepAspectRatio)
painter.drawPixmap(option.rect, pixmap)
else:
QtWidgets.QStyledItemDelegate.paint(self, painter, option, index)
def sizeHint(self, option, index):
if index.column()==self.COL.NumConf:
return QtCore.QSize(28,28)
elif index.column()==self.COL.TxDir:
return QtCore.QSize(28,28)
return QtWidgets.QStyledItemDelegate.sizeHint(self, option, index)
################################################################################
class WalletAddrDispModel(QtCore.QAbstractTableModel):
def __init__(self, wlt, mainWindow):
super(WalletAddrDispModel, self).__init__()
self.main = mainWindow
self.wlt = wlt
self.noChange = False
self.usedOnly = False
self.notEmpty = False
self.filterAddrList()