-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathcreatetx.go
2184 lines (1956 loc) · 65 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-2024 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"
"sort"
"time"
"decred.org/dcrwallet/v5/deployments"
"decred.org/dcrwallet/v5/errors"
"decred.org/dcrwallet/v5/wallet/txauthor"
"decred.org/dcrwallet/v5/wallet/txrules"
"decred.org/dcrwallet/v5/wallet/txsizes"
"decred.org/dcrwallet/v5/wallet/udb"
"decred.org/dcrwallet/v5/wallet/walletdb"
"github.com/decred/dcrd/blockchain/stake/v5"
blockchain "github.com/decred/dcrd/blockchain/standalone/v2"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/chaincfg/v3"
"github.com/decred/dcrd/crypto/rand"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrutil/v4"
"github.com/decred/dcrd/mixing/mixclient"
"github.com/decred/dcrd/txscript/v4"
"github.com/decred/dcrd/txscript/v4/sign"
"github.com/decred/dcrd/txscript/v4/stdaddr"
"github.com/decred/dcrd/txscript/v4/stdscript"
"github.com/decred/dcrd/wire"
)
// --------------------------------------------------------------------------------
// Constants and simple functions
const (
revocationFeeLimit = 1 << 14
// 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 = txscript.ScriptDiscourageUpgradableNops |
txscript.ScriptVerifyCleanStack |
txscript.ScriptVerifyCheckLockTimeVerify |
txscript.ScriptVerifyCheckSequenceVerify |
txscript.ScriptVerifyTreasury
)
// Input provides transaction inputs referencing spendable outputs.
type Input struct {
OutPoint wire.OutPoint
PrevOut wire.TxOut
}
// --------------------------------------------------------------------------------
// 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 available output. This is useful for sweeping.
OutputSelectionAlgorithmAll
)
// NewUnsignedTransaction constructs an unsigned transaction using unspent
// account outputs.
//
// The changeSource and inputSource parameters are optional and can be nil.
// When the changeSource is nil and change output should be added, an internal
// change address is created for the account. When the inputSource is nil,
// the inputs will be selected by the wallet.
func (w *Wallet) NewUnsignedTransaction(ctx context.Context, outputs []*wire.TxOut,
relayFeePerKb dcrutil.Amount, account uint32, minConf int32,
algo OutputSelectionAlgorithm, changeSource txauthor.ChangeSource, inputSource txauthor.InputSource) (*txauthor.AuthoredTx, error) {
const op errors.Op = "wallet.NewUnsignedTransaction"
ignoreInput := func(op *wire.OutPoint) bool {
_, ok := w.lockedOutpoints[outpoint{op.Hash, op.Index}]
return ok
}
defer w.lockedOutpointMu.Unlock()
w.lockedOutpointMu.Lock()
var authoredTx *txauthor.AuthoredTx
var changeSourceUpdates []func(walletdb.ReadWriteTx) error
err := walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
_, tipHeight := w.txStore.MainChainTip(dbtx)
if account != udb.ImportedAddrAccount {
lastAcct, err := w.manager.LastAccount(addrmgrNs)
if err != nil {
return err
}
if account > lastAcct {
return errors.E(errors.NotExist, "missing account")
}
}
if inputSource == nil {
sourceImpl := w.txStore.MakeInputSource(dbtx, account,
minConf, tipHeight, ignoreInput)
switch algo {
case OutputSelectionAlgorithmDefault:
inputSource = sourceImpl.SelectInputs
case OutputSelectionAlgorithmAll:
// Wrap the source with one that always fetches the max amount
// available and ignores insufficient balance issues.
inputSource = func(dcrutil.Amount) (*txauthor.InputDetail, error) {
inputDetail, err := sourceImpl.SelectInputs(dcrutil.MaxAmount)
if errors.Is(err, errors.InsufficientBalance) {
err = nil
}
return inputDetail, err
}
default:
return errors.E(errors.Invalid,
errors.Errorf("unknown output selection algorithm %v", algo))
}
}
if changeSource == nil {
changeSource = &p2PKHChangeSource{
persist: w.deferPersistReturnedChild(ctx, &changeSourceUpdates),
account: account,
wallet: w,
ctx: context.Background(),
}
}
var err error
authoredTx, err = txauthor.NewUnsignedTransaction(outputs, relayFeePerKb,
inputSource, changeSource, w.chainParams.MaxTxSize)
if err != nil {
return err
}
return nil
})
if err != nil {
return nil, errors.E(op, err)
}
if len(changeSourceUpdates) != 0 {
err := walletdb.Update(ctx, w.db, func(tx walletdb.ReadWriteTx) error {
for _, up := range changeSourceUpdates {
err := up(tx)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return nil, errors.E(op, err)
}
}
return authoredTx, nil
}
// 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 stdaddr.Address) ([]byte, dcrec.SignatureType, bool, error) {
privKey, done, err := s.Manager.PrivateKey(s.addrmgrNs, addr)
if err != nil {
return nil, 0, false, err
}
s.doneFuncs = append(s.doneFuncs, done)
return privKey.Serialize(), dcrec.STEcdsaSecp256k1, true, nil
}
func (s *secretSource) GetScript(addr stdaddr.Address) ([]byte, error) {
return s.Manager.RedeemScript(s.addrmgrNs, addr)
}
// SecretsSource is an implementation of txauthor.SecretsSource querying the
// wallet's address manager.
//
// The Close method must be called after the SecretsSource usage is over.
type SecretsSource struct {
wallet *Wallet
dbtx walletdb.ReadTx
doneFuncs []func()
}
// SecretsSource returns a txauthor.SecretsSource implementor using the wallet
// as the backing store for keys and scripts.
func (w *Wallet) SecretsSource() (*SecretsSource, error) {
dbtx, err := w.db.BeginReadTx()
if err != nil {
return nil, err
}
return &SecretsSource{wallet: w, dbtx: dbtx}, nil
}
// ChainParams returns the chain parameters.
func (s *SecretsSource) ChainParams() *chaincfg.Params {
return s.wallet.chainParams
}
// GetKey provides the private key associated with an address.
func (s *SecretsSource) GetKey(addr stdaddr.Address) (key []byte, sigType dcrec.SignatureType, compressed bool, err error) {
addrmgrNs := s.dbtx.ReadBucket(waddrmgrNamespaceKey)
privKey, done, err := s.wallet.manager.PrivateKey(addrmgrNs, addr)
if err != nil {
return
}
s.doneFuncs = append(s.doneFuncs, done)
return privKey.Serialize(), dcrec.STEcdsaSecp256k1, true, nil
}
// GetScript provides the redeem script for a P2SH address.
func (s *SecretsSource) GetScript(addr stdaddr.Address) ([]byte, error) {
addrmgrNs := s.dbtx.ReadBucket(waddrmgrNamespaceKey)
return s.wallet.manager.RedeemScript(addrmgrNs, addr)
}
// Close finishes the SecretsSource usage by releasing all secret key material
// and closing the underlying database transaction.
func (s *SecretsSource) Close() error {
for _, f := range s.doneFuncs {
f()
}
s.doneFuncs = nil
err := s.dbtx.Rollback()
if err == nil {
s.dbtx = nil
}
return err
}
// CreatedTx holds the state of a newly-created transaction and the change
// output (if one was added).
type CreatedTx struct {
MsgTx *wire.MsgTx
ChangeAddr stdaddr.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(dbtx walletdb.ReadWriteTx, 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, err
}
err = w.txStore.InsertMemPoolTx(dbtx, rec)
if err != nil {
return nil, err
}
return rec, nil
}
// insertCreditsIntoTxMgr inserts the wallet credits from msgTx to the wallet's
// transaction store. It assumes msgTx is a regular transaction, which will
// cause balance issues if this is called from a code path where msgtx is not
// guaranteed to be a regular tx.
func (w *Wallet) insertCreditsIntoTxMgr(op errors.Op, dbtx walletdb.ReadWriteTx, msgTx *wire.MsgTx, rec *udb.TxRecord) error {
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
// 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 := stdscript.ExtractAddrs(output.Version, output.PkScript, w.chainParams)
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(dbtx, rec, nil,
uint32(i), ma.Internal(), ma.Account())
if err != nil {
return errors.E(op, err)
}
err = w.markUsedAddress(op, dbtx, ma)
if err != nil {
return err
}
log.Debugf("Marked address %v used", addr)
continue
}
// Missing addresses are skipped. Other errors should
// be propagated.
if !errors.Is(err, errors.NotExist) {
return errors.E(op, err)
}
}
}
return nil
}
// insertMultisigOutIntoTxMgr inserts a multisignature output into the
// transaction store database.
func (w *Wallet) insertMultisigOutIntoTxMgr(dbtx walletdb.ReadWriteTx, 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(dbtx, 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 errors.E(errors.Policy, "high fee")
}
return nil
}
// publishAndWatch publishes an authored transaction to the network and begins watching for
// relevant transactions.
func (w *Wallet) publishAndWatch(ctx context.Context, op errors.Op, n NetworkBackend, tx *wire.MsgTx,
watch []wire.OutPoint) error {
if n == nil {
var err error
n, err = w.NetworkBackend()
if err != nil {
return errors.E(op, err)
}
}
err := n.PublishTransactions(ctx, tx)
if err != nil {
hash := tx.TxHash()
log.Errorf("Abandoning transaction %v which failed to publish", &hash)
if err := w.AbandonTransaction(ctx, &hash); err != nil {
log.Errorf("Cannot abandon %v: %v", &hash, err)
}
return errors.E(op, err)
}
// Watch for future relevant transactions.
_, err = w.watchHDAddrs(ctx, false, n)
if err != nil {
log.Errorf("Failed to watch for future address usage after publishing "+
"transaction: %v", err)
}
if len(watch) > 0 {
err := n.LoadTxFilter(ctx, false, nil, watch)
if err != nil {
log.Errorf("Failed to watch outpoints: %v", err)
}
}
return nil
}
type authorTx struct {
outputs []*wire.TxOut
account uint32
changeAccount uint32
minconf int32
randomizeChangeIdx bool
txFee dcrutil.Amount
dontSignTx bool
isTreasury bool
atx *txauthor.AuthoredTx
changeSourceUpdates []func(walletdb.ReadWriteTx) error
watch []wire.OutPoint
}
// authorTx creates a (typically signed) transaction which includes each output
// from outputs. Previous outputs to redeem 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.
func (w *Wallet) authorTx(ctx context.Context, op errors.Op, a *authorTx) error {
var unlockOutpoints []*wire.OutPoint
defer func() {
for _, op := range unlockOutpoints {
delete(w.lockedOutpoints, outpoint{op.Hash, op.Index})
}
w.lockedOutpointMu.Unlock()
}()
ignoreInput := func(op *wire.OutPoint) bool {
_, ok := w.lockedOutpoints[outpoint{op.Hash, op.Index}]
return ok
}
w.lockedOutpointMu.Lock()
var atx *txauthor.AuthoredTx
var changeSourceUpdates []func(walletdb.ReadWriteTx) error
err := walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
// Create the unsigned transaction.
_, tipHeight := w.txStore.MainChainTip(dbtx)
inputSource := w.txStore.MakeInputSource(dbtx, a.account,
a.minconf, tipHeight, ignoreInput)
var changeSource txauthor.ChangeSource
if a.isTreasury {
changeSource = &p2PKHTreasuryChangeSource{
persist: w.deferPersistReturnedChild(ctx,
&changeSourceUpdates),
account: a.changeAccount,
wallet: w,
ctx: ctx,
}
} else {
changeSource = &p2PKHChangeSource{
persist: w.deferPersistReturnedChild(ctx,
&changeSourceUpdates),
account: a.changeAccount,
wallet: w,
ctx: ctx,
gapPolicy: gapPolicyWrap,
}
}
var err error
atx, err = txauthor.NewUnsignedTransaction(a.outputs, a.txFee,
inputSource.SelectInputs, changeSource,
w.chainParams.MaxTxSize)
if err != nil {
return err
}
for _, in := range atx.Tx.TxIn {
prev := &in.PreviousOutPoint
w.lockedOutpoints[outpoint{prev.Hash, prev.Index}] = struct{}{}
unlockOutpoints = append(unlockOutpoints, prev)
}
// 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 && a.randomizeChangeIdx {
atx.RandomizeChangePosition()
}
// TADDs need to use version 3 txs.
if a.isTreasury {
// This check ensures that if NewUnsignedTransaction is
// updated to generate a different transaction version
// we error out loudly instead of failing to validate
// in some obscure way.
//
// TODO: maybe isTreasury should be passed into
// NewUnsignedTransaction?
if atx.Tx.Version != wire.TxVersion {
return errors.E(op, "violated assumption: "+
"expected unsigned tx to be version 1")
}
atx.Tx.Version = wire.TxVersionTreasury
}
if !a.dontSignTx {
// 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 errors.E(op, err)
}
// Warn when spending UTXOs controlled by imported keys created change for
// the default account.
if atx.ChangeIndex >= 0 && a.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 errors.E(op, err)
}
if !a.dontSignTx {
// Ensure valid signatures were created.
err = validateMsgTx(op, atx.Tx, atx.PrevScripts)
if err != nil {
return errors.E(op, err)
}
}
a.atx = atx
a.changeSourceUpdates = changeSourceUpdates
return nil
}
// recordAuthoredTx records an authored transaction to the wallet's database. It
// also updates the database for change addresses used by the new transaction.
//
// As a side effect of recording the transaction to the wallet, clients
// subscribed to new tx notifications will also be notified of the new
// transaction.
func (w *Wallet) recordAuthoredTx(ctx context.Context, op errors.Op, a *authorTx) error {
rec, err := udb.NewTxRecordFromMsgTx(a.atx.Tx, time.Now())
if err != nil {
return errors.E(op, err)
}
w.lockedOutpointMu.Lock()
defer w.lockedOutpointMu.Unlock()
// To avoid a race between publishing a transaction and potentially opening
// a database view during PublishTransaction, the update must be committed
// before publishing the transaction to the network.
var watch []wire.OutPoint
err = walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
for _, up := range a.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.
var err error
watch, err = w.processTransactionRecord(ctx, dbtx, rec, nil, nil)
return err
})
if err != nil {
return errors.E(op, err)
}
a.watch = watch
return nil
}
// txToMultisig spends funds to a multisig output, partially signs the
// transaction, then returns fund
func (w *Wallet) txToMultisig(ctx context.Context, op errors.Op, account uint32, amount dcrutil.Amount, pubkeys [][]byte,
nRequired int8, minconf int32) (*CreatedTx, stdaddr.Address, []byte, error) {
defer w.lockedOutpointMu.Unlock()
w.lockedOutpointMu.Lock()
var created *CreatedTx
var addr stdaddr.Address
var msScript []byte
err := walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
var err error
created, addr, msScript, err = w.txToMultisigInternal(ctx, op, dbtx,
account, amount, pubkeys, nRequired, minconf)
return err
})
if err != nil {
return nil, nil, nil, errors.E(op, err)
}
return created, addr, msScript, nil
}
func (w *Wallet) txToMultisigInternal(ctx context.Context, op errors.Op, dbtx walletdb.ReadWriteTx, account uint32, amount dcrutil.Amount,
pubkeys [][]byte, nRequired int8, minconf int32) (*CreatedTx, stdaddr.Address, []byte, error) {
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
txToMultisigError := func(err error) (*CreatedTx, stdaddr.Address, []byte, error) {
return nil, nil, nil, err
}
n, err := w.NetworkBackend()
if err != nil {
return txToMultisigError(err)
}
// Get current block's height and hash.
_, topHeight := w.txStore.MainChainTip(dbtx)
// Add in some extra for fees. TODO In the future, make a better
// fee estimator.
var feeEstForTx dcrutil.Amount
switch w.chainParams.Net {
case wire.MainNet:
feeEstForTx = 5e7
case 0x48e7a065: // testnet2
feeEstForTx = 5e7
case wire.TestNet3:
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.
const minAmount = 0
const maxResults = 0
eligible, err := w.findEligibleOutputsAmount(dbtx, account, minconf,
amountRequired, topHeight, minAmount, maxResults)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
if eligible == nil {
return txToMultisigError(errors.E(op, "not enough funds to send to multisig address"))
}
for i := range eligible {
op := &eligible[i].OutPoint
w.lockedOutpoints[outpoint{op.Hash, op.Index}] = struct{}{}
}
defer func() {
for i := range eligible {
op := &eligible[i].OutPoint
delete(w.lockedOutpoints, outpoint{op.Hash, op.Index})
}
}()
msgtx := wire.NewMsgTx()
scriptSizes := make([]int, 0, len(eligible))
// Fill out inputs.
forSigning := make([]Input, 0, len(eligible))
totalInput := dcrutil.Amount(0)
for _, e := range eligible {
txIn := wire.NewTxIn(&e.OutPoint, e.PrevOut.Value, nil)
msgtx.AddTxIn(txIn)
totalInput += dcrutil.Amount(e.PrevOut.Value)
forSigning = append(forSigning, e)
scriptSizes = append(scriptSizes, txsizes.RedeemP2SHSigScriptSize)
}
// Insert a multi-signature output, then insert this P2SH
// hash160 into the address manager and the transaction
// manager.
msScript, err := stdscript.MultiSigScriptV0(int(nRequired), pubkeys...)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
_, err = w.manager.ImportScript(addrmgrNs, msScript)
if err != nil {
// We don't care if we've already used this address.
if !errors.Is(err, errors.Exist) {
return txToMultisigError(errors.E(op, err))
}
}
scAddr, err := stdaddr.NewAddressScriptHashV0(msScript, w.chainParams)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
vers, p2shScript := scAddr.PaymentScript()
txOut := &wire.TxOut{
Value: int64(amount),
PkScript: p2shScript,
Version: vers,
}
msgtx.AddTxOut(txOut)
// Add change if we need it.
changeSize := 0
if totalInput > amount+feeEstForTx {
changeSize = txsizes.P2PKHPkScriptSize
}
feeSize := txsizes.EstimateSerializeSize(scriptSizes, msgtx.TxOut, changeSize)
feeEst := txrules.FeeForSerializeSize(w.RelayFee(), feeSize)
if totalInput < amount+feeEst {
return txToMultisigError(errors.E(op, errors.InsufficientBalance))
}
if totalInput > amount+feeEst {
changeSource := p2PKHChangeSource{
persist: w.persistReturnedChild(ctx, dbtx),
account: account,
wallet: w,
ctx: ctx,
}
pkScript, vers, err := changeSource.Script()
if err != nil {
return txToMultisigError(err)
}
change := totalInput - (amount + feeEst)
msgtx.AddTxOut(&wire.TxOut{
Value: int64(change),
Version: vers,
PkScript: pkScript,
})
}
err = w.signP2PKHMsgTx(msgtx, forSigning, addrmgrNs)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
err = w.checkHighFees(totalInput, msgtx)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
err = n.PublishTransactions(ctx, msgtx)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
// Request updates from dcrd for new transactions sent to this
// script hash address.
err = n.LoadTxFilter(ctx, false, []stdaddr.Address{scAddr}, nil)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
err = w.insertMultisigOutIntoTxMgr(dbtx, msgtx, 0)
if err != nil {
return txToMultisigError(errors.E(op, err))
}
created := &CreatedTx{
MsgTx: msgtx,
ChangeAddr: nil,
ChangeIndex: -1,
}
return created, 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(op errors.Op, tx *wire.MsgTx, prevScripts [][]byte) error {
for i, prevScript := range prevScripts {
vm, err := txscript.NewEngine(prevScript, tx, i,
sanityVerifyFlags, scriptVersionAssumed, nil)
if err != nil {
return errors.E(op, err)
}
err = vm.Execute()
if err != nil {
prevOut := &tx.TxIn[i].PreviousOutPoint
sigScript := tx.TxIn[i].SignatureScript
log.Errorf("Script validation failed (outpoint %v pkscript %x sigscript %x): %v",
prevOut, prevScript, sigScript, err)
return errors.E(op, errors.ScriptFailure, err)
}
}
return nil
}
func creditScripts(credits []Input) [][]byte {
scripts := make([][]byte, 0, len(credits))
for _, c := range credits {
scripts = append(scripts, c.PrevOut.PkScript)
}
return scripts
}
// compressWallet compresses all the utxos in a wallet into a single change
// address. For use when it becomes dusty.
func (w *Wallet) compressWallet(ctx context.Context, op errors.Op, maxNumIns int, account uint32, changeAddr stdaddr.Address) (*chainhash.Hash, error) {
defer w.lockedOutpointMu.Unlock()
w.lockedOutpointMu.Lock()
var hash *chainhash.Hash
err := walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
var err error
hash, err = w.compressWalletInternal(ctx, op, dbtx, maxNumIns, account, changeAddr)
return err
})
if err != nil {
return nil, errors.E(op, err)
}
return hash, nil
}
func (w *Wallet) compressWalletInternal(ctx context.Context, op errors.Op, dbtx walletdb.ReadWriteTx, maxNumIns int, account uint32,
changeAddr stdaddr.Address) (*chainhash.Hash, error) {
addrmgrNs := dbtx.ReadWriteBucket(waddrmgrNamespaceKey)
n, err := w.NetworkBackend()
if err != nil {
return nil, errors.E(op, err)
}
// Get current block's height
_, tipHeight := w.txStore.MainChainTip(dbtx)
minconf := int32(1)
eligible, err := w.findEligibleOutputs(dbtx, account, minconf, tipHeight)
if err != nil {
return nil, errors.E(op, err)
}
if len(eligible) <= 1 {
return nil, errors.E(op, "too few outputs to consolidate")
}
for i := range eligible {
op := eligible[i].OutPoint
w.lockedOutpoints[outpoint{op.Hash, op.Index}] = struct{}{}
}
defer func() {
for i := range eligible {
op := &eligible[i].OutPoint
delete(w.lockedOutpoints, outpoint{op.Hash, op.Index})
}
}()
// Check if output address is default, and generate a new address if needed
if changeAddr == nil {
const accountName = "" // not used, so can be faked.
changeAddr, err = w.newChangeAddress(ctx, op, w.persistReturnedChild(ctx, dbtx),
accountName, account, gapPolicyIgnore)
if err != nil {
return nil, errors.E(op, err)
}
}
vers, pkScript := changeAddr.PaymentScript()
msgtx := wire.NewMsgTx()
msgtx.AddTxOut(&wire.TxOut{
Value: 0,
PkScript: pkScript,
Version: vers,
})
maximumTxSize := w.chainParams.MaxTxSize
if w.chainParams.Net == wire.MainNet {
maximumTxSize = maxStandardTxSize
}
// Add the txins using all the eligible outputs.
totalAdded := dcrutil.Amount(0)
scriptSizes := make([]int, 0, maxNumIns)
forSigning := make([]Input, 0, maxNumIns)
count := 0
for _, e := range eligible {
if count >= maxNumIns {
break
}
// Add the size of a wire.OutPoint
if msgtx.SerializeSize() > maximumTxSize {
break
}
txIn := wire.NewTxIn(&e.OutPoint, e.PrevOut.Value, nil)
msgtx.AddTxIn(txIn)
totalAdded += dcrutil.Amount(e.PrevOut.Value)
forSigning = append(forSigning, e)
scriptSizes = append(scriptSizes, txsizes.RedeemP2PKHSigScriptSize)
count++
}
// Get an initial fee estimate based on the number of selected inputs
// and added outputs, with no change.
szEst := txsizes.EstimateSerializeSize(scriptSizes, msgtx.TxOut, 0)
feeEst := txrules.FeeForSerializeSize(w.RelayFee(), szEst)
msgtx.TxOut[0].Value = int64(totalAdded - feeEst)
err = w.signP2PKHMsgTx(msgtx, forSigning, addrmgrNs)
if err != nil {
return nil, errors.E(op, err)
}
err = validateMsgTx(op, msgtx, creditScripts(forSigning))
if err != nil {
return nil, errors.E(op, err)
}
err = w.checkHighFees(totalAdded, msgtx)
if err != nil {
return nil, errors.E(op, err)
}
err = n.PublishTransactions(ctx, msgtx)
if err != nil {
return nil, errors.E(op, err)
}
// Insert the transaction and credits into the transaction manager.
rec, err := w.insertIntoTxMgr(dbtx, msgtx)
if err != nil {
return nil, errors.E(op, err)
}
err = w.insertCreditsIntoTxMgr(op, 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.
func makeTicket(params *chaincfg.Params, input *Input, addrVote stdaddr.StakeAddress,
addrSubsidy stdaddr.StakeAddress, ticketCost int64) (*wire.MsgTx, error) {
mtx := wire.NewMsgTx()
txIn := wire.NewTxIn(&input.OutPoint, input.PrevOut.Value, []byte{})
mtx.AddTxIn(txIn)
// Create a new script which pays to the provided address with an
// SStx tagged output.
if addrVote == nil {
return nil, errors.E(errors.Invalid, "nil vote address")
}
vers, pkScript := addrVote.VotingRightsScript()
txOut := &wire.TxOut{
Value: ticketCost,
PkScript: pkScript,
Version: vers,
}
mtx.AddTxOut(txOut)
// Obtain the commitment amounts.
var amountsCommitted []int64
const userSubsidyNullIdx = 0
var err error
_, amountsCommitted, err = stake.SStxNullOutputAmounts(
[]int64{input.PrevOut.Value}, []int64{0}, ticketCost)
if err != nil {
return nil, err
}
// Zero value P2PKH addr.
zeroed := [20]byte{}
addrZeroed, err := stdaddr.NewAddressPubKeyHashEcdsaSecp256k1V0(zeroed[:], params)
if err != nil {
return nil, err
}
// 2. 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.
vers, pkScript = addrSubsidy.RewardCommitmentScript(
amountsCommitted[userSubsidyNullIdx], 0, revocationFeeLimit)
txout := &wire.TxOut{
Value: 0,
PkScript: pkScript,
Version: vers,
}
mtx.AddTxOut(txout)
// Create a new script which pays to the provided address with an
// SStx change tagged output.
vers, pkScript = addrZeroed.StakeChangeScript()
txOut = &wire.TxOut{
Value: 0,
PkScript: pkScript,
Version: vers,
}
mtx.AddTxOut(txOut)
// Make sure we generated a valid SStx.
if err := stake.CheckSStx(mtx); err != nil {
return nil, errors.E(errors.Op("stake.CheckSStx"), errors.Bug, err)
}
return mtx, nil
}
var p2pkhSizedScript = make([]byte, 25)
func (w *Wallet) mixedSplit(ctx context.Context, req *PurchaseTicketsRequest, neededPerTicket dcrutil.Amount) (tx *wire.MsgTx, outIndexes []int, err error) {
// Use txauthor to perform input selection and change amount
// calculations for the unmixed portions of the coinjoin.
mixOut := make([]*wire.TxOut, req.Count)
for i := 0; i < req.Count; i++ {
mixOut[i] = &wire.TxOut{Value: int64(neededPerTicket), Version: 0, PkScript: p2pkhSizedScript}
}
relayFee := w.RelayFee()
var changeSourceUpdates []func(walletdb.ReadWriteTx) error
defer func() {
if err != nil {
return
}