forked from etotheipi/BitcoinArmory
-
Notifications
You must be signed in to change notification settings - Fork 172
/
TxFrames.py
2371 lines (1962 loc) · 96.2 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, estimateTxSize
from ui.WalletFrames import SelectWalletFrame, LockboxSelectFrame
from armoryengine.MultiSigUtils import \
calcLockboxID, readLockboxEntryStr, createLockboxEntryStr, isBareLockbox,\
isP2SHLockbox
from armoryengine.ArmoryUtils import MAX_COMMENT_LENGTH, getAddrByte
from FeeSelectUI import FeeSelectionDialog
from CppBlockUtils import TXOUT_SCRIPT_P2SH, TXOUT_SCRIPT_P2WPKH, TXOUT_SCRIPT_P2WSH, \
TransactionBatch, SecureBinaryData, RecipientReuseException
from armoryengine.SignerWrapper import SIGNER_DEFAULT
class SendBitcoinsFrame(ArmoryFrame):
def __init__(self, parent, main, initLabel='',
wlt=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.customUtxoList = []
self.altBalance = None
self.useCustomListInFull = False
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
self.widgetTable = []
self.isMax = False
self.scrollRecipArea = QScrollArea()
self.signerType = SIGNER_DEFAULT
lblRecip = QRichLabel('<b>Enter Recipients:</b>')
lblRecip.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
self.shuffleEntries = True
self.freeOfErrors = True
def getWalletIdList(onlyOfflineWallets):
result = []
if onlyOfflineWallets:
result = self.main.getWatchingOnlyWallets()
else:
result = list(self.main.walletIDList)
return result
self.wltIDList = wltIDList
if wltIDList == None:
self.wltIDList = getWalletIdList(onlyOfflineWallets)
feetip = self.main.createToolTipWidget(\
self.tr('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.'))
self.feeDialog = FeeSelectionDialog(self, self.main, \
self.resolveCoinSelection, self.getCoinSelectionState)
self.feeLblButton = self.feeDialog.getLabelButton()
def feeDlg():
self.feeDialog.exec_()
self.connect(self.feeLblButton, SIGNAL('clicked()'), feeDlg)
# 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(self.tr('Use an existing address for change'))
self.radioFeedback = QRadioButton(self.tr('Send change to first input address'))
self.radioSpecify = QRadioButton(self.tr('Specify a change address'))
self.lblChangeAddr = QRichLabel(self.tr('Change:'))
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(self.tr('Remember for future transactions'))
self.vertLine = VLINE()
self.ttipSendChange = self.main.createToolTipWidget(\
self.tr('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(\
self.tr('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(\
self.tr('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(\
self.tr('Check this box to create an unsigned transaction to be signed'
' and/or broadcast later.'))
self.unsignedCheckbox = QCheckBox(self.tr('Create Unsigned'))
self.RBFcheckbox = QCheckBox(self.tr('enable RBF'))
self.RBFcheckbox.setChecked(True)
self.ttipRBF = self.main.createToolTipWidget(\
self.tr('RBF flagged inputs allow to respend the underlying outpoint for a '
'higher fee as long as the original spending transaction remains '
'unconfirmed. <br><br>'
'Checking this box will RBF flag all inputs in this transaction'))
self.btnSend = QPushButton(self.tr('Send!'))
self.btnCancel = QPushButton(self.tr('Cancel'))
self.connect(self.btnCancel, SIGNAL(CLICKED), parent.reject)
self.btnPreviewTx = QLabelButton("Preview Transaction")
self.connect(self.btnPreviewTx, SIGNAL('clicked()'), self.previewTx)
# 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
RBFcallback = self.RBFupdate 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,
RBFcallback=RBFcallback)
else:
self.frmSelectedWlt = LockboxSelectFrame(parent, main,
VERTICAL,
self.lbox.uniqueIDB58)
self.setupCoinSelectionForLockbox(self.lbox)
# 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
metaButtonList = [self.btnPreviewTx, STRETCH, self.RBFcheckbox, self.ttipRBF]
buttonList = []
if self.createUnsignedTxCallback:
self.connect(self.unsignedCheckbox, SIGNAL(CLICKED), self.unsignedCheckBoxUpdate)
buttonList.append(self.unsignedCheckbox)
buttonList.append(self.ttipUnsigned)
buttonList.append(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([self.feeLblButton, feetip], STYLE_RAISED, condenseMargins=True)
metaFrm = makeHorizFrame(metaButtonList, STYLE_RAISED, condenseMargins=True)
buttonFrame = makeHorizFrame(buttonList, condenseMargins=True)
btnEnterURI = QPushButton(self.tr('Manually Enter "bitcoin:" Link'))
ttipEnterURI = self.main.createToolTipWidget( self.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 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(self.tr('<b>Sending from Wallet:</b>'))
lblSend.setAlignment(Qt.AlignLeft | Qt.AlignBottom)
leftFrame = makeVertFrame([lblSend, frmBottomLeft], condenseMargins=True)
rightFrame = makeVertFrame(\
[lblRecip, self.scrollRecipArea, txFrm, metaFrm, 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(self.tr('Send Bitcoins'))
self.setMinimumHeight(self.maxHeight * 20)
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(self.tr('Continue'))
self.btnSend.setToolTip(self.tr('Click to create an unsigned transaction!'))
else:
self.btnSend.setText(self.tr('Send!'))
self.btnSend.setToolTip(self.tr('Click to send bitcoins!'))
#############################################################################
def getRBFFlag(self):
return self.RBFcheckbox.checkState() == Qt.Checked
#############################################################################
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 and addr160:
self.wlt.setComment(addr160, label)
if len(self.widgetTable) > 0:
lastIsEmpty = True
for widg in ['QLE_ADDR', 'QLE_AMT', 'QLE_COMM']:
if len(str(self.widgetTable[-1][widg].text())) > 0:
lastIsEmpty = False
else:
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)
self.addCoinSelectionRecipient(len(self.widgetTable) - 1)
self.resolveCoinSelection()
#############################################################################
# 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
self.setupCoinSelectionInstance()
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)
#############################################################################
def setupCoinSelectionInstance(self):
if self.wlt is None:
self.coinSelection = None
return
self.coinSelection = self.wlt.cppWallet.getCoinSelectionInstance()
try:
self.resetCoinSelectionRecipients()
except:
pass
#############################################################################
def setupCoinSelectionForLockbox(self, lbox):
try:
lbCppWlt = self.main.cppLockboxWltMap[lbox.uniqueIDB58]
self.coinSelection = Cpp.CoinSelectionInstance(\
lbCppWlt, lbox.M, lbox.N, \
TheBDM.getTopBlockHeight(), lbCppWlt.getSpendableBalance())
except:
self.coinSelection = None
#############################################################################
def resetCoinSelectionRecipients(self):
if self.coinSelection is None:
return
self.coinSelection.resetRecipients()
for row in range(len(self.widgetTable)):
self.addCoinSelectionRecipient(row)
try:
self.resolveCoinSelection()
except:
pass
#############################################################################
def addCoinSelectionRecipient(self, id_):
try:
coinSelRow = self.widgetTable[id_]
scrAddr = str(coinSelRow['QLE_ADDR'].text()).strip()
if len(scrAddr) == 0:
raise BadAddressError('Empty address string')
try:
prefix, h160 = addrStr_to_hash160(scrAddr)
except:
h160 = Cpp.BtcUtils_bech32ToScript(scrAddr, BECH32_PREFIX)[2:]
if len(h160) == 20:
prefix = SCRADDR_P2WPKH_BYTE
elif len(h160) == 32:
prefix = SCRADDR_P2WSH_BYTE
scrAddr = prefix + h160
valueStr = str(coinSelRow['QLE_AMT'].text()).strip()
value = str2coin(valueStr, negAllowed=False)
self.coinSelection.addRecipient(scrAddr, value)
except:
self.resetCoinSelectionText()
#############################################################################
def updateCoinSelectionRecipient(self, uid):
try:
id_ = -1
for i in range(len(self.widgetTable)):
if self.widgetTable[i]['UID'] == uid:
id_ = i
if id_ == -1:
raise Exception()
coinSelRow = self.widgetTable[id_]
if 'OP_RETURN' not in coinSelRow:
addrStr = str(coinSelRow['QLE_ADDR'].text()).strip()
try:
prefix, h160 = addrStr_to_hash160(addrStr)
except:
#recipient input is not an address, is it a locator instead?
scriptDict = self.main.getScriptForUserString(addrStr)
if scriptDict['Script'] == None:
raise Exception("invalid addrStr in recipient")
if scriptDict['IsBech32'] == False:
scraddr = script_to_scrAddr(scriptDict['Script'])
prefix = scraddr[0]
h160 = scraddr[1:]
else:
h160 = Cpp.BtcUtils_bech32ToScript(addrStr, BECH32_PREFIX)[2:]
if len(h160) == 20:
prefix = SCRADDR_P2WPKH_BYTE
elif len(h160) == 32:
prefix = SCRADDR_P2WSH_BYTE
scrAddr = prefix + h160
valueStr = str(coinSelRow['QLE_AMT'].text()).strip()
try:
value = str2coin(valueStr, negAllowed=False)
except:
value = 0
self.coinSelection.updateRecipient(id_, scrAddr, value)
else:
opreturn_message = str(coinSelRow['QLE_ADDR'].text())
self.coinSelection.updateOpReturnRecipient(id_, opreturn_message)
self.resolveCoinSelection()
except:
self.resetCoinSelectionText()
#############################################################################
def serializeUtxoList(self, utxoList):
serializedUtxoList = []
for utxo in utxoList:
bp = BinaryPacker()
bp.put(UINT64, utxo.getValue())
bp.put(UINT32, utxo.getTxHeight())
bp.put(UINT16, utxo.getTxIndex())
bp.put(UINT16, utxo.getTxOutIndex())
bp.put(VAR_STR, utxo.getTxHash())
bp.put(VAR_STR, utxo.getScript())
bp.put(UINT32, utxo.sequence)
serializedUtxoList.append(bp.getBinaryString())
return serializedUtxoList
#############################################################################
def resolveCoinSelection(self):
maxRecipientID = self.getMaxRecipientID()
if maxRecipientID != None:
self.setMaximum(maxRecipientID)
try:
fee, feePerByte, adjust_fee = self.feeDialog.getFeeData()
processFlag = 0
if self.useCustomListInFull:
processFlag += Cpp.USE_FULL_CUSTOM_LIST
if adjust_fee:
processFlag += Cpp.ADJUST_FEE
if self.shuffleEntries:
processFlag += Cpp.SHUFFLE_ENTRIES
if self.customUtxoList is None or len(self.customUtxoList) == 0:
self.coinSelection.selectUTXOs(fee, feePerByte, processFlag)
else:
serializedUtxoList = self.serializeUtxoList(self.customUtxoList)
self.coinSelection.processCustomUtxoList(\
serializedUtxoList, fee, feePerByte, processFlag)
self.feeDialog.updateLabelButton()
except RuntimeError as e:
self.resetCoinSelectionText()
raise e
#############################################################################
def getCoinSelectionState(self):
txSize = self.coinSelection.getSizeEstimate()
flatFee = self.coinSelection.getFlatFee()
feeByte = self.coinSelection.getFeeByte()
return txSize, flatFee, feeByte
#############################################################################
def resetCoinSelectionText(self):
self.feeDialog.resetLabel()
#############################################################################
# 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, customUtxoList, altBalance, useAll):
self.customUtxoList = customUtxoList
self.altBalance = altBalance
self.useCustomListInFull = useAll
try:
self.resolveCoinSelection()
except:
pass
#############################################################################
def RBFupdate(self, rbfList, altBalance, forceVerbose=False):
self.customUtxoList = rbfList
self.useCustomListInFull = True
self.altBalance = altBalance
try:
self.resolveCoinSelection()
except:
if forceVerbose == False:
return
#failed to setup rbf send dialog, maybe the setup cannot cover for
#auto fee. let's force the fee to 0 and warn the user
self.feeDialog.setZeroFee()
try:
self.resolveCoinSelection()
MsgBoxCustom(MSGBOX.Warning, self.tr('RBF value error'), \
self.tr(
'You are trying to bump the fee of a broadcasted unconfirmed transaction. '
'Unfortunately, your transaction lacks the funds to cover the default fee. '
'Therefore, <b><u>the default fee has currently been set to 0</b></u>.<br><br>'
'You will have to set the appropriate fee and arrange the transaction spend '
'value manually to successfully double spend this transaction.'
), \
yesStr=self.tr('Ok'))
except:
MsgBoxCustom(MSGBOX.Error, self.tr('RBF failure'), \
self.tr(
'You are trying to bump the fee of a broadcasted unconfirmed transaction. '
'The process failed unexpectedly. To double spend your transaction, pick '
'the relevant output from the RBF Control dialog, found in the Send dialog '
'in Expert User Mode.') , \
yesStr=self.tr('Ok'))
#############################################################################
def handleCppCoinSelectionExceptions(self):
try:
self.coinSelection.rethrow()
except RecipientReuseException as e:
addrList = e.getAddresses()
addrParagraph = '<br>'
for addrEntry in addrList:
addrParagraph = addrParagraph + ' - ' + addrEntry + '<br>'
result = MsgBoxCustom(MSGBOX.Warning, self.tr('Recipient reuse'), \
self.tr(
'The transaction you crafted <b>reuses</b> the following recipient address(es):<br>'
'%1<br>'
' The sum of values for this leg of the transaction amounts to %2 BTC. There is only'
' a total of %3 BTC available in UTXOs to fund this leg of the'
' transaction without <b>damaging your privacy.</b>'
'<br><br>In order to meet the full payment, Armory has to make use of extra '
' UTXOs, <u>and this will result in privacy loss on chain.</u> <br><br>'
'To progress beyond this warning, choose Ignore. Otherwise'
' the operation will be cancelled.'
).arg(addrParagraph, \
coin2str(e.total(), 5, maxZeros=0), \
coin2str(e.value(), 5, maxZeros=0)), \
wCancel=True, yesStr=self.tr('Ignore'), noStr=self.tr('Cancel'))
if not result:
return False
return True;
#############################################################################
def validateInputsGetUSTX(self, peek=False):
self.freeOfErrors = True
scripts = []
addrList = []
self.comments = []
if self.handleCppCoinSelectionExceptions() == False:
return
for row in range(len(self.widgetTable)):
# Verify validity of address strings
widget_obj = self.widgetTable[row]
if 'OP_RETURN' in widget_obj:
continue
addrStr = str(widget_obj['QLE_ADDR'].text()).strip()
self.widgetTable[row]['QLE_ADDR'].setText(addrStr) # overwrite w/ stripped
addrIsValid = True
addrList.append(addrStr)
try:
enteredScript = widget_obj['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, self.tr('Invalid Address'),
self.tr("You have entered %1 invalid addresses. "
"The errors have been highlighted on the entry screen").arg(str(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, self.tr('Wrong Network!'), self.tr(
'Address %1 is for the wrong network! You are on the <b>%2</b> '
'and the address you supplied is for the the <b>%3</b>!').arg(row+1, NETWORKS[ADDRBYTE], net), QMessageBox.Ok)
except:
pass
return False
# Construct recipValuePairs and check that all metrics check out
scriptValPairs = []
opreturn_list = []
totalSend = 0
for row in range(len(self.widgetTable)):
widget_obj = self.widgetTable[row]
if 'OP_RETURN' in widget_obj:
opreturn_msg = str(widget_obj['QLE_ADDR'].text())
if len(opreturn_msg) > 80:
self.updateAddrColor(row, Colors.SlightRed)
QMessageBox.critical(self, self.tr('Negative Value'), \
self.tr('You have specified a OP_RETURN message over 80 bytes long in recipient %1!'
).arg(row + 1), QMessageBox.Ok)
return False
opreturn_list.append(opreturn_msg)
continue
try:
valueStr = str(self.widgetTable[row]['QLE_AMT'].text()).strip()
value = str2coin(valueStr, negAllowed=False)
if value == 0:
QMessageBox.critical(self, self.tr('Zero Amount'), \
self.tr('You cannot send 0 BTC to any recipients. <br>Please enter '
'a positive amount for recipient %1.').arg(row+1), QMessageBox.Ok)
return False
except NegativeValueError:
QMessageBox.critical(self, self.tr('Negative Value'), \
self.tr('You have specified a negative amount for recipient %1. <br>Only '
'positive values are allowed!.').arg(row + 1), QMessageBox.Ok)
return False
except TooMuchPrecisionError:
QMessageBox.critical(self, self.tr('Too much precision'), \
self.tr('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 %1.').arg(row + 1), QMessageBox.Ok)
return False
except ValueError:
QMessageBox.critical(self, self.tr('Missing recipient amount'), \
self.tr('You did not specify an amount to send!'), QMessageBox.Ok)
return False
except:
QMessageBox.critical(self, self.tr('Invalid Value String'), \
self.tr('The amount you specified '
'to send to address %1 is invalid (%2).').arg(row + 1, valueStr), QMessageBox.Ok)
LOGERROR('Invalid amount specified: "%s"', valueStr)
return False
totalSend += value
script = self.widgetTable[row]['FUNC_GETSCRIPT']()['Script']
scriptValPairs.append([script, value])
self.comments.append((str(self.widgetTable[row]['QLE_COMM'].text()), value))
try:
utxoSelect = self.getUsableTxOutList()
except RuntimeError as e:
QMessageBox.critical(self, self.tr('Coin Selection Failure'), \
self.tr('Coin selection failed with error: <b>%1<b/>').arg(e.message), \
QMessageBox.Ok)
return False
fee = self.coinSelection.getFlatFee()
fee_byte = self.coinSelection.getFeeByte()
# Warn user of excessive fee specified
if peek == False:
feebyteStr = "%.2f" % fee_byte
if fee_byte > 10 * MIN_FEE_BYTE:
reply = QMessageBox.warning(self, self.tr('Excessive Fee'), self.tr(
'Your transaction comes with a fee rate of <b>%1 satoshis per byte</b>. '
'</br></br> '
'This is at least an order of magnitude higher than the minimum suggested fee rate of <b>%2 satoshi/Byte</b>. '
'<br><br>'
'Are you <i>absolutely sure</i> that you want to send with this '
'fee? If you do not want to proceed with this fee rate, click "No".').arg(\
feebyteStr, unicode(MIN_FEE_BYTE)), QMessageBox.Yes | QMessageBox.No)
if not reply==QMessageBox.Yes:
return False
elif fee_byte < MIN_FEE_BYTE:
reply = QMessageBox.warning(self, self.tr('Insufficient Fee'), self.tr(
'Your transaction comes with a fee rate of <b>%1 satoshi/Byte</b>. '
'</br><br> '
'This is lower than the suggested minimum fee rate of <b>%2 satoshi/Byte</b>. '
'<br><br>'
'Are you <i>absolutely sure</i> that you want to send with this '
'fee? If you do not want to proceed with this fee rate, click "No".').arg(\
feebyteStr, unicode(MIN_FEE_BYTE)), QMessageBox.Yes | QMessageBox.No)
if not reply==QMessageBox.Yes:
return False
if len(utxoSelect) == 0:
QMessageBox.critical(self, self.tr('Coin Selection Error'), self.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, scriptValPairs, peek)
self.changeScript = script
self.selectedBehavior = behavior
scriptValPairs.append([self.changeScript, totalChange])
LOGINFO('Change address behavior: %s', self.selectedBehavior)
else:
self.selectedBehavior = NO_CHANGE
# Keep a copy of the originally-sorted list for display
origSVPairs = scriptValPairs[:]
# Anonymize the outputs
if self.shuffleEntries:
random.shuffle(scriptValPairs)
p2shMap = {}
pubKeyMap = {}
if self.getRBFFlag():
for utxo in utxoSelect:
if utxo.sequence == 2**32 - 1:
utxo.sequence = 2**32 - 3
# In order to create the USTXI objects, need to make sure we supply a
# map of public keys that can be included
if self.lbox:
p2shMap = self.lbox.getScriptDict()
ustx = UnsignedTransaction().createFromTxOutSelection( \
utxoSelect, scriptValPairs, \
p2shMap = p2shMap, \
lockTime=TheBDM.getTopBlockHeight())
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
for utxo in utxoSelect:
scrType = getTxOutScriptType(utxo.getScript())
scrAddr = utxo.getRecipientScrAddr()
if scrType in CPP_TXOUT_STDSINGLESIG:
a160 = scrAddr_to_hash160(scrAddr)[1]
addrObj = self.wlt.getAddrByHash160(a160)
if addrObj:
pubKeyMap[scrAddr] = addrObj.binPublicKey65.toBinStr()
elif scrType == CPP_TXOUT_P2SH:
p2shScript = self.wlt.cppWallet.getP2SHScriptForHash(utxo.getScript())
p2shKey = binary_to_hex(script_to_scrAddr(script_to_p2sh_script(
p2shScript)))
p2shMap[p2shKey] = p2shScript
addrIndex = self.wlt.cppWallet.getAssetIndexForAddr(utxo.getRecipientHash160())
try:
addrStr = self.wlt.chainIndexMap[addrIndex]
except:
if addrIndex < -2:
importIndex = self.wlt.cppWallet.convertToImportIndex(addrIndex)
addrStr = self.wlt.linearAddr160List[importIndex]
else:
raise Exception("invalid address index")
addrObj = self.wlt.addrMap[addrStr]
pubKeyMap[scrAddr] = addrObj.binPublicKey65.toBinStr()
'''
If we are consuming any number of SegWit utxos, pass the utxo selection
and outputs to the new signer for processing instead of creating the
unsigned tx in Python.
'''
# Now create the unsigned USTX
ustx = UnsignedTransaction().createFromTxOutSelection(\
utxoSelect, scriptValPairs, pubKeyMap, p2shMap=p2shMap, \
lockTime=TheBDM.getTopBlockHeight())
for msg in opreturn_list:
ustx.addOpReturnOutput(str(msg))
#ustx.pprint()
txValues = [totalSend, fee, totalChange]
if not peek:
if not self.unsignedCheckbox.isChecked():
dlg = DlgConfirmSend(self.wlt, origSVPairs, txValues[1], self, \
self.main, True, ustx)
if not dlg.exec_():
return False
self.signerType = dlg.getSignerType()
else:
self.main.warnNewUSTXFormat()
return ustx
def createTxAndBroadcast(self):
def unlockWallet():
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(), self.tr('Wallet is Locked'), \
self.tr('Cannot sign transaction while your wallet is locked. '), \
QMessageBox.Ok)
return
else:
self.wlt.kdfKey = self.wlt.kdf.DeriveKey(Passphrase)
Passphrase.destroy()
# The Send! button is clicked validate and broadcast tx
ustx = self.validateInputsGetUSTX()
if ustx:
self.updateUserComments()
if self.createUnsignedTxCallback and self.unsignedCheckbox.isChecked():
self.createUnsignedTxCallback(ustx)
else:
try:
unlockWallet()
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, signer=self.signerType)
finalTx = ustxSigned.getSignedPyTx(signer=ustxSigned.signerType)
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()
#############################################################################