forked from decred/dcrwallet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
createtx.go
1634 lines (1430 loc) · 51.3 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-2017 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 (
"context"
"encoding/binary"
"errors"
"fmt"
"time"
"github.com/decred/dcrd/blockchain"
"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/dcrutil"
"github.com/decred/dcrd/mempool"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrwallet/apperrors"
"github.com/decred/dcrwallet/wallet/internal/txsizes"
"github.com/decred/dcrwallet/wallet/txauthor"
"github.com/decred/dcrwallet/wallet/txrules"
"github.com/decred/dcrwallet/wallet/udb"
"github.com/decred/dcrwallet/walletdb"
)
// --------------------------------------------------------------------------------
// Constants and simple functions
const (
// 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
// maxStandardTxSize is the maximum size allowed for transactions that
// are considered standard and will therefore be relayed and considered
// for mining.
// TODO: import from dcrd.
maxStandardTxSize = 100000
// sanityVerifyFlags are the flags used to enable and disable features of
// the txscript engine used for sanity checking of transactions signed by
// the wallet.
sanityVerifyFlags = mempool.BaseStandardVerifyFlags
)
var (
// maxTxSize is the maximum size of a transaction we can
// build with the wallet.
maxTxSize = chaincfg.MainNetParams.MaxTxSize
)
// 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
// OutputSelectionAlgorithm specifies the algorithm to use when selecting outputs
// to construct a transaction.
type OutputSelectionAlgorithm uint
const (
// OutputSelectionAlgorithmDefault describes the default output selection
// algorithm. It is not optimized for any particular use case.
OutputSelectionAlgorithmDefault = iota
// OutputSelectionAlgorithmAll describes the output selection algorithm of
// picking every possible availble output. This is useful for sweeping.
OutputSelectionAlgorithmAll
)
// NewUnsignedTransaction constructs an unsigned transaction using unspent
// account outputs.
//
// The changeSource parameter is optional and can be nil. When nil, and if a
// change output should be added, an internal change address is created for the
// account.
func (w *Wallet) NewUnsignedTransaction(outputs []*wire.TxOut, relayFeePerKb dcrutil.Amount, account uint32, minConf int32,
algo OutputSelectionAlgorithm, changeSource txauthor.ChangeSource) (*txauthor.AuthoredTx, error) {
var authoredTx *txauthor.AuthoredTx
var changeSourceUpdates []func(walletdb.ReadWriteTx) error
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
_, tipHeight := w.TxStore.MainChainTip(txmgrNs)
if account != udb.ImportedAddrAccount {
lastAcct, err := w.Manager.LastAccount(addrmgrNs)
if err != nil {
return err
}
if account > lastAcct {
return apperrors.E{
ErrorCode: apperrors.ErrAccountNotFound,
Description: "account not found",
}
}
}
sourceImpl := w.TxStore.MakeInputSource(txmgrNs, addrmgrNs, account,
minConf, tipHeight)
var inputSource txauthor.InputSource
switch algo {
case OutputSelectionAlgorithmDefault:
inputSource = sourceImpl.SelectInputs
case OutputSelectionAlgorithmAll:
// Wrap the source with one that always fetches the max amount
// available and ignores any returned InputSourceErrors.
inputSource = func(dcrutil.Amount) (dcrutil.Amount, []*wire.TxIn, [][]byte, error) {
total, inputs, prevScripts, err := sourceImpl.SelectInputs(dcrutil.MaxAmount)
switch err.(type) {
case txauthor.InputSourceError:
err = nil
}
return total, inputs, prevScripts, err
}
default:
return fmt.Errorf("unrecognized output selection algorithm %d", algo)
}
if changeSource == nil {
persist := w.deferPersistReturnedChild(&changeSourceUpdates)
changeSource = w.changeSource(persist, account)
}
var err error
authoredTx, err = txauthor.NewUnsignedTransaction(outputs, relayFeePerKb,
inputSource, changeSource)
return err
})
if err != nil {
return nil, err
}
if len(changeSourceUpdates) != 0 {
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
for _, up := range changeSourceUpdates {
err := up(tx)
if err != nil {
return err
}
}
return nil
})
}
return authoredTx, err
}
// secretSource is an implementation of txauthor.SecretSource for the wallet's
// address manager.
type secretSource struct {
*udb.Manager
addrmgrNs walletdb.ReadBucket
doneFuncs []func()
}
func (s *secretSource) GetKey(addr dcrutil.Address) (chainec.PrivateKey, bool, error) {
privKey, done, err := s.Manager.PrivateKey(s.addrmgrNs, addr)
if err != nil {
return nil, false, err
}
s.doneFuncs = append(s.doneFuncs, done)
return privKey, true, nil
}
func (s *secretSource) GetScript(addr dcrutil.Address) ([]byte, error) {
script, done, err := s.Manager.RedeemScript(s.addrmgrNs, addr)
if err != nil {
return nil, err
}
s.doneFuncs = append(s.doneFuncs, done)
return script, nil
}
// 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(ns walletdb.ReadWriteBucket, msgTx *wire.MsgTx) (*udb.TxRecord, error) {
// Create transaction record and insert into the db.
rec, err := udb.NewTxRecordFromMsgTx(msgTx, time.Now())
if err != nil {
return nil, dcrjson.ErrInternal
}
return rec, w.TxStore.InsertMemPoolTx(ns, rec)
}
func (w *Wallet) insertCreditsIntoTxMgr(tx walletdb.ReadWriteTx,
msgTx *wire.MsgTx, rec *udb.TxRecord) error {
addrmgrNs := tx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := tx.ReadWriteBucket(wtxmgrNamespaceKey)
// 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(addrmgrNs, 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(txmgrNs, rec, nil,
uint32(i), ma.Internal(), ma.Account())
if err != nil {
return err
}
err = w.markUsedAddress(tx, ma)
if err != nil {
return err
}
log.Debugf("Marked address %v used", addr)
continue
}
// Missing addresses are skipped. Other errors should
// be propagated.
code := err.(apperrors.E).ErrorCode
if code != apperrors.ErrAddressNotFound {
return err
}
}
}
return nil
}
// insertMultisigOutIntoTxMgr inserts a multisignature output into the
// transaction store database.
func (w *Wallet) insertMultisigOutIntoTxMgr(ns walletdb.ReadWriteBucket, msgTx *wire.MsgTx,
index uint32) error {
// Create transaction record and insert into the db.
rec, err := udb.NewTxRecordFromMsgTx(msgTx, time.Now())
if err != nil {
return err
}
return w.TxStore.AddMultisigOut(ns, rec, nil, index)
}
// checkHighFees performs a high fee check if enabled and possible, returning an
// error if the transaction pays high fees.
func (w *Wallet) checkHighFees(totalInput dcrutil.Amount, tx *wire.MsgTx) error {
if w.AllowHighFees {
return nil
}
if !txrules.PaysHighFees(totalInput, tx) {
return nil
}
return apperrors.New(apperrors.ErrHighFees, "transaction pays exceedingly high fees")
}
// txToOutputs creates a transaction, selecting previous outputs from an account
// with no less than minconf confirmations, and creates a signed transaction
// that pays to each of the outputs.
func (w *Wallet) txToOutputs(outputs []*wire.TxOut, account uint32, minconf int32,
randomizeChangeIdx bool) (*txauthor.AuthoredTx, error) {
n, err := w.NetworkBackend()
if err != nil {
return nil, err
}
return w.txToOutputsInternal(outputs, account, minconf, n,
randomizeChangeIdx, w.RelayFee())
}
// txToOutputsInternal 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) txToOutputsInternal(outputs []*wire.TxOut, account uint32, minconf int32,
n NetworkBackend, randomizeChangeIdx bool, txFee dcrutil.Amount) (*txauthor.AuthoredTx, error) {
var atx *txauthor.AuthoredTx
var changeSourceUpdates []func(walletdb.ReadWriteTx) error
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
// Create the unsigned transaction.
_, tipHeight := w.TxStore.MainChainTip(txmgrNs)
inputSource := w.TxStore.MakeInputSource(txmgrNs, addrmgrNs, account,
minconf, tipHeight)
persist := w.deferPersistReturnedChild(&changeSourceUpdates)
changeSource := w.changeSource(persist, account)
var err error
atx, err = txauthor.NewUnsignedTransaction(outputs, txFee,
inputSource.SelectInputs, changeSource)
if err != nil {
return 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 atx.ChangeIndex >= 0 && randomizeChangeIdx {
atx.RandomizeChangePosition()
}
// Sign the transaction
secrets := &secretSource{Manager: w.Manager, addrmgrNs: addrmgrNs}
err = atx.AddAllInputScripts(secrets)
for _, done := range secrets.doneFuncs {
done()
}
return err
})
if err != nil {
return nil, err
}
// Ensure valid signatures were created.
err = validateMsgTx(atx.Tx, atx.PrevScripts)
if err != nil {
return nil, err
}
// Warn when spending UTXOs controlled by imported keys created change for
// the default account.
if atx.ChangeIndex >= 0 && account == udb.ImportedAddrAccount {
changeAmount := dcrutil.Amount(atx.Tx.TxOut[atx.ChangeIndex].Value)
log.Warnf("Spend from imported account produced change: moving"+
" %v from imported account into default account.", changeAmount)
}
err = w.checkHighFees(atx.TotalInput, atx.Tx)
if err != nil {
return nil, err
}
rec, err := udb.NewTxRecordFromMsgTx(atx.Tx, time.Now())
if err != nil {
return nil, err
}
// Use a single DB update to store and publish the transaction. If the
// transaction is rejected, the update is rolled back.
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
for _, up := range changeSourceUpdates {
err := up(dbtx)
if err != nil {
return err
}
}
// TODO: this can be improved by not using the same codepath as notified
// relevant transactions, since this does a lot of extra work.
err = w.processTransactionRecord(dbtx, rec, nil, nil)
if err != nil {
return err
}
return n.PublishTransaction(context.TODO(), atx.Tx)
})
if err != nil {
return nil, err
}
// Watch for future address usage.
err = walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
return w.watchFutureAddresses(dbtx)
})
if err != nil {
log.Errorf("Failed to watch for future address usage after publishing "+
"transaction: %v", err)
}
return atx, nil
}
// 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) {
var (
ctx *CreatedTx
addr dcrutil.Address
msScript []byte
)
err := walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
var err error
ctx, addr, msScript, err = w.txToMultisigInternal(dbtx,
account, amount, pubkeys, nRequired, minconf)
return err
})
return ctx, addr, msScript, err
}
func (w *Wallet) txToMultisigInternal(dbtx walletdb.ReadWriteTx, account uint32,
amount dcrutil.Amount, pubkeys []*dcrutil.AddressSecpPubKey, nRequired int8,
minconf int32) (*CreatedTx, dcrutil.Address, []byte, error) {
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)
txToMultisigError :=
func(err error) (*CreatedTx, dcrutil.Address, []byte, error) {
return nil, nil, nil, err
}
n, err := w.NetworkBackend()
if err != nil {
return txToMultisigError(err)
}
w.reorganizingLock.Lock()
reorg := w.reorganizing
w.reorganizingLock.Unlock()
if reorg {
return txToMultisigError(ErrBlockchainReorganizing)
}
// Get current block's height and hash.
_, topHeight := w.TxStore.MainChainTip(txmgrNs)
// 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.TestNet2Params:
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(dbtx, account, minconf,
amountRequired, topHeight)
if err != nil {
return txToMultisigError(err)
}
if eligible == nil {
return txToMultisigError(
fmt.Errorf("Not enough funds to send to multisig address"))
}
msgtx := wire.NewMsgTx()
scriptSizers := []txsizes.ScriptSizer{}
// Fill out inputs.
var forSigning []udb.Credit
totalInput := dcrutil.Amount(0)
for _, e := range eligible {
msgtx.AddTxIn(wire.NewTxIn(&e.OutPoint, nil))
totalInput += e.Amount
forSigning = append(forSigning, e)
scriptSizers = append(scriptSizers, txsizes.P2SHScriptSize)
}
// Insert a multi-signature output, then insert this P2SH
// hash160 into the address manager and the transaction
// manager.
msScript, err := txscript.MultiSigScript(pubkeys, int(nRequired))
if err != nil {
return txToMultisigError(err)
}
_, err = w.Manager.ImportScript(addrmgrNs, msScript)
if err != nil {
// We don't care if we've already used this address.
if err.(apperrors.E).ErrorCode != apperrors.ErrDuplicateAddress {
return txToMultisigError(err)
}
}
err = w.TxStore.InsertTxScript(txmgrNs, 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)
// 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 := txsizes.EstimateSerializeSize(scriptSizers, msgtx.TxOut, false)
feeEst := txrules.FeeForSerializeSize(w.RelayFee(), 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 {
pkScript, _, err := w.changeSource(w.persistReturnedChild(dbtx), account)()
if err != nil {
return txToMultisigError(err)
}
change := totalInput - (amount + feeEst)
msgtx.AddTxOut(wire.NewTxOut(int64(change), pkScript))
}
if err = signMsgTx(msgtx, forSigning, w.Manager, addrmgrNs,
w.chainParams); err != nil {
return txToMultisigError(err)
}
err = w.checkHighFees(totalInput, msgtx)
if err != nil {
return txToMultisigError(err)
}
err = n.PublishTransaction(context.TODO(), msgtx)
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
err = n.LoadTxFilter(context.TODO(), false, []dcrutil.Address{scAddr}, nil)
if err != nil {
return txToMultisigError(err)
}
err = w.insertMultisigOutIntoTxMgr(txmgrNs, 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,
sanityVerifyFlags, txscript.DefaultScriptVersion, nil)
if err != nil {
return fmt.Errorf("cannot create script engine: %s", err)
}
err = vm.Execute()
if err != nil {
prevOut := &tx.TxIn[i].PreviousOutPoint
sigScript := tx.TxIn[i].SignatureScript
return fmt.Errorf("script execution errored: %s "+
"(spending outpoint %v pkscript %x with sigscript %x)",
err, prevOut, prevScript, sigScript)
}
}
return nil
}
func validateMsgTxCredits(tx *wire.MsgTx, prevCredits []udb.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, changeAddr dcrutil.Address) (*chainhash.Hash, error) {
var hash *chainhash.Hash
err := walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
var err error
hash, err = w.compressWalletInternal(dbtx, maxNumIns, account, changeAddr)
return err
})
return hash, err
}
func (w *Wallet) compressWalletInternal(dbtx walletdb.ReadWriteTx, maxNumIns int, account uint32,
changeAddr dcrutil.Address) (*chainhash.Hash, error) {
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
txmgrNs := dbtx.ReadWriteBucket(wtxmgrNamespaceKey)
n, err := w.NetworkBackend()
if err != nil {
return nil, err
}
w.reorganizingLock.Lock()
reorg := w.reorganizing
w.reorganizingLock.Unlock()
if reorg {
return nil, ErrBlockchainReorganizing
}
// Get current block's height
_, tipHeight := w.TxStore.MainChainTip(txmgrNs)
minconf := int32(1)
eligible, err := w.findEligibleOutputs(dbtx, account, minconf, tipHeight)
if err != nil {
return nil, err
}
if len(eligible) == 0 {
return nil, ErrNoOutsToConsolidate
}
// Check if output address is default, and generate a new adress if needed
if changeAddr == nil {
changeAddr, err = w.newChangeAddress(w.persistReturnedChild(dbtx), account)
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 := wire.NewMsgTx()
msgtx.AddTxOut(wire.NewTxOut(0, pkScript))
maximumTxSize := maxTxSize
if w.chainParams.Net == wire.MainNet {
maximumTxSize = maxStandardTxSize
}
// Add the txins using all the eligible outputs.
totalAdded := dcrutil.Amount(0)
scriptSizers := []txsizes.ScriptSizer{}
count := 0
var forSigning []udb.Credit
for _, e := range eligible {
if count >= maxNumIns {
break
}
// Add the size of a wire.OutPoint
if msgtx.SerializeSize() > maximumTxSize {
break
}
msgtx.AddTxIn(wire.NewTxIn(&e.OutPoint, nil))
totalAdded += e.Amount
forSigning = append(forSigning, e)
scriptSizers = append(scriptSizers, txsizes.P2PKHScriptSize)
count++
}
// Get an initial fee estimate based on the number of selected inputs
// and added outputs, with no change.
szEst := txsizes.EstimateSerializeSize(scriptSizers, msgtx.TxOut, false)
feeEst := txrules.FeeForSerializeSize(w.RelayFee(), szEst)
msgtx.TxOut[0].Value = int64(totalAdded - feeEst)
if err = signMsgTx(msgtx, forSigning, w.Manager, addrmgrNs,
w.chainParams); err != nil {
return nil, err
}
if err := validateMsgTxCredits(msgtx, forSigning); err != nil {
return nil, err
}
err = w.checkHighFees(totalAdded, msgtx)
if err != nil {
return nil, err
}
err = n.PublishTransaction(context.TODO(), msgtx)
if err != nil {
return nil, err
}
// Insert the transaction and credits into the transaction manager.
rec, err := w.insertIntoTxMgr(txmgrNs, msgtx)
if err != nil {
return nil, err
}
err = w.insertCreditsIntoTxMgr(dbtx, msgtx, rec)
if err != nil {
return nil, err
}
txHash := msgtx.TxHash()
log.Infof("Successfully consolidated funds in transaction %v", &txHash)
return &txHash, 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.SStxNullOutputAmounts(
[]int64{input.amt}, []int64{0}, ticketCost)
if err != nil {
return nil, err
}
} else {
_, amountsCommitted, err = stake.SStxNullOutputAmounts(
[]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)
if err != nil {
return nil, fmt.Errorf("cannot create user 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)
// Make sure we generated a valid SStx.
if err := stake.CheckSStx(mtx); err != nil {
return nil, err
}
return mtx, nil
}
// purchaseTickets indicates to the wallet that a ticket should be purchased
// using all currently available funds. The ticket address parameter in the
// request can be nil in which case the ticket address associated with the
// wallet instance will be used. Also, when the spend limit in the request is
// greater than or equal to 0, tickets that cost more than that limit will
// return an error that not enough funds are available.
func (w *Wallet) purchaseTickets(req purchaseTicketRequest) ([]*chainhash.Hash, error) {
n, err := w.NetworkBackend()
if err != nil {
return nil, err
}
// Ensure the minimum number of required confirmations is positive.
if req.minConf < 0 {
return nil, fmt.Errorf("need positive minconf")
}
// Need a positive or zero expiry that is higher than the next block to
// generate.
if req.expiry < 0 {
return nil, fmt.Errorf("need positive expiry")
}
// Perform a sanity check on expiry.
var tipHeight int32
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
ns := tx.ReadBucket(wtxmgrNamespaceKey)
_, tipHeight = w.TxStore.MainChainTip(ns)
return nil
})
if err != nil {
return nil, err
}
if req.expiry <= tipHeight+1 && req.expiry > 0 {
return nil, fmt.Errorf("need expiry that is beyond next height ("+
"given: %v, next height %v)", req.expiry, tipHeight+1)
}
// addrFunc returns a change address.
addrFunc := w.newChangeAddress
if w.addressReuse {
xpub := w.addressBuffers[udb.DefaultAccountNum].albExternal.branchXpub
addr, err := deriveChildAddress(xpub, 0, w.chainParams)
addrFunc = func(persistReturnedChildFunc, uint32) (dcrutil.Address, error) {
return addr, err
}
}
// Fetch a new address for creating a split transaction. Then,
// make a split transaction that contains exact outputs for use
// in ticket generation. Cache its hash to use below when
// generating a ticket. The account balance is checked first
// in case there is not enough money to generate the split
// even without fees.
// TODO This can still sometimes fail if the split amount
// required plus fees for the split is larger than the
// balance we have, wasting an address. In the future,
// address this better and prevent address burning.
account := req.account
// Get the current ticket price.
ticketPrice, err := n.StakeDifficulty(context.TODO())
if err != nil {
return nil, err
}
// Ensure the ticket price does not exceed the spend limit if set.
if req.spendLimit >= 0 && ticketPrice > req.spendLimit {
return nil, ErrSStxPriceExceedsSpendLimit
}
// Try to get the pool address from the request. If none exists
// in the request, try to get the global pool address. Then do
// the same for pool fees, but check sanity too.
poolAddress := req.poolAddress
if poolAddress == nil {
poolAddress = w.PoolAddress()
}
poolFees := req.poolFees
if poolFees == 0.0 {
poolFees = w.PoolFees()
}
if poolAddress != nil && poolFees == 0.0 {
return nil, fmt.Errorf("pool address given, but pool fees not set")
}
// Make sure that we have enough funds. Calculate different
// ticket required amounts depending on whether or not a
// pool output is needed. If the ticket fee increment is
// unset in the request, use the global ticket fee increment.
var neededPerTicket, ticketFee dcrutil.Amount
ticketFeeIncrement := req.ticketFee
if ticketFeeIncrement == 0 {
ticketFeeIncrement = w.TicketFeeIncrement()
}
if poolAddress == nil {
ticketFee = (ticketFeeIncrement * singleInputTicketSize) /
1000
neededPerTicket = ticketFee + ticketPrice
} else {
ticketFee = (ticketFeeIncrement * doubleInputTicketSize) /
1000
neededPerTicket = ticketFee + ticketPrice
}
// If we need to calculate the amount for a pool fee percentage,
// do so now.
var poolFeeAmt dcrutil.Amount
if poolAddress != nil {
poolFeeAmt = txrules.StakePoolTicketFee(ticketPrice, ticketFee,
tipHeight, poolFees, w.ChainParams())
if poolFeeAmt >= ticketPrice {
return nil, fmt.Errorf("pool fee amt of %v >= than current "+
"ticket price of %v", poolFeeAmt, ticketPrice)
}
}
// Make sure this doesn't over spend based on the balance to
// maintain. This component of the API is inaccessible to the
// end user through the legacy RPC, so it should only ever be
// set by internal calls e.g. automatic ticket purchase.
if req.minBalance > 0 {