-
Notifications
You must be signed in to change notification settings - Fork 616
/
TxFrames.py
1861 lines (1565 loc) · 79.3 KB
/
TxFrames.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 #
# #
################################################################################
from PyQt4.Qt import * #@UnusedWildImport
from PyQt4.QtGui import * #@UnusedWildImport
from armoryengine.BDM import TheBDM, BDM_BLOCKCHAIN_READY
from qtdefines import * #@UnusedWildImport
from armoryengine.Transaction import UnsignedTransaction, getTxOutScriptType
from armoryengine.Script import convertScriptToOpStrings
from armoryengine.CoinSelection import PySelectCoins, calcMinSuggestedFees,\
calcMinSuggestedFeesHackMS, PyUnspentTxOut
from ui.WalletFrames import SelectWalletFrame, LockboxSelectFrame
from armoryengine.MultiSigUtils import \
calcLockboxID, readLockboxEntryStr, createLockboxEntryStr, isBareLockbox,\
isP2SHLockbox
from armoryengine.ArmoryUtils import MAX_COMMENT_LENGTH
class SendBitcoinsFrame(ArmoryFrame):
def __init__(self, parent, main, initLabel='',
wlt=None, prefill=None, wltIDList=None,
selectWltCallback = None, onlyOfflineWallets=False,
sendCallback = None, createUnsignedTxCallback = None,
spendFromLockboxID=None):
super(SendBitcoinsFrame, self).__init__(parent, main)
self.maxHeight = tightSizeNChar(GETFONT('var'), 1)[1] + 8
self.sourceAddrList = None
self.altBalance = None
self.wlt = wlt
self.wltID = wlt.uniqueIDB58 if wlt else None
self.wltIDList = wltIDList
self.selectWltCallback = selectWltCallback
self.sendCallback = sendCallback
self.createUnsignedTxCallback = createUnsignedTxCallback
self.lbox = self.main.getLockboxByID(spendFromLockboxID)
self.onlyOfflineWallets = onlyOfflineWallets
txFee = self.main.getSettingOrSetDefault('Default_Fee', MIN_TX_FEE)
self.widgetTable = []
self.scrollRecipArea = QScrollArea()
lblRecip = QRichLabel('<b>Enter Recipients:</b>')
lblRecip.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
self.freeOfErrors = True
feetip = self.main.createToolTipWidget(\
'Transaction fees go to users who contribute computing power to '
'keep the Bitcoin network secure, and in return they get your transaction '
'included in the blockchain faster. <b>Most transactions '
'do not require a fee</b> but it is recommended anyway '
'since it guarantees quick processing and helps the network.')
self.edtFeeAmt = QLineEdit()
self.edtFeeAmt.setFont(GETFONT('Fixed'))
self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0])
self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0])
self.edtFeeAmt.setMaximumHeight(self.maxHeight)
self.edtFeeAmt.setAlignment(Qt.AlignRight)
self.edtFeeAmt.setText(coin2str(txFee, maxZeros=1).strip())
# This used to be in the later, expert-only section, but some of these
# are actually getting referenced before being declared. So moved them
# up to here.
self.chkDefaultChangeAddr = QCheckBox('Use an existing address for change')
self.radioFeedback = QRadioButton('Send change to first input address')
self.radioSpecify = QRadioButton('Specify a change address')
self.lblChangeAddr = QRichLabel('Change:')
# Replaced with createAddressEntryWidgets
#self.edtChangeAddr = QLineEdit()
#self.btnChangeAddr = createAddrBookButton(parent, self.edtChangeAddr, \
#None, 'Send change to')
addrWidgets = self.main.createAddressEntryWidgets(self, maxDetectLen=36,
defaultWltID=self.wltID)
self.edtChangeAddr = addrWidgets['QLE_ADDR']
self.btnChangeAddr = addrWidgets['BTN_BOOK']
self.lblAutoDetect = addrWidgets['LBL_DETECT']
self.getUserChangeScript = addrWidgets['CALLBACK_GETSCRIPT']
self.chkRememberChng = QCheckBox('Remember for future transactions')
self.vertLine = VLINE()
self.ttipSendChange = self.main.createToolTipWidget(\
'Most transactions end up with oversized inputs and Armory will send '
'the change to the next address in this wallet. You may change this '
'behavior by checking this box.')
self.ttipFeedback = self.main.createToolTipWidget(\
'Guarantees that no new addresses will be created to receive '
'change. This reduces anonymity, but is useful if you '
'created this wallet solely for managing imported addresses, '
'and want to keep all funds within existing addresses.')
self.ttipSpecify = self.main.createToolTipWidget(\
'You can specify any valid Bitcoin address for the change. '
'<b>NOTE:</b> If the address you specify is not in this wallet, '
'Armory will not be able to distinguish the outputs when it shows '
'up in your ledger. The change will look like a second recipient, '
'and the total debit to your wallet will be equal to the amount '
'you sent to the recipient <b>plus</b> the change.')
self.ttipUnsigned = self.main.createToolTipWidget(\
'Check this box to create an unsigned transaction to be signed'
' and/or broadcast later.')
self.unsignedCheckbox = QCheckBox('Create Unsigned')
self.btnSend = QPushButton('Send!')
self.btnCancel = QPushButton('Cancel')
self.connect(self.btnCancel, SIGNAL(CLICKED), parent.reject)
# Created a standard wallet chooser frame. Pass the call back method
# for when the user selects a wallet.
if self.lbox is None:
coinControlCallback = self.coinControlUpdate if self.main.usermode == USERMODE.Expert else None
self.frmSelectedWlt = SelectWalletFrame(parent, main,
VERTICAL,
self.wltID,
wltIDList=self.wltIDList,
selectWltCallback=self.setWallet, \
coinControlCallback=coinControlCallback,
onlyOfflineWallets=self.onlyOfflineWallets)
else:
self.frmSelectedWlt = LockboxSelectFrame(parent, main,
VERTICAL,
self.lbox.uniqueIDB58)
# Only the Create Unsigned Transaction button if there is a callback for it.
# Otherwise the containing dialog or wizard will provide the offlien tx button
componentList = [ QLabel('Fee:'), self.edtFeeAmt, feetip, STRETCH]
if self.createUnsignedTxCallback:
self.connect(self.unsignedCheckbox, SIGNAL(CLICKED), self.unsignedCheckBoxUpdate)
componentList.append(self.unsignedCheckbox)
componentList.append(self.ttipUnsigned)
buttonList = [STRETCH]
buttonList.append(self.btnCancel)
# Only add the Send Button if there's a callback for it
# Otherwise the containing dialog or wizard will provide the send button
if self.sendCallback:
self.connect(self.btnSend, SIGNAL(CLICKED), self.createTxAndBroadcast)
buttonList.append(self.btnSend)
txFrm = makeHorizFrame(componentList, condenseMargins=True)
buttonFrame = makeHorizFrame(buttonList, condenseMargins=True)
btnEnterURI = QPushButton('Manually Enter "bitcoin:" Link')
ttipEnterURI = self.main.createToolTipWidget( tr("""
Armory does not always succeed at registering itself to handle
URL links from webpages and email.
Click this button to copy a "bitcoin:" link directly into Armory."""))
self.connect(btnEnterURI, SIGNAL("clicked()"), self.clickEnterURI)
fromFrameList = [self.frmSelectedWlt]
if not USE_TESTNET:
btnDonate = QPushButton("Donate to Armory Developers!")
ttipDonate = self.main.createToolTipWidget(\
'Making this software was a lot of work. You can give back '
'by adding a small donation to go to the Armory developers. '
'You will have the ability to change the donation amount '
'before finalizing the transaction.')
self.connect(btnDonate, SIGNAL("clicked()"), self.addDonation)
frmDonate = makeHorizFrame([btnDonate, ttipDonate], condenseMargins=True)
fromFrameList.append(frmDonate)
if not self.main.usermode == USERMODE.Standard:
frmEnterURI = makeHorizFrame([btnEnterURI, ttipEnterURI], condenseMargins=True)
fromFrameList.append(frmEnterURI)
########################################################################
# In Expert usermode, allow the user to modify source addresses
if self.main.usermode == USERMODE.Expert:
sendChangeToFrame = QFrame()
sendChangeToLayout = QGridLayout()
sendChangeToLayout.addWidget(self.lblChangeAddr, 0,0)
sendChangeToLayout.addWidget(self.edtChangeAddr, 0,1)
sendChangeToLayout.addWidget(self.btnChangeAddr, 0,2)
sendChangeToLayout.addWidget(self.lblAutoDetect, 1,1, 1,2)
sendChangeToLayout.setColumnStretch(0,0)
sendChangeToLayout.setColumnStretch(1,1)
sendChangeToLayout.setColumnStretch(2,0)
sendChangeToFrame.setLayout(sendChangeToLayout)
btngrp = QButtonGroup(self)
btngrp.addButton(self.radioFeedback)
btngrp.addButton(self.radioSpecify)
btngrp.setExclusive(True)
self.connect(self.chkDefaultChangeAddr, SIGNAL('toggled(bool)'), self.toggleChngAddr)
self.connect(self.radioSpecify, SIGNAL('toggled(bool)'), self.toggleSpecify)
frmChngLayout = QGridLayout()
i = 0;
frmChngLayout.addWidget(self.chkDefaultChangeAddr, i, 0, 1, 6)
frmChngLayout.addWidget(self.ttipSendChange, i, 6, 1, 2)
i += 1
frmChngLayout.addWidget(self.radioFeedback, i, 1, 1, 5)
frmChngLayout.addWidget(self.ttipFeedback, i, 6, 1, 2)
i += 1
frmChngLayout.addWidget(self.radioSpecify, i, 1, 1, 5)
frmChngLayout.addWidget(self.ttipSpecify, i, 6, 1, 2)
i += 1
frmChngLayout.addWidget(sendChangeToFrame, i, 1, 1, 6)
i += 1
frmChngLayout.addWidget(self.chkRememberChng, i, 1, 1, 7)
frmChngLayout.addWidget(self.vertLine, 1, 0, i - 1, 1)
frmChngLayout.setColumnStretch(0,1)
frmChngLayout.setColumnStretch(1,1)
frmChngLayout.setColumnStretch(2,1)
frmChngLayout.setColumnStretch(3,1)
frmChngLayout.setColumnStretch(4,1)
frmChngLayout.setColumnStretch(5,1)
frmChngLayout.setColumnStretch(6,1)
frmChangeAddr = QFrame()
frmChangeAddr.setLayout(frmChngLayout)
frmChangeAddr.setFrameStyle(STYLE_SUNKEN)
fromFrameList.append('Stretch')
fromFrameList.append(frmChangeAddr)
else:
fromFrameList.append('Stretch')
frmBottomLeft = makeVertFrame(fromFrameList, STYLE_RAISED, condenseMargins=True)
lblSend = QRichLabel('<b>Sending from Wallet:</b>')
lblSend.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
leftFrame = makeVertFrame([lblSend, frmBottomLeft], condenseMargins=True)
rightFrame = makeVertFrame([lblRecip, self.scrollRecipArea, txFrm, buttonFrame], condenseMargins=True)
layout = QHBoxLayout()
layout.addWidget(leftFrame, 0)
layout.addWidget(rightFrame, 1)
layout.setContentsMargins(0,0,0,0)
layout.setSpacing(0)
self.setLayout(layout)
self.makeRecipFrame(1)
self.setWindowTitle('Send Bitcoins')
self.setMinimumHeight(self.maxHeight * 20)
# self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
loadCount = self.main.settings.get('Load_Count')
alreadyDonated = self.main.getSettingOrSetDefault('DonateAlready', False)
lastPestering = self.main.getSettingOrSetDefault('DonateLastPester', 0)
donateFreq = self.main.getSettingOrSetDefault('DonateFreq', 20)
dnaaDonate = self.main.getSettingOrSetDefault('DonateDNAA', False)
if prefill:
amount = prefill.get('amount','')
message = prefill.get('message','')
label = prefill.get('label','')
if prefill.get('lockbox',''):
plainStr = createLockboxEntryStr(prefill.get('lockbox',''))
self.addOneRecipient(None, amount, message, None, plainStr)
else:
atype, addr160 = addrStr_to_hash160(prefill.get('address',''))
self.addOneRecipient(addr160, amount, message, label)
elif not self.main == None and \
loadCount % donateFreq == (donateFreq-1) and \
not loadCount == lastPestering and \
not dnaaDonate and \
not USE_TESTNET:
result = MsgBoxWithDNAA(self, self.main, MSGBOX.Question, 'Please donate!', tr("""
<i>Armory</i> is the result of thousands of hours of development
by very talented coders. Yet, this software
has been given to you for free to benefit the greater Bitcoin
community!
<br><br>
If you are satisfied with this software, please consider
donating what you think this software would be worth as a commercial
application.
<br><br><b>Are you willing to donate to the Armory developers?</b> If you
select "Yes," a donation field will be added to your
next transaction. You will have the opportunity to remove it or change
the amount before sending the transaction."""), None)
self.main.writeSetting('DonateLastPester', loadCount)
if result[0] == True:
self.addDonation()
self.makeRecipFrame(2)
if result[1] == True:
self.main.writeSetting('DonateDNAA', True)
if self.lbox:
self.toggleSpecify(False)
self.toggleChngAddr(False)
hexgeom = self.main.settings.get('SendBtcGeometry')
if len(hexgeom) > 0:
geom = QByteArray.fromHex(hexgeom)
self.restoreGeometry(geom)
# Use this to fire wallet change after the constructor is complete.
# if it's called during construction then self's container may not exist yet.
def fireWalletChange(self):
# Set the wallet in the wallet selector and let all of display components
# react to it. This is at the end so that we can be sure that all of the
# components that react to setting the wallet exist.
if self.lbox:
self.unsignedCheckbox.setChecked(True)
self.unsignedCheckbox.setEnabled(False)
else:
self.frmSelectedWlt.updateOnWalletChange()
self.unsignedCheckBoxUpdate()
#############################################################################
def unsignedCheckBoxUpdate(self):
if self.unsignedCheckbox.isChecked():
self.btnSend.setText('Continue')
self.btnSend.setToolTip('Click to create an unsigned transaction!')
else:
self.btnSend.setText('Send!')
self.btnSend.setToolTip('Click to send bitcoins!')
#############################################################################
def addOneRecipient(self, addr160, amt, msg, label=None, plainText=None):
"""
plainText arg can be used, and will override addr160. It is for
injecting either fancy script types, or special keywords into the
address field, such as a lockbox ID
"""
if label is not None:
self.wlt.setComment(addr160, label)
lastIsEmpty = True
for widg in ['QLE_ADDR', 'QLE_AMT', 'QLE_COMM']:
if len(str(self.widgetTable[-1][widg].text())) > 0:
lastIsEmpty = False
if not lastIsEmpty:
self.makeRecipFrame(len(self.widgetTable) + 1)
if amt:
amt = coin2str(amt, maxZeros=2).strip()
if plainText is None:
plainText = hash160_to_addrStr(addr160)
self.widgetTable[-1]['QLE_ADDR'].setText(plainText)
self.widgetTable[-1]['QLE_ADDR'].setCursorPosition(0)
self.widgetTable[-1]['QLE_AMT'].setText(amt)
self.widgetTable[-1]['QLE_AMT'].setCursorPosition(0)
self.widgetTable[-1]['QLE_COMM'].setText(msg)
self.widgetTable[-1]['QLE_COMM'].setCursorPosition(0)
#############################################################################
# Now that the wallet can change in the context of the send dialog, this
# method is used as a callback for when the wallet changes
# isDoubleClick is unused - do not accept or close dialog on double click
def setWallet(self, wlt, isDoubleClick=False):
self.wlt = wlt
self.wltID = wlt.uniqueIDB58 if wlt else None
if not TheBDM.getState() == BDM_BLOCKCHAIN_READY:
self.lblSummaryBal.setText('(available when online)', color='DisableFG')
if self.main.usermode == USERMODE.Expert:
# Pre-set values based on settings
chngBehave = self.main.getWltSetting(self.wltID, 'ChangeBehavior')
chngAddr = self.main.getWltSetting(self.wltID, 'ChangeAddr')
if chngBehave == 'Feedback':
self.chkDefaultChangeAddr.setChecked(True)
self.radioFeedback.setChecked(True)
self.radioSpecify.setChecked(False)
self.toggleChngAddr(True)
self.chkRememberChng.setChecked(True)
elif chngBehave == 'Specify':
self.chkDefaultChangeAddr.setChecked(True)
self.radioFeedback.setChecked(False)
self.radioSpecify.setChecked(True)
self.toggleChngAddr(True)
if checkAddrStrValid(chngAddr):
self.edtChangeAddr.setText(chngAddr)
self.edtChangeAddr.setCursorPosition(0)
self.chkRememberChng.setChecked(True)
else:
# Other option is "NewAddr" but in case there's an error, should run
# this branch by default
self.chkDefaultChangeAddr.setChecked(False)
self.radioFeedback.setChecked(False)
self.radioSpecify.setChecked(False)
self.toggleChngAddr(False)
if (self.chkDefaultChangeAddr.isChecked() and \
not self.radioFeedback.isChecked() and \
not self.radioSpecify.isChecked()):
self.radioFeedback.setChecked(True)
# If there is a unsigned then we have a send button and unsigned checkbox to update
if self.createUnsignedTxCallback:
self.unsignedCheckbox.setChecked(wlt.watchingOnly)
self.unsignedCheckbox.setEnabled(not wlt.watchingOnly)
self.unsignedCheckBoxUpdate()
if self.selectWltCallback:
self.selectWltCallback(wlt)
#############################################################################
# Update the available source address list and balance based on results from
# coin control. This callback is now necessary because coin control was moved
# to the Select Wallet Frame
def coinControlUpdate(self, sourceAddrList, altBalance):
self.sourceAddrList = sourceAddrList
self.altBalance = altBalance
#############################################################################
def validateInputsGetUSTX(self):
self.freeOfErrors = True
scripts = []
addrList = []
self.comments = []
isSendToNonStandardLockbox = False
for row in range(len(self.widgetTable)):
# Verify validity of address strings
addrStr = str(self.widgetTable[row]['QLE_ADDR'].text()).strip()
self.widgetTable[row]['QLE_ADDR'].setText(addrStr) # overwrite w/ stripped
addrIsValid = True
addrList.append(addrStr)
try:
enteredScript = self.widgetTable[row]['FUNC_GETSCRIPT']()['Script']
if not enteredScript:
addrIsValid = False
else:
scripts.append(enteredScript)
except:
LOGEXCEPT('Failed to parse entered address: %s', addrStr)
addrIsValid = False
if not addrIsValid:
scripts.append('')
self.freeOfErrors = False
self.updateAddrColor(row, Colors.SlightRed)
numChkFail = sum([1 if len(b)==0 else 0 for b in scripts])
if not self.freeOfErrors:
QMessageBox.critical(self, tr('Invalid Address'),
tr("You have entered an invalid address. The error has been highlighted on the entrry screen.",
"You have entered %d invalid addresses. The errors have been highlighted on the entry screen", numChkFail), QMessageBox.Ok)
for row in range(len(self.widgetTable)):
try:
atype, a160 = addrStr_to_hash160(addrList[row])
if atype == -1 or not atype in [ADDRBYTE,P2SHBYTE]:
net = 'Unknown Network'
if NETWORKS.has_key(addrList[row][0]):
net = NETWORKS[addrList[row][0]]
QMessageBox.warning(self, tr('Wrong Network!'), tr("""
Address %d is for the wrong network! You are on the <b>%s</b>
and the address you supplied is for the the <b>%s</b>!""") % \
(row+1, NETWORKS[ADDRBYTE], net), QMessageBox.Ok)
except:
pass
return False
# Construct recipValuePairs and check that all metrics check out
scriptValPairs = []
totalSend = 0
for row in range(len(self.widgetTable)):
try:
recipStr = str(self.widgetTable[row]['QLE_ADDR'].text()).strip()
valueStr = str(self.widgetTable[row]['QLE_AMT'].text()).strip()
value = str2coin(valueStr, negAllowed=False)
if value == 0:
QMessageBox.critical(self, 'Zero Amount', \
'You cannot send 0 BTC to any recipients. <br>Please enter '
'a positive amount for recipient %d.' % (row+1), QMessageBox.Ok)
return False
except NegativeValueError:
QMessageBox.critical(self, 'Negative Value', \
'You have specified a negative amount for recipient %d. <br>Only '
'positive values are allowed!.' % (row + 1), QMessageBox.Ok)
return False
except TooMuchPrecisionError:
QMessageBox.critical(self, 'Too much precision', \
'Bitcoins can only be specified down to 8 decimal places. '
'The smallest value that can be sent is 0.0000 0001 BTC. '
'Please enter a new amount for recipient %d.' % (row + 1), QMessageBox.Ok)
return False
except ValueError:
QMessageBox.critical(self, 'Missing recipient amount', \
'You did not specify an amount to send!', QMessageBox.Ok)
return False
except:
QMessageBox.critical(self, 'Invalid Value String', \
'The amount you specified '
'to send to address %d is invalid (%s).' % (row + 1, valueStr), QMessageBox.Ok)
LOGERROR('Invalid amount specified: "%s"', valueStr)
return False
totalSend += value
script = self.widgetTable[row]['FUNC_GETSCRIPT']()['Script']
#scraddr = script_to_scrAddr(script)
# Checking for sending bitcoins to a Lockbox using P2SH that is
# non-standard to spend.
# only P2SH matters, if it's a bare multi sig, you won't be able to
# deposit if it's non-standard. In other words if it standard to spend from
# a bare sig lockbox it's standard to deposit into it.
# This is not necessarily so for P2SH. Must warn the user or else they
# may get some bitcoins stuck in a lockbox until they upgrade to bitcoin
# 0.10.0
if isP2SHLockbox(recipStr):
lbox = self.main.getLockboxByID(readLockboxEntryStr(recipStr))
if isMofNNonStandardToSpend(lbox.M, lbox.N):
reply = QMessageBox.warning(self, tr('Non-Standard to Spend'), tr("""
Due to the Lockbox size (%d-of-%d) of recipient %d, spending
funds from this Lockbox is valid but non-standard for versions
of Bitcoin prior to 0.10.0. This means if your version of
Bitcoin is 0.9.x or below, and you try to broadcast a
transaction that spends from this Lockbox the transaction
will not be accepted. If you have version 0.10.0, but all
of your peers have an older version your transaction will
not be forwarded to the rest of the network. If you deposit
Bitcoins into this Lockbox you may have to wait until you
and at least some of your peers have upgraded to 0.10.0
before those Bitcoins can be spent. Alternatively, if you
have enough computing power to mine your own transactions,
or know someone who does, you can arrange to have any valid
but non-standard transaction included in the block chain.""") % \
(lbox.M, lbox.N, row+1), QMessageBox.Ok | QMessageBox.Cancel)
if not reply==QMessageBox.Ok:
return
scriptValPairs.append([script, value])
self.comments.append((str(self.widgetTable[row]['QLE_COMM'].text()), value))
try:
feeStr = str(self.edtFeeAmt.text())
fee = str2coin(feeStr, negAllowed=False)
except NegativeValueError:
QMessageBox.critical(self, tr('Negative Value'), tr("""
You must enter a positive value for the fee."""), QMessageBox.Ok)
return False
except TooMuchPrecisionError:
QMessageBox.critical(self, tr('Too much precision'), tr("""
Bitcoins can only be specified down to 8 decimal places.
The smallest unit of a Bitcoin is 0.0000 0001 BTC.
Please enter a fee of at least 0.0000 0001"""), QMessageBox.Ok)
return False
except:
QMessageBox.critical(self, tr('Invalid Fee String'), tr("""
The fee you specified is invalid. A standard fee is
0.0001 BTC, though some transactions may succeed with
zero fee."""), QMessageBox.Ok)
LOGERROR(tr('Invalid fee specified: "%s"') % feeStr)
return False
bal = self.getUsableBalance()
if totalSend + fee > bal:
valTry = coin2str(totalSend + fee, maxZeros=2).strip()
valMax = coin2str(bal, maxZeros=2).strip()
if self.altBalance == None:
QMessageBox.critical(self, tr('Insufficient Funds'), tr("""
You just tried to send more Bitcoins than you have available. You only
have %s BTC (spendable) in this wallet!""") % \
valMax, QMessageBox.Ok)
else:
QMessageBox.critical(self, tr('Insufficient Funds'), tr("""
You just tried to send more Bitcoins than you have available. You only
have %s BTC with this coin control selection!""") % \
valMax, QMessageBox.Ok)
return False
# Iteratively calculate the minimum fee by first trying the user selected
# fee then on each iteration set the feeTry to the minFee, and see if the
# new feeTry can cover the original amount plus the new minfee. This loop
# will rarely iterate. It will only iterate when there is enough dust in
# utxoList so that each fee increase causes enough dust to be used to
# increase the fee yet again. Also, for the loop to iterate, the
# totalSend + fee must be close to the bal, but not go over when the min
# fee is increased If it does go over, it will exit the loop on the
# last condition,and give the user an insufficient balance warning.
minFee = None
utxoSelect = []
feeTry = fee
while minFee is None or (feeTry < minFee and totalSend + minFee <= bal):
if minFee:
feeTry = minFee
utxoList = self.getUsableTxOutList(totalSend)
utxoSelect = PySelectCoins(utxoList, totalSend, feeTry)
if self.lbox is None:
minFee = calcMinSuggestedFees(utxoSelect, totalSend, feeTry, \
len(scriptValPairs))[1]
else:
minFee = calcMinSuggestedFeesHackMS(utxoSelect, totalSend, feeTry, \
len(scriptValPairs))[1]
if minFee > 99*MIN_RELAY_TX_FEE:
QMessageBox.critical(self, tr('Minimum Transaction Fee Is Too Large'), tr("""
The minimum fee for this transaction is <b>%s BTC</b>. That fee is too
large and indicates that there are probably too many small inputs to fit
into a single transaction. To send these Bitcoins, this transaction must
be broken up into to smaller pieces.
""") % coin2strNZS(minFee), QMessageBox.Ok)
return False
# We now have a min-fee that we know we can match if the user agrees
if fee < minFee:
usrFeeStr = coin2strNZS(fee)
minFeeStr = coin2strNZS(minFee)
newBalStr = coin2strNZS(bal - minFee)
if totalSend + minFee > bal:
# Need to adjust this based on overrideMin flag
self.edtFeeAmt.setText(coin2str(minFee, maxZeros=1).strip())
QMessageBox.warning(self, tr('Insufficient Balance'), tr("""
The required transaction fee causes this transaction to exceed
your balance. In order to send this transaction, you will be
required to pay a fee of <b>%s BTC</b>.
<br><br>
Please go back and adjust the value of your transaction, not
to exceed a total of <b>%s BTC</b> (the necessary fee has
been entered into the form, so you can use the "MAX" button
to enter the remaining balance for a recipient).""") % \
(minFeeStr, newBalStr), QMessageBox.Ok)
return
reply = QMessageBox.warning(self, tr('Insufficient Fee'), tr("""
The fee you have specified (%s BTC) is insufficient for the
size and priority of your transaction. You must include at
least %s BTC to send this transaction.
<br><br>
Do you agree to the fee of %s BTC?""") % \
(usrFeeStr, minFeeStr, minFeeStr), \
QMessageBox.Yes | QMessageBox.Cancel)
if reply == QMessageBox.Cancel:
return False
if reply == QMessageBox.No:
pass
elif reply == QMessageBox.Yes:
fee = long(minFee)
# Warn user of excessive fee specified
if fee > 100*MIN_RELAY_TX_FEE or (minFee > 0 and fee > 10*minFee):
reply = QMessageBox.warning(self, tr('Excessive Fee'), tr("""
You have specified a fee of <b>%s BTC</b> which is much higher
than the minimum fee required for this transaction: <b>%s BTC</b>.
Are you <i>absolutely sure</i> that you want to send with this
fee?
<br><br>
If you do not want this fee, click "No" and then change the fee
at the bottom of the "Send Bitcoins" window before trying
again.""") % (coin2strNZS(fee), coin2strNZS(minFee)), QMessageBox.Yes | QMessageBox.No)
if not reply==QMessageBox.Yes:
return False
if len(utxoSelect) == 0:
QMessageBox.critical(self, tr('Coin Selection Error'), tr("""
There was an error constructing your transaction, due to a
quirk in the way Bitcoin transactions work. If you see this
error more than once, try sending your BTC in two or more
separate transactions."""), QMessageBox.Ok)
return False
# ## IF we got here, everything is good to go...
# Just need to get a change address and then construct the tx
totalTxSelect = sum([u.getValue() for u in utxoSelect])
totalChange = totalTxSelect - (totalSend + fee)
self.changeScript = ''
self.selectedBehavior = ''
if totalChange > 0:
script,behavior = self.determineChangeScript(utxoSelect)
self.changeScript = script
self.selectedBehavior = behavior
scriptValPairs.append([self.changeScript, totalChange])
LOGINFO('Change address behavior: %s', self.selectedBehavior)
else:
self.selectedBehavior = NO_CHANGE
changePair = None
if len(self.selectedBehavior) > 0:
changePair = (self.changeScript, self.selectedBehavior)
# Keep a copy of the originally-sorted list for display
origSVPairs = scriptValPairs[:]
# Anonymize the outputs
random.shuffle(scriptValPairs)
# In order to create the USTXI objects, need to make we supply a
# map of public keys that can be included
if self.lbox:
p2shMap = {binary_to_hex(script_to_scrAddr(script_to_p2sh_script(
self.lbox.binScript))) : self.lbox.binScript}
ustx = UnsignedTransaction().createFromTxOutSelection( \
utxoSelect, scriptValPairs,
p2shMap = p2shMap)
for i in range(len(ustx.ustxInputs)):
ustx.ustxInputs[i].contribID = self.lbox.uniqueIDB58
for i in range(len(ustx.decorTxOuts)):
if ustx.decorTxOuts[i].binScript == self.lbox.binScript:
ustx.decorTxOuts[i].contribID = self.lbox.uniqueIDB58
else:
# If this has nothing to do with lockboxes, we need to make sure
# we're providing a key map for the inputs
pubKeyMap = {}
for utxo in utxoSelect:
scrType = getTxOutScriptType(utxo.getScript())
if scrType in CPP_TXOUT_STDSINGLESIG:
scrAddr = utxo.getRecipientScrAddr()
a160 = scrAddr_to_hash160(scrAddr)[1]
addrObj = self.wlt.getAddrByHash160(a160)
if addrObj:
pubKeyMap[scrAddr] = addrObj.binPublicKey65.toBinStr()
# Now create the unsigned USTX
ustx = UnsignedTransaction().createFromTxOutSelection( \
utxoSelect, scriptValPairs, pubKeyMap)
#ustx.pprint()
txValues = [totalSend, fee, totalChange]
if not self.unsignedCheckbox.isChecked():
dlg = DlgConfirmSend(self.wlt, origSVPairs, txValues[1], self, \
self.main, True, ustx)
if not dlg.exec_():
return False
else:
self.main.warnNewUSTXFormat()
return ustx
def createTxAndBroadcast(self):
# The Send! button is clicked validate and broadcast tx
ustx = self.validateInputsGetUSTX()
if ustx:
if self.createUnsignedTxCallback and self.unsignedCheckbox.isChecked():
self.createUnsignedTxCallback(ustx)
else:
try:
if self.wlt.isLocked:
Passphrase = None
unlockdlg = DlgUnlockWallet(self.wlt, self, self.main, 'Send Transaction', returnPassphrase=True)
if unlockdlg.exec_():
if unlockdlg.Accepted == 1:
Passphrase = unlockdlg.securePassphrase.copy()
unlockdlg.securePassphrase.destroy()
if Passphrase is None or self.wlt.kdf is None:
QMessageBox.critical(self.parent(), 'Wallet is Locked', \
'Cannot sign transaction while your wallet is locked. ', \
QMessageBox.Ok)
return
else:
self.wlt.kdfKey = self.wlt.kdf.DeriveKey(Passphrase)
Passphrase.destroy()
self.wlt.mainWnd = self.main
self.wlt.parent = self
commentStr = ''
if len(self.comments) == 1:
commentStr = self.comments[0][0]
else:
for i in range(len(self.comments)):
amt = self.comments[i][1]
if len(self.comments[i][0].strip()) > 0:
commentStr += '%s (%s); ' % (self.comments[i][0], coin2str_approx(amt).strip())
ustxSigned = self.wlt.signUnsignedTx(ustx)
finalTx = ustxSigned.getSignedPyTx()
if len(commentStr) > 0:
self.wlt.setComment(finalTx.getHash(), commentStr)
self.main.broadcastTransaction(finalTx)
except:
LOGEXCEPT('Problem sending transaction!')
# TODO: not sure what errors to catch here, yet...
raise
if self.sendCallback:
self.sendCallback()
#############################################################################
def getUsableBalance(self):
if self.lbox is None:
if self.altBalance == None:
return self.wlt.getBalance('Spendable')
else:
return self.altBalance
else:
lbID = self.lbox.uniqueIDB58
cppWlt = self.main.cppLockboxWltMap.get(lbID)
if cppWlt is None:
LOGERROR('Somehow failed to get cppWlt for lockbox: %s', lbID)
return cppWlt.getSpendableBalance(TheBDM.getTopBlockHeight(), IGNOREZC)
#############################################################################
def getUsableTxOutList(self, totalSend):
if self.lbox is None:
if self.altBalance is None:
return list(self.wlt.getUTXOListForSpendVal(totalSend))
else:
utxoList = []
for a160 in self.sourceAddrList:
# Trying to avoid a swig bug involving iteration over vector<> types
cppAddr = self.wlt.getCppAddr(a160)
utxos = cppAddr.getSpendableTxOutList(IGNOREZC)
for i in range(len(utxos)):
utxoList.append(PyUnspentTxOut().createFromCppUtxo(utxos[i]))
return utxoList
else:
lbID = self.lbox.uniqueIDB58
cppWlt = self.main.cppLockboxWltMap.get(lbID)
if cppWlt is None:
LOGERROR('Somehow failed to get cppWlt for lockbox: %s', lbID)
txoList = cppWlt.getSpendableTxOutListForValue(totalSend, IGNOREZC)
pyUtxoList = []
for i in range(len(txoList)):
pyUtxo = PyUnspentTxOut().createFromCppUtxo(txoList[i])
pyUtxoList.append(pyUtxo)
return pyUtxoList
#############################################################################
def determineChangeScript(self, utxoList):
changeScript = ''
changeAddrStr = ''
changeAddr160 = ''
selectedBehavior = 'NewAddr' if self.lbox is None else 'Feedback'
if not self.main.usermode == USERMODE.Expert or \
not self.chkDefaultChangeAddr.isChecked():
# Default behavior for regular wallets is 'NewAddr', but for lockboxes
# the default behavior is "Feedback" (send back to the original addr
if self.lbox is None:
changeAddrStr = self.wlt.getNextUnusedAddress().getAddrStr()
changeAddr160 = addrStr_to_hash160(changeAddrStr)[1]
changeScript = scrAddr_to_script(addrStr_to_scrAddr(changeAddrStr))
self.wlt.setComment(changeAddr160, CHANGE_ADDR_DESCR_STRING)
else:
changeScript = script_to_p2sh_script(self.lbox.binScript)
if self.main.usermode == USERMODE.Expert:
if not self.chkDefaultChangeAddr.isChecked():
self.main.setWltSetting(self.wltID, 'ChangeBehavior', selectedBehavior)
else:
if self.radioFeedback.isChecked():
selectedBehavior = 'Feedback'
changeScript = utxoList[0].getScript()
elif self.radioSpecify.isChecked():
selectedBehavior = 'Specify'
changeScript = self.getUserChangeScript()['Script']
if changeScript is None:
QMessageBox.warning(self, tr('Invalid Address'), tr("""
You specified an invalid change address for this
transcation."""), QMessageBox.Ok)
return None
scrType = getTxOutScriptType(changeScript)
if scrType in CPP_TXOUT_HAS_ADDRSTR:
changeAddrStr = script_to_addrStr(changeScript)
elif scrType==CPP_TXOUT_MULTISIG:
scrP2SH = script_to_p2sh_script(changeScript)
changeAddrStr = script_to_addrStr(scrP2SH)
if self.main.usermode == USERMODE.Expert and self.chkRememberChng.isChecked():
self.main.setWltSetting(self.wltID, 'ChangeBehavior', selectedBehavior)
if selectedBehavior == 'Specify' and len(changeAddrStr) > 0:
self.main.setWltSetting(self.wltID, 'ChangeAddr', changeAddrStr)
else:
self.main.setWltSetting(self.wltID, 'ChangeBehavior', 'NewAddr')
return changeScript,selectedBehavior
#####################################################################
def setMaximum(self, targWidget):
nRecip = len(self.widgetTable)
totalOther = 0
r = 0
try:
bal = self.getUsableBalance()
txFee = str2coin(str(self.edtFeeAmt.text()))
while r < nRecip:
# Use while loop so 'r' is still in scope in the except-clause
if targWidget == self.widgetTable[r]['QLE_AMT']:
r += 1
continue
amtStr = str(self.widgetTable[r]['QLE_AMT'].text()).strip()
if len(amtStr) > 0:
totalOther += str2coin(amtStr)
r += 1
except:
QMessageBox.warning(self, 'Invalid Input', \
'Cannot compute the maximum amount '
'because there is an error in the amount '
'for recipient %d.' % (r + 1,), QMessageBox.Ok)
return
maxStr = coin2str((bal - (txFee + totalOther)), maxZeros=0)
if bal < txFee + totalOther:
QMessageBox.warning(self, 'Insufficient funds', \
'You have specified more than your spendable balance to '
'the other recipients and the transaction fee. Therefore, the '
'maximum amount for this recipient would actually be negative.', \
QMessageBox.Ok)
return
targWidget.setText(maxStr.strip())
#####################################################################
def createSetMaxButton(self, targWidget):
newBtn = QPushButton('MAX')
newBtn.setMaximumWidth(relaxedSizeStr(self, 'MAX')[0])
newBtn.setToolTip('<u></u>Fills in the maximum spendable amount minus '
'the amounts specified for other recipients '
'and the transaction fee ')
funcSetMax = lambda: self.setMaximum(targWidget)
self.connect(newBtn, SIGNAL(CLICKED), funcSetMax)
return newBtn
#####################################################################
def makeRecipFrame(self, nRecip):
prevNRecip = len(self.widgetTable)
nRecip = max(nRecip, 1)
inputs = []
for i in range(nRecip):
if i < prevNRecip and i < nRecip:
inputs.append([])
for widg in ['QLE_ADDR', 'QLE_AMT', 'QLE_COMM']:
inputs[-1].append(str(self.widgetTable[i][widg].text()))
frmRecip = QFrame()
frmRecip.setFrameStyle(QFrame.NoFrame)
frmRecipLayout = QVBoxLayout()
def revertColorCallback(row):
def callbk():
self.updateAddrColor(row, Colors.Background)
return callbk
self.widgetTable = []
for r in range(nRecip):
self.widgetTable.append({})
self.widgetTable[r]['LBL_ADDR'] = QLabel('Address %d:' % (r+1))
addrEntryWidgets = self.main.createAddressEntryWidgets(self, maxDetectLen=45, boldDetectParts=1)
self.widgetTable[r]['FUNC_GETSCRIPT'] = addrEntryWidgets['CALLBACK_GETSCRIPT']
self.widgetTable[r]['QLE_ADDR'] = addrEntryWidgets['QLE_ADDR']
self.widgetTable[r]['QLE_ADDR'].setMinimumWidth(relaxedSizeNChar(GETFONT('var'), 20)[0])
self.widgetTable[r]['QLE_ADDR'].setMaximumHeight(self.maxHeight)
self.widgetTable[r]['QLE_ADDR'].setFont(GETFONT('var', 9))
self.connect(self.widgetTable[r]['QLE_ADDR'], SIGNAL('textChanged(QString)'),
revertColorCallback(r))
self.widgetTable[r]['BTN_BOOK'] = addrEntryWidgets['BTN_BOOK']
self.widgetTable[r]['LBL_DETECT'] = addrEntryWidgets['LBL_DETECT']
self.widgetTable[r]['LBL_AMT'] = QLabel('Amount:')
self.widgetTable[r]['QLE_AMT'] = QLineEdit()
self.widgetTable[r]['QLE_AMT'].setFont(GETFONT('Fixed'))
self.widgetTable[r]['QLE_AMT'].setMinimumWidth(tightSizeNChar(GETFONT('Fixed'), 14)[0])