forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createtx.go
1926 lines (1681 loc) · 55.7 KB
/
createtx.go
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) 2013-2016 The btcsuite developers
// Copyright (c) 2015-2016 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package wallet
import (
"crypto/rand"
"errors"
"fmt"
"time"
"github.com/btcsuite/golangcrypto/ripemd160"
"github.com/decred/dcrd/blockchain/stake"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainec"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrutil"
"github.com/decred/dcrwallet/chain"
"github.com/decred/dcrwallet/waddrmgr"
"github.com/decred/dcrwallet/wallet/txauthor"
"github.com/decred/dcrwallet/wallet/txrules"
"github.com/decred/dcrwallet/wtxmgr"
)
// --------------------------------------------------------------------------------
// Constants and simple functions
const (
// All transactions have 4 bytes for version, 4 bytes of locktime,
// 4 bytes of expiry, and 2 varints for the number of inputs and
// outputs, and 1 varint for the witnesses.
txOverheadEstimate = 4 + 4 + 4 + 1 + 1 + 1
// A worst case signature script to redeem a P2PKH output for a
// compressed pubkey has 73 bytes of the possible DER signature
// (with no leading 0 bytes for R and S), 65 bytes of serialized pubkey,
// and data push opcodes for both, plus one byte for the hash type flag
// appended to the end of the signature.
sigScriptEstimate = 1 + 73 + 1 + 65 + 1
// A best case tx input serialization cost is 32 bytes of sha, 4 bytes
// of output index, 1 byte for tree, 4 bytes of sequence, 12 bytes for
// fraud proof, and the estimated signature script size.
txInEstimate = 32 + 4 + 1 + 12 + 4 + sigScriptEstimate
// sstxTicketCommitmentEstimate =
// - version + amount +
// OP_SSTX OP_DUP OP_HASH160 OP_DATA_20 OP_EQUALVERIFY OP_CHECKSIG
sstxTicketCommitmentEstimate = 2 + 8 + 1 + 1 + 1 + 1 + 20 + 1 + 1
// sstxSubsidyCommitmentEstimate =
// version + amount + OP_RETURN OP_DATA_30
sstxSubsidyCommitmentEstimate = 2 + 8 + 2 + 30
// sstxChangeOutputEstimate =
// version + amount + OP_SSTXCHANGE OP_DUP OP_HASH160 OP_DATA_20
// OP_EQUALVERIFY OP_CHECKSIG
sstxChangeOutputEstimate = 2 + 8 + 1 + 1 + 1 + 1 + 20 + 1 + 1
// A P2PKH pkScript contains the following bytes:
// - OP_DUP
// - OP_HASH160
// - OP_DATA_20 + 20 bytes of pubkey hash
// - OP_EQUALVERIFY
// - OP_CHECKSIG
pkScriptEstimate = 1 + 1 + 1 + 20 + 1 + 1
// pkScriptEstimateSS is the estimated size of a ticket P2PKH output script.
pkScriptEstimateSS = 1 + 1 + 1 + 1 + 20 + 1 + 1
// txOutEstimate is a best case tx output serialization cost is 8 bytes
// of value, two bytes of version, one byte of varint, and the pkScript
// size.
txOutEstimate = 8 + 2 + 1 + pkScriptEstimate
// ssTxOutEsimate is the estimated size of a P2PKH ticket output.
ssTxOutEsimate = 8 + 2 + 1 + pkScriptEstimateSS
// singleInputTicketSize is the typical size of a normal P2PKH ticket
// in bytes when the ticket has one input, rounded up.
singleInputTicketSize = 300
// doubleInputTicketSize is the typical size of a normal P2PKH ticket
// in bytes when the ticket has two inputs, rounded up.
doubleInputTicketSize = 550
// defaultTicketFeeLimits is the default byte string for the default
// fee limits imposed on a ticket.
defaultTicketFeeLimits = 0x5800
)
var (
// maxTxSize is the maximum size of a transaction we can
// build with the wallet.
maxTxSize = chaincfg.MainNetParams.MaximumBlockSize - 75000
)
func estimateTxSize(numInputs, numOutputs int) int {
return txOverheadEstimate + txInEstimate*numInputs + txOutEstimate*numOutputs
}
// EstimateTxSize is the exported version of estimateTxSize which provides
// an estimate of the tx size based on the number of inputs, outputs, and some
// assumed overhead.
func EstimateTxSize(numInputs, numOutputs int) int {
return estimateTxSize(numInputs, numOutputs)
}
func estimateSSTxSize(numInputs int) int {
return txOverheadEstimate + txInEstimate*numInputs +
sstxTicketCommitmentEstimate +
(sstxSubsidyCommitmentEstimate+
sstxChangeOutputEstimate)*numInputs
}
func feeForSize(incr dcrutil.Amount, sz int) dcrutil.Amount {
return dcrutil.Amount(1+sz/1000) * incr
}
// FeeForSize is the exported version of feeForSize which returns a fee
// based on the provided feeIncrement and provided size.
func FeeForSize(incr dcrutil.Amount, sz int) dcrutil.Amount {
return feeForSize(incr, sz)
}
// DefaultTicketFeeIncrement is the default minimum stake transaction fees per KB (0.01
// coin, measured in atoms).
const DefaultTicketFeeIncrement dcrutil.Amount = 1e6
// EstMaxTicketFeeAmount is the estimated max ticket fee to be used for size
// calculation for eligible utxos for ticket purchasing.
const EstMaxTicketFeeAmount = 0.1 * 1e8
// extendedOutPoint is a UTXO with an amount.
type extendedOutPoint struct {
op *wire.OutPoint
amt int64
pkScript []byte
}
// --------------------------------------------------------------------------------
// Error Handling
// ErrUnsupportedTransactionType represents an error where a transaction
// cannot be signed as the API only supports spending P2PKH outputs.
var ErrUnsupportedTransactionType = errors.New("Only P2PKH transactions " +
"are supported")
// ErrNonPositiveAmount represents an error where an amount is
// not positive (either negative, or zero).
var ErrNonPositiveAmount = errors.New("amount is not positive")
// ErrNegativeFee represents an error where a fee is erroneously
// negative.
var ErrNegativeFee = errors.New("fee is negative")
// ErrSStxNotEnoughFunds indicates that not enough funds were available in the
// wallet to purchase a ticket.
var ErrSStxNotEnoughFunds = errors.New("not enough to purchase sstx")
// ErrSStxPriceExceedsSpendLimit indicates that the current ticket price exceeds
// the specified spend maximum spend limit.
var ErrSStxPriceExceedsSpendLimit = errors.New("ticket price exceeds spend limit")
// ErrNoOutsToConsolidate indicates that there were no outputs available
// to compress.
var ErrNoOutsToConsolidate = errors.New("no outputs to consolidate")
// ErrBlockchainReorganizing indicates that the blockchain is currently
// reorganizing.
var ErrBlockchainReorganizing = errors.New("blockchain is currently " +
"reorganizing")
// ErrTicketPriceNotSet indicates that the wallet was recently connected
// and that the ticket price has not yet been set.
var ErrTicketPriceNotSet = errors.New("ticket price not yet established")
// --------------------------------------------------------------------------------
// Transaction creation
// secretSource is an implementation of txauthor.SecretSource for the wallet's
// address manager.
type secretSource struct {
*waddrmgr.Manager
}
func (s secretSource) GetKey(addr dcrutil.Address) (chainec.PrivateKey, bool, error) {
ma, err := s.Address(addr)
if err != nil {
return nil, false, err
}
mpka, ok := ma.(waddrmgr.ManagedPubKeyAddress)
if !ok {
e := fmt.Errorf("managed address type for %v is `%T` but "+
"want waddrmgr.ManagedPubKeyAddress", addr, ma)
return nil, false, e
}
privKey, err := mpka.PrivKey()
if err != nil {
return nil, false, err
}
return privKey, ma.Compressed(), nil
}
func (s secretSource) GetScript(addr dcrutil.Address) ([]byte, error) {
ma, err := s.Address(addr)
if err != nil {
return nil, err
}
msa, ok := ma.(waddrmgr.ManagedScriptAddress)
if !ok {
e := fmt.Errorf("managed address type for %v is `%T` but "+
"want waddrmgr.ManagedScriptAddress", addr, ma)
return nil, e
}
return msa.Script()
}
// CreatedTx holds the state of a newly-created transaction and the change
// output (if one was added).
type CreatedTx struct {
MsgTx *wire.MsgTx
ChangeAddr dcrutil.Address
ChangeIndex int // negative if no change
Fee dcrutil.Amount
}
// insertIntoTxMgr inserts a newly created transaction into the tx store
// as unconfirmed.
func (w *Wallet) insertIntoTxMgr(msgTx *wire.MsgTx) (*wtxmgr.TxRecord, error) {
// Create transaction record and insert into the db.
rec, err := wtxmgr.NewTxRecordFromMsgTx(msgTx, time.Now())
if err != nil {
return nil, dcrjson.ErrInternal
}
return rec, w.TxStore.InsertTx(rec, nil)
}
func (w *Wallet) insertCreditsIntoTxMgr(msgTx *wire.MsgTx,
rec *wtxmgr.TxRecord) error {
// Check every output to determine whether it is controlled by a wallet
// key. If so, mark the output as a credit.
for i, output := range msgTx.TxOut {
_, addrs, _, err := txscript.ExtractPkScriptAddrs(output.Version,
output.PkScript, w.chainParams)
if err != nil {
// Non-standard outputs are skipped.
continue
}
for _, addr := range addrs {
ma, err := w.Manager.Address(addr)
if err == nil {
// TODO: Credits should be added with the
// account they belong to, so wtxmgr is able to
// track per-account balances.
err = w.TxStore.AddCredit(rec, nil, uint32(i),
ma.Internal(), ma.Account())
if err != nil {
return err
}
err = w.Manager.MarkUsed(addr)
if err != nil {
return err
}
log.Debugf("Marked address %v used", addr)
continue
}
// Missing addresses are skipped. Other errors should
// be propagated.
code := err.(waddrmgr.ManagerError).ErrorCode
if code != waddrmgr.ErrAddressNotFound {
return err
}
}
}
return nil
}
// insertMultisigOutIntoTxMgr inserts a multisignature output into the
// transaction store database.
func (w *Wallet) insertMultisigOutIntoTxMgr(msgTx *wire.MsgTx,
index uint32) error {
// Create transaction record and insert into the db.
rec, err := wtxmgr.NewTxRecordFromMsgTx(msgTx, time.Now())
if err != nil {
return dcrjson.ErrInternal
}
return w.TxStore.AddMultisigOut(rec, nil, index)
}
// TxToOutputs is the exported version of txToOutputs that does all relevant
// locking to ensure the safety of the wallet state to generate a transaction.
// It then calls txToOutputs to generate a transaction.
func (w *Wallet) TxToOutputs(outputs []*wire.TxOut, account uint32, minconf int32,
randomizeChangeIdx bool) (atx *txauthor.AuthoredTx, err error) {
// Address manager must be unlocked to compose transaction. Grab
// the unlock if possible (to prevent future unlocks), or return the
// error if already locked.
heldUnlock, err := w.HoldUnlock()
if err != nil {
return nil, err
}
defer heldUnlock.Release()
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
isReorganizing, _ := chainClient.GetReorganizing()
if isReorganizing {
return nil, ErrBlockchainReorganizing
}
// Initialize the address pool for use. If we
// are using an imported account, loopback to
// the default account to create change.
var pool *addressPool
if account == waddrmgr.ImportedAddrAccount {
err := w.CheckAddressPoolsInitialized(waddrmgr.DefaultAccountNum)
if err != nil {
return nil, err
}
pool = w.addrPools[waddrmgr.DefaultAccountNum].internal
} else {
err := w.CheckAddressPoolsInitialized(account)
if err != nil {
return nil, err
}
pool = w.addrPools[account].internal
}
changeAddrUsed := false
txSucceeded := false
pool.mutex.Lock()
defer pool.mutex.Unlock()
defer func() {
if txSucceeded && changeAddrUsed {
pool.BatchFinish()
} else {
pool.BatchRollback()
}
}()
atx, err = w.txToOutputs(outputs, account, minconf, pool, chainClient,
randomizeChangeIdx, w.RelayFee())
txSucceeded = atx != nil
return atx, err
}
// txToOutputs creates a signed transaction which includes each output from
// outputs. Previous outputs to reedeem are chosen from the passed account's
// UTXO set and minconf policy. An additional output may be added to return
// change to the wallet. An appropriate fee is included based on the wallet's
// current relay fee. The wallet must be unlocked to create the transaction.
// The address pool passed must be locked and engaged in an address pool
// batch call.
//
// Decred: This func also sends the transaction, and if successful, inserts it
// into the database, rather than delegating this work to the caller as
// btcwallet does.
func (w *Wallet) txToOutputs(outputs []*wire.TxOut, account uint32, minconf int32,
pool *addressPool, chainClient *chain.RPCClient, randomizeChangeIdx bool,
txFee dcrutil.Amount) (atx *txauthor.AuthoredTx, err error) {
// The change address is pulled here rather than after
// MakeInputSource is called because MakeInputSource
// accesses the database in a way that deadlocks other
// packages that also access the database like waddmgr.
// Because the address pool occasionally makes calls
// to the address manager to replenish the address pool,
// calling the address function after MakeInputSource
// and before inputSource.CloseTransaction() will
// sometimes cause a lockup.
changeAddrUsed := false
changeAddr, err := pool.getNewAddress()
if err != nil {
return nil, err
}
changeSource := func() ([]byte, error) {
changeAddrUsed = true
return txscript.PayToAddrScript(changeAddr)
}
// Get current block's height and hash.
bs, err := chainClient.BlockStamp()
if err != nil {
return nil, err
}
inputSource := w.TxStore.MakeInputSource(account, minconf, bs.Height)
tx, err := txauthor.NewUnsignedTransaction(outputs, txFee,
inputSource.SelectInputs, changeSource)
closeErr := inputSource.CloseTransaction()
if closeErr != nil {
log.Errorf("Failed to close view: %v", closeErr)
}
if err != nil {
return nil, err
}
// Randomize change position, if change exists, before signing. This
// doesn't affect the serialize size, so the change amount will still be
// valid.
if tx.ChangeIndex >= 0 && randomizeChangeIdx {
tx.RandomizeChangePosition()
}
err = tx.AddAllInputScripts(secretSource{w.Manager})
if err != nil {
return nil, err
}
err = validateMsgTx(tx.Tx, tx.PrevScripts)
if err != nil {
return nil, err
}
if tx.ChangeIndex >= 0 && account == waddrmgr.ImportedAddrAccount {
changeAmount := dcrutil.Amount(tx.Tx.TxOut[tx.ChangeIndex].Value)
log.Warnf("Spend from imported account produced change: moving"+
" %v from imported account into default account.", changeAmount)
}
_, err = chainClient.SendRawTransaction(tx.Tx, w.AllowHighFees)
if err != nil {
return nil, err
}
// Create transaction record and insert into the db.
rec, err := wtxmgr.NewTxRecordFromMsgTx(tx.Tx, time.Now())
if err != nil {
return nil, fmt.Errorf("Cannot create record for created transaction: %v",
err)
}
err = w.TxStore.InsertTx(rec, nil)
if err != nil {
return nil, fmt.Errorf("Error adding sent tx history: %v", err)
}
err = w.insertCreditsIntoTxMgr(tx.Tx, rec)
if err != nil {
return nil, err
}
return tx, nil
}
// constructMultiSigScript create a multisignature output script from a
// given list of public keys.
func constructMultiSigScript(keys []dcrutil.AddressSecpPubKey,
nRequired int) ([]byte, error) {
keysesPrecious := make([]*dcrutil.AddressSecpPubKey, len(keys))
return txscript.MultiSigScript(keysesPrecious, nRequired)
}
// txToMultisig spends funds to a multisig output, partially signs the
// transaction, then returns fund
func (w *Wallet) txToMultisig(account uint32, amount dcrutil.Amount,
pubkeys []*dcrutil.AddressSecpPubKey, nRequired int8,
minconf int32) (*CreatedTx, dcrutil.Address, []byte, error) {
txToMultisigError :=
func(err error) (*CreatedTx, dcrutil.Address, []byte, error) {
return nil, nil, nil, err
}
// Initialize the address pool for use. If we
// are using an imported account, loopback to
// the default account to create change.
var pool *addressPool
if account == waddrmgr.ImportedAddrAccount {
err := w.CheckAddressPoolsInitialized(waddrmgr.DefaultAccountNum)
if err != nil {
return txToMultisigError(err)
}
pool = w.addrPools[waddrmgr.DefaultAccountNum].internal
} else {
err := w.CheckAddressPoolsInitialized(account)
if err != nil {
return txToMultisigError(err)
}
pool = w.addrPools[account].internal
}
txSucceeded := false
pool.mutex.Lock()
defer pool.mutex.Unlock()
defer func() {
if txSucceeded {
pool.BatchFinish()
} else {
pool.BatchRollback()
}
}()
addrFunc := pool.getNewAddress
chainClient, err := w.requireChainClient()
if err != nil {
return txToMultisigError(err)
}
isReorganizing, _ := chainClient.GetReorganizing()
if isReorganizing {
return txToMultisigError(err)
}
// Address manager must be unlocked to compose transaction. Grab
// the unlock if possible (to prevent future unlocks), or return the
// error if already locked.
heldUnlock, err := w.HoldUnlock()
if err != nil {
return txToMultisigError(err)
}
defer heldUnlock.Release()
// Get current block's height and hash.
bs, err := chainClient.BlockStamp()
if err != nil {
return txToMultisigError(err)
}
// Add in some extra for fees. TODO In the future, make a better
// fee estimator.
var feeEstForTx dcrutil.Amount
switch {
case w.chainParams == &chaincfg.MainNetParams:
feeEstForTx = 5e7
case w.chainParams == &chaincfg.TestNetParams:
feeEstForTx = 5e7
default:
feeEstForTx = 3e4
}
amountRequired := amount + feeEstForTx
// Instead of taking reward addresses by arg, just create them now and
// automatically find all eligible outputs from all current utxos.
eligible, err := w.findEligibleOutputsAmount(account, minconf,
amountRequired, bs)
if err != nil {
return txToMultisigError(err)
}
if eligible == nil {
return txToMultisigError(
fmt.Errorf("Not enough funds to send to multisig address"))
}
msgtx := wire.NewMsgTx()
// Fill out inputs.
var forSigning []wtxmgr.Credit
totalInput := dcrutil.Amount(0)
numInputs := 0
for _, e := range eligible {
msgtx.AddTxIn(wire.NewTxIn(&e.OutPoint, nil))
totalInput += e.Amount
forSigning = append(forSigning, e)
numInputs++
}
// Insert a multi-signature output, then insert this P2SH
// hash160 into the address manager and the transaction
// manager.
totalOutput := dcrutil.Amount(0)
msScript, err := txscript.MultiSigScript(pubkeys, int(nRequired))
if err != nil {
return txToMultisigError(err)
}
_, err = w.Manager.ImportScript(msScript, bs)
if err != nil {
// We don't care if we've already used this address.
if err.(waddrmgr.ManagerError).ErrorCode !=
waddrmgr.ErrDuplicateAddress {
return txToMultisigError(err)
}
}
err = w.TxStore.InsertTxScript(msScript)
if err != nil {
return txToMultisigError(err)
}
scAddr, err := dcrutil.NewAddressScriptHash(msScript, w.chainParams)
if err != nil {
return txToMultisigError(err)
}
p2shScript, err := txscript.PayToAddrScript(scAddr)
if err != nil {
return txToMultisigError(err)
}
txout := wire.NewTxOut(int64(amount), p2shScript)
msgtx.AddTxOut(txout)
totalOutput += amount
// Add change if we need it. The case in which
// totalInput == amount+feeEst is skipped because
// we don't need to add a change output in this
// case.
feeSize := estimateTxSize(numInputs, 2)
feeIncrement := w.RelayFee()
feeEst := feeForSize(feeIncrement, feeSize)
if totalInput < amount+feeEst {
return txToMultisigError(fmt.Errorf("Not enough funds to send to " +
"multisig address after accounting for fees"))
}
if totalInput > amount+feeEst {
changeAddr, err := addrFunc()
if err != nil {
return txToMultisigError(err)
}
change := totalInput - (amount + feeEst)
pkScript, err := txscript.PayToAddrScript(changeAddr)
if err != nil {
return txToMultisigError(
fmt.Errorf("cannot create txout script: %s", err))
}
msgtx.AddTxOut(wire.NewTxOut(int64(change), pkScript))
}
if err = signMsgTx(msgtx, forSigning, w.Manager,
w.chainParams); err != nil {
return txToMultisigError(err)
}
_, err = chainClient.SendRawTransaction(msgtx, w.AllowHighFees)
if err != nil {
return txToMultisigError(err)
}
// Request updates from dcrd for new transactions sent to this
// script hash address.
utilAddrs := make([]dcrutil.Address, 1)
utilAddrs[0] = scAddr
if err := chainClient.NotifyReceived(utilAddrs); err != nil {
return txToMultisigError(err)
}
err = w.insertMultisigOutIntoTxMgr(msgtx, 0)
if err != nil {
return txToMultisigError(err)
}
ctx := &CreatedTx{
MsgTx: msgtx,
ChangeAddr: nil,
ChangeIndex: -1,
}
return ctx, scAddr, msScript, nil
}
// validateMsgTx verifies transaction input scripts for tx. All previous output
// scripts from outputs redeemed by the transaction, in the same order they are
// spent, must be passed in the prevScripts slice.
func validateMsgTx(tx *wire.MsgTx, prevScripts [][]byte) error {
for i, prevScript := range prevScripts {
vm, err := txscript.NewEngine(prevScript, tx, i,
txscript.StandardVerifyFlags, txscript.DefaultScriptVersion, nil)
if err != nil {
return fmt.Errorf("cannot create script engine: %s", err)
}
err = vm.Execute()
if err != nil {
return fmt.Errorf("cannot validate transaction: %s", err)
}
}
return nil
}
func validateMsgTxCredits(tx *wire.MsgTx, prevCredits []wtxmgr.Credit) error {
prevScripts := make([][]byte, 0, len(prevCredits))
for _, c := range prevCredits {
prevScripts = append(prevScripts, c.PkScript)
}
return validateMsgTx(tx, prevScripts)
}
// compressWallet compresses all the utxos in a wallet into a single change
// address. For use when it becomes dusty.
func (w *Wallet) compressWallet(maxNumIns int, account uint32) (*chainhash.Hash,
error) {
chainClient, err := w.requireChainClient()
if err != nil {
return nil, err
}
isReorganizing, _ := chainClient.GetReorganizing()
if isReorganizing {
return nil, ErrBlockchainReorganizing
}
// Get current block's height and hash.
bs, err := chainClient.BlockStamp()
if err != nil {
return nil, err
}
// Initialize the address pool for use. If we
// are using an imported account, loopback to
// the default account to create change.
var pool *addressPool
if account == waddrmgr.ImportedAddrAccount {
err := w.CheckAddressPoolsInitialized(waddrmgr.DefaultAccountNum)
if err != nil {
return nil, err
}
pool = w.addrPools[waddrmgr.DefaultAccountNum].internal
} else {
err := w.CheckAddressPoolsInitialized(account)
if err != nil {
return nil, err
}
pool = w.addrPools[account].internal
}
txSucceeded := false
pool.mutex.Lock()
defer pool.mutex.Unlock()
defer func() {
if txSucceeded {
pool.BatchFinish()
} else {
pool.BatchRollback()
}
}()
addrFunc := pool.getNewAddress
minconf := int32(1)
eligible, err := w.findEligibleOutputs(account, minconf, bs)
if err != nil {
return nil, err
}
if len(eligible) == 0 {
return nil, ErrNoOutsToConsolidate
}
txInCount := len(eligible)
if maxNumIns < txInCount {
txInCount = maxNumIns
}
// Get an initial fee estimate based on the number of selected inputs
// and added outputs, with no change.
szEst := estimateTxSize(txInCount, 1)
var feeIncrement dcrutil.Amount
feeIncrement = w.RelayFee()
feeEst := feeForSize(feeIncrement, szEst)
msgtx := wire.NewMsgTx()
// Add the txins using all the eligible outputs.
totalAdded := dcrutil.Amount(0)
count := 0
var forSigning []wtxmgr.Credit
for _, e := range eligible {
if count >= maxNumIns {
break
}
msgtx.AddTxIn(wire.NewTxIn(&e.OutPoint, nil))
totalAdded += e.Amount
forSigning = append(forSigning, e)
count++
}
outputAmt := totalAdded - feeEst
changeAddr, err := addrFunc()
if err != nil {
return nil, err
}
pkScript, err := txscript.PayToAddrScript(changeAddr)
if err != nil {
return nil, fmt.Errorf("cannot create txout script: %s", err)
}
msgtx.AddTxOut(wire.NewTxOut(int64(outputAmt), pkScript))
if err = signMsgTx(msgtx, forSigning, w.Manager,
w.chainParams); err != nil {
return nil, err
}
if err := validateMsgTxCredits(msgtx, forSigning); err != nil {
return nil, err
}
txSha, err := chainClient.SendRawTransaction(msgtx, w.AllowHighFees)
if err != nil {
return nil, err
}
txSucceeded = true
// Insert the transaction and credits into the transaction manager.
rec, err := w.insertIntoTxMgr(msgtx)
if err != nil {
return nil, err
}
err = w.insertCreditsIntoTxMgr(msgtx, rec)
if err != nil {
return nil, err
}
log.Infof("Successfully consolidated funds in transaction %v", txSha)
return txSha, nil
}
// compressEligible compresses all the utxos passed to it into a single
// output back to the wallet.
func (w *Wallet) compressEligible(eligible []wtxmgr.Credit) error {
chainClient, err := w.requireChainClient()
if err != nil {
return err
}
// Initialize the address pool for use.
var pool *addressPool
err = w.CheckAddressPoolsInitialized(waddrmgr.DefaultAccountNum)
if err != nil {
return err
}
pool = w.addrPools[waddrmgr.DefaultAccountNum].internal
if pool == nil {
log.Errorf("tried to use uninitialized pool for acct %v "+
"when attempting to make a transaction",
waddrmgr.DefaultAccountNum)
}
txSucceeded := false
pool.mutex.Lock()
defer pool.mutex.Unlock()
defer func() {
if txSucceeded {
pool.BatchFinish()
} else {
pool.BatchRollback()
}
}()
addrFunc := pool.getNewAddress
if len(eligible) == 0 {
return ErrNoOutsToConsolidate
}
txInCount := len(eligible)
// Get an initial fee estimate based on the number of selected inputs
// and added outputs, with no change.
szEst := estimateTxSize(txInCount, 1)
var feeIncrement dcrutil.Amount
feeIncrement = w.RelayFee()
feeEst := feeForSize(feeIncrement, szEst)
msgtx := wire.NewMsgTx()
// Add the txins using all the eligible outputs.
totalAdded := dcrutil.Amount(0)
var forSigning []wtxmgr.Credit
for _, e := range eligible {
msgtx.AddTxIn(wire.NewTxIn(&e.OutPoint, nil))
totalAdded += e.Amount
forSigning = append(forSigning, e)
}
outputAmt := totalAdded - feeEst
changeAddr, err := addrFunc()
if err != nil {
return err
}
pkScript, err := txscript.PayToAddrScript(changeAddr)
if err != nil {
return fmt.Errorf("cannot create txout script: %s", err)
}
msgtx.AddTxOut(wire.NewTxOut(int64(outputAmt), pkScript))
if err = signMsgTx(msgtx, forSigning, w.Manager,
w.chainParams); err != nil {
return err
}
if err := validateMsgTxCredits(msgtx, forSigning); err != nil {
return err
}
txSha, err := chainClient.SendRawTransaction(msgtx, w.AllowHighFees)
if err != nil {
return err
}
txSucceeded = true
// Insert the transaction and credits into the transaction manager.
rec, err := w.insertIntoTxMgr(msgtx)
if err != nil {
return err
}
err = w.insertCreditsIntoTxMgr(msgtx, rec)
if err != nil {
return err
}
log.Infof("Successfully consolidated funds in transaction %v", txSha)
return nil
}
// makeTicket creates a ticket from a split transaction output. It can optionally
// create a ticket that pays a fee to a pool if a pool input and pool address are
// passed.
func makeTicket(params *chaincfg.Params, inputPool *extendedOutPoint,
input *extendedOutPoint, addrVote dcrutil.Address, addrSubsidy dcrutil.Address,
ticketCost int64, addrPool dcrutil.Address) (*wire.MsgTx, error) {
mtx := wire.NewMsgTx()
if addrPool != nil && inputPool != nil {
txIn := wire.NewTxIn(inputPool.op, []byte{})
mtx.AddTxIn(txIn)
}
txIn := wire.NewTxIn(input.op, []byte{})
mtx.AddTxIn(txIn)
// Create a new script which pays to the provided address with an
// SStx tagged output.
pkScript, err := txscript.PayToSStx(addrVote)
if err != nil {
return nil, err
}
txOut := wire.NewTxOut(ticketCost, pkScript)
txOut.Version = txscript.DefaultScriptVersion
mtx.AddTxOut(txOut)
// Obtain the commitment amounts.
var amountsCommitted []int64
userSubsidyNullIdx := 0
if addrPool == nil {
_, amountsCommitted, err = stake.GetSStxNullOutputAmounts(
[]int64{input.amt}, []int64{0}, ticketCost)
if err != nil {
return nil, err
}
} else {
_, amountsCommitted, err = stake.GetSStxNullOutputAmounts(
[]int64{inputPool.amt, input.amt}, []int64{0, 0}, ticketCost)
if err != nil {
return nil, err
}
userSubsidyNullIdx = 1
}
// Zero value P2PKH addr.
zeroed := [20]byte{}
addrZeroed, err := dcrutil.NewAddressPubKeyHash(zeroed[:], params, 0)
if err != nil {
return nil, err
}
// 2. (Optional) If we're passed a pool address, make an extra
// commitment to the pool.
limits := uint16(defaultTicketFeeLimits)
if addrPool != nil {
pkScript, err = txscript.GenerateSStxAddrPush(addrPool,
dcrutil.Amount(amountsCommitted[0]), limits)
if err != nil {
return nil, fmt.Errorf("cannot create pool txout script: %s", err)
}
txout := wire.NewTxOut(int64(0), pkScript)
mtx.AddTxOut(txout)
// Create a new script which pays to the provided address with an
// SStx change tagged output.
pkScript, err = txscript.PayToSStxChange(addrZeroed)
if err != nil {
return nil, err
}
txOut = wire.NewTxOut(0, pkScript)
txOut.Version = txscript.DefaultScriptVersion
mtx.AddTxOut(txOut)
}
// 3. Create the commitment and change output paying to the user.
//
// Create an OP_RETURN push containing the pubkeyhash to send rewards to.
// Apply limits to revocations for fees while not allowing
// fees for votes.
pkScript, err = txscript.GenerateSStxAddrPush(addrSubsidy,
dcrutil.Amount(amountsCommitted[userSubsidyNullIdx]), limits)