-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathwallet.go
5815 lines (5224 loc) · 174 KB
/
wallet.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 (
"bytes"
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"math/big"
"runtime"
"sort"
"sync"
"sync/atomic"
"time"
"decred.org/dcrwallet/v5/deployments"
"decred.org/dcrwallet/v5/errors"
"decred.org/dcrwallet/v5/internal/compat"
"decred.org/dcrwallet/v5/internal/loggers"
"decred.org/dcrwallet/v5/rpc/client/dcrd"
"decred.org/dcrwallet/v5/rpc/jsonrpc/types"
"decred.org/dcrwallet/v5/validate"
"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/blake256"
"github.com/decred/dcrd/dcrec"
"github.com/decred/dcrd/dcrec/secp256k1/v4"
"github.com/decred/dcrd/dcrec/secp256k1/v4/ecdsa"
"github.com/decred/dcrd/dcrutil/v4"
gcs2 "github.com/decred/dcrd/gcs/v4"
"github.com/decred/dcrd/hdkeychain/v3"
"github.com/decred/dcrd/mixing/mixclient"
"github.com/decred/dcrd/mixing/mixpool"
dcrdtypes "github.com/decred/dcrd/rpc/jsonrpc/types/v4"
"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"
"golang.org/x/sync/errgroup"
)
const (
// InsecurePubPassphrase is the default outer encryption passphrase used
// for public data (everything but private keys). Using a non-default
// public passphrase can prevent an attacker without the public
// passphrase from discovering all past and future wallet addresses if
// they gain access to the wallet database.
//
// NOTE: at time of writing, public encryption only applies to public
// data in the waddrmgr namespace. Transactions are not yet encrypted.
InsecurePubPassphrase = "public"
)
var (
// SimulationPassphrase is the password for a wallet created for simnet
// with --createtemp.
SimulationPassphrase = []byte("password")
)
// Namespace bucket keys.
var (
waddrmgrNamespaceKey = []byte("waddrmgr")
wtxmgrNamespaceKey = []byte("wtxmgr")
)
// The assumed output script version is defined to assist with refactoring to
// use actual script versions.
const scriptVersionAssumed = 0
// StakeDifficultyInfo is a container for stake difficulty information updates.
type StakeDifficultyInfo struct {
BlockHash *chainhash.Hash
BlockHeight int64
StakeDifficulty int64
}
// outpoint is a wire.OutPoint without specifying a tree. It is used as the key
// for the lockedOutpoints map.
type outpoint struct {
hash chainhash.Hash
index uint32
}
// Wallet is a structure containing all the components for a
// complete wallet. It contains the Armory-style key store
// addresses and keys),
type Wallet struct {
// disapprovePercent is an atomic. It sets the percentage of blocks to
// disapprove on simnet or testnet.
disapprovePercent atomic.Uint32
// Data stores
db walletdb.DB
manager *udb.Manager
txStore *udb.Store
// Handlers for stake system.
stakeSettingsLock sync.Mutex
defaultVoteBits stake.VoteBits
votingEnabled bool
manualTickets bool
subsidyCache *blockchain.SubsidyCache
tspends map[chainhash.Hash]wire.MsgTx
tspendPolicy map[chainhash.Hash]stake.TreasuryVoteT
tspendKeyPolicy map[string]stake.TreasuryVoteT // keyed by politeia key
vspTSpendPolicy map[udb.VSPTSpend]stake.TreasuryVoteT
vspTSpendKeyPolicy map[udb.VSPTreasuryKey]stake.TreasuryVoteT
// Start up flags/settings
gapLimit uint32
watchLast uint32
accountGapLimit int
// initialHeight is the wallet's tip height prior to syncing with the
// network. Useful for calculating or estimating headers fetch progress
// during sync if the target header height is known or can be estimated.
initialHeight int32
networkBackend NetworkBackend
networkBackendMu sync.Mutex
lockedOutpoints map[outpoint]struct{}
lockedOutpointMu sync.Mutex
relayFee dcrutil.Amount
relayFeeMu sync.Mutex
allowHighFees bool
disableCoinTypeUpgrades bool
recentlyPublished map[chainhash.Hash]struct{}
recentlyPublishedMu sync.Mutex
logRescannedTransactions bool
logRescannedTransactionsMu sync.Mutex
// Internal address handling.
addressBuffers map[uint32]*bip0044AccountData
addressBuffersMu sync.Mutex
// Passphrase unlock
passphraseUsedMu sync.RWMutex
passphraseTimeoutMu sync.Mutex
passphraseTimeoutCancel chan struct{}
// Mixing
mixing bool
mixpool *mixpool.Pool
mixSems mixSemaphores
mixClient *mixclient.Client
// Cached Blake3 anchor candidate
cachedBlake3WorkDiffCandidateAnchor *wire.BlockHeader
cachedBlake3WorkDiffCandidateAnchorMu sync.Mutex
NtfnServer *NotificationServer
chainParams *chaincfg.Params
deploymentsByID map[string]*chaincfg.ConsensusDeployment
minTestNetTarget *big.Int
minTestNetDiffBits uint32
vspClientsMu sync.Mutex
vspClients map[string]*VSPClient
dialer DialFunc
}
// Config represents the configuration options needed to initialize a wallet.
type Config struct {
DB DB
PubPassphrase []byte
VotingEnabled bool
GapLimit uint32
WatchLast uint32
AccountGapLimit int
MixSplitLimit int
DisableCoinTypeUpgrades bool
DisableMixing bool
ManualTickets bool
AllowHighFees bool
RelayFee dcrutil.Amount
Params *chaincfg.Params
Dialer DialFunc
}
// DisapprovePercent returns the wallet's block disapproval percentage.
func (w *Wallet) DisapprovePercent() uint32 {
return w.disapprovePercent.Load()
}
// SetDisapprovePercent sets the wallet's block disapproval percentage. Do not
// set on mainnet.
func (w *Wallet) SetDisapprovePercent(percent uint32) {
w.disapprovePercent.Store(percent)
}
// FetchOutput fetches the associated transaction output given an outpoint.
// It cannot be used to fetch multi-signature outputs.
func (w *Wallet) FetchOutput(ctx context.Context, outPoint *wire.OutPoint) (*wire.TxOut, error) {
const op errors.Op = "wallet.FetchOutput"
var out *wire.TxOut
err := walletdb.View(ctx, w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
outTx, err := w.txStore.Tx(txmgrNs, &outPoint.Hash)
if err != nil {
return err
}
out = outTx.TxOut[outPoint.Index]
return err
})
if err != nil {
return nil, errors.E(op, err)
}
return out, nil
}
// VotingEnabled returns whether the wallet is configured to vote tickets.
func (w *Wallet) VotingEnabled() bool {
w.stakeSettingsLock.Lock()
enabled := w.votingEnabled
w.stakeSettingsLock.Unlock()
return enabled
}
// IsTSpendCached returns whether the given hash is already cached.
func (w *Wallet) IsTSpendCached(hash *chainhash.Hash) bool {
if _, ok := w.tspends[*hash]; ok {
return true
}
return false
}
// AddTSpend adds a tspend to the cache.
func (w *Wallet) AddTSpend(tx wire.MsgTx) error {
hash := tx.TxHash()
log.Infof("TSpend arrived: %v", hash)
w.stakeSettingsLock.Lock()
defer w.stakeSettingsLock.Unlock()
if _, ok := w.tspends[hash]; ok {
return fmt.Errorf("tspend already cached")
}
w.tspends[hash] = tx
return nil
}
// GetAllTSpends returns all tspends currently in the cache.
// Note: currently the tspend list does not get culled.
func (w *Wallet) GetAllTSpends(ctx context.Context) []*wire.MsgTx {
_, height := w.MainChainTip(ctx)
w.stakeSettingsLock.Lock()
defer w.stakeSettingsLock.Unlock()
txs := make([]*wire.MsgTx, 0, len(w.tspends))
for k := range w.tspends {
v := w.tspends[k]
if uint32(height) > v.Expiry {
delete(w.tspends, k)
continue
}
txs = append(txs, &v)
}
return txs
}
func voteVersion(params *chaincfg.Params) uint32 {
switch params.Net {
case wire.MainNet:
return 10
case 0x48e7a065: // TestNet2
return 6
case wire.TestNet3:
return 11
case wire.SimNet:
return 11
default:
return 1
}
}
// CurrentAgendas returns the current stake version for the active network and
// this version of the software, and all agendas defined by it.
func CurrentAgendas(params *chaincfg.Params) (version uint32, agendas []chaincfg.ConsensusDeployment) {
version = voteVersion(params)
if params.Deployments == nil {
return version, nil
}
return version, params.Deployments[version]
}
func (w *Wallet) readDBVoteBits(dbtx walletdb.ReadTx) stake.VoteBits {
version, deployments := CurrentAgendas(w.chainParams)
vb := stake.VoteBits{
Bits: 0x0001,
ExtendedBits: make([]byte, 4),
}
binary.LittleEndian.PutUint32(vb.ExtendedBits, version)
if len(deployments) == 0 {
return vb
}
for i := range deployments {
d := &deployments[i]
choiceID := udb.DefaultAgendaPreference(dbtx, version, d.Vote.Id)
if choiceID == "" {
continue
}
for j := range d.Vote.Choices {
choice := &d.Vote.Choices[j]
if choiceID == choice.Id {
vb.Bits |= choice.Bits
break
}
}
}
return vb
}
func (w *Wallet) readDBTicketVoteBits(dbtx walletdb.ReadTx, ticketHash *chainhash.Hash) (stake.VoteBits, bool) {
version, deployments := CurrentAgendas(w.chainParams)
tvb := stake.VoteBits{
Bits: 0x0001,
ExtendedBits: make([]byte, 4),
}
binary.LittleEndian.PutUint32(tvb.ExtendedBits, version)
if len(deployments) == 0 {
return tvb, false
}
var hasSavedPrefs bool
for i := range deployments {
d := &deployments[i]
choiceID := udb.TicketAgendaPreference(dbtx, ticketHash, version, d.Vote.Id)
if choiceID == "" {
continue
}
hasSavedPrefs = true
for j := range d.Vote.Choices {
choice := &d.Vote.Choices[j]
if choiceID == choice.Id {
tvb.Bits |= choice.Bits
break
}
}
}
return tvb, hasSavedPrefs
}
func (w *Wallet) readDBTreasuryPolicies(dbtx walletdb.ReadTx) (
map[chainhash.Hash]stake.TreasuryVoteT, map[udb.VSPTSpend]stake.TreasuryVoteT, error) {
a, err := udb.TSpendPolicies(dbtx)
if err != nil {
return nil, nil, err
}
b, err := udb.VSPTSpendPolicies(dbtx)
return a, b, err
}
func (w *Wallet) readDBTreasuryKeyPolicies(dbtx walletdb.ReadTx) (
map[string]stake.TreasuryVoteT, map[udb.VSPTreasuryKey]stake.TreasuryVoteT, error) {
a, err := udb.TreasuryKeyPolicies(dbtx)
if err != nil {
return nil, nil, err
}
b, err := udb.VSPTreasuryKeyPolicies(dbtx)
return a, b, err
}
// VoteBits returns the vote bits that are described by the currently set agenda
// preferences. The previous block valid bit is always set, and must be unset
// elsewhere if the previous block's regular transactions should be voted
// against.
func (w *Wallet) VoteBits() stake.VoteBits {
w.stakeSettingsLock.Lock()
vb := w.defaultVoteBits
w.stakeSettingsLock.Unlock()
return vb
}
// AgendaChoices returns the choice IDs for every agenda of the supported stake
// version. Abstains are included. Returns choice IDs set for the specified
// non-nil ticket hash, or the default choice IDs if the ticket hash is nil or
// there are no choices set for the ticket.
func (w *Wallet) AgendaChoices(ctx context.Context, ticketHash *chainhash.Hash) (choices map[string]string, voteBits uint16, err error) {
const op errors.Op = "wallet.AgendaChoices"
version, deployments := CurrentAgendas(w.chainParams)
if len(deployments) == 0 {
return map[string]string{}, 0, nil
}
choices = make(map[string]string, len(deployments))
for _, d := range deployments {
choices[d.Vote.Id] = "abstain"
}
var ownTicket bool
var hasSavedPrefs bool
voteBits = 1
err = walletdb.View(ctx, w.db, func(tx walletdb.ReadTx) error {
if ticketHash != nil {
ownTicket = w.txStore.OwnTicket(tx, ticketHash)
if !ownTicket {
return nil
}
}
for i := range deployments {
agenda := &deployments[i].Vote
var choice string
if ticketHash == nil {
choice = udb.DefaultAgendaPreference(tx, version, agenda.Id)
} else {
choice = udb.TicketAgendaPreference(tx, ticketHash, version, agenda.Id)
}
if choice == "" {
continue
}
hasSavedPrefs = true
choices[agenda.Id] = choice
for j := range agenda.Choices {
if agenda.Choices[j].Id == choice {
voteBits |= agenda.Choices[j].Bits
break
}
}
}
return nil
})
if err != nil {
return nil, 0, errors.E(op, err)
}
if ticketHash != nil && !ownTicket {
return nil, 0, errors.E(errors.NotExist, "ticket not found")
}
if ticketHash != nil && !hasSavedPrefs {
// no choices set for ticket hash, return default choices.
return w.AgendaChoices(ctx, nil)
}
return choices, voteBits, nil
}
// SetAgendaChoices sets the choices for agendas defined by the supported stake
// version. If a choice is set multiple times, the last takes preference. The
// new votebits after each change is made are returned.
// If a ticketHash is provided, agenda choices are only set for that ticket and
// the new votebits for that ticket is returned.
func (w *Wallet) SetAgendaChoices(ctx context.Context, ticketHash *chainhash.Hash, choices map[string]string) (voteBits uint16, err error) {
const op errors.Op = "wallet.SetAgendaChoices"
version, deployments := CurrentAgendas(w.chainParams)
if len(deployments) == 0 {
return 0, errors.E("no agendas to set for this network")
}
if ticketHash != nil {
// validate ticket ownership
var ownTicket bool
err = walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
ownTicket = w.txStore.OwnTicket(dbtx, ticketHash)
return nil
})
if err != nil {
return 0, errors.E(op, err)
}
if !ownTicket {
return 0, errors.E(errors.NotExist, "ticket not found")
}
}
type maskChoice struct {
mask uint16
bits uint16
}
var appliedChoices []maskChoice
err = walletdb.Update(ctx, w.db, func(tx walletdb.ReadWriteTx) error {
for agendaID, choiceID := range choices {
var matchingAgenda *chaincfg.Vote
for i := range deployments {
if deployments[i].Vote.Id == agendaID {
matchingAgenda = &deployments[i].Vote
break
}
}
if matchingAgenda == nil {
return errors.E(errors.Invalid, errors.Errorf("no agenda with ID %q", agendaID))
}
var matchingChoice *chaincfg.Choice
for i := range matchingAgenda.Choices {
if matchingAgenda.Choices[i].Id == choiceID {
matchingChoice = &matchingAgenda.Choices[i]
break
}
}
if matchingChoice == nil {
return errors.E(errors.Invalid, errors.Errorf("agenda %q has no choice ID %q", agendaID, choiceID))
}
var err error
if ticketHash == nil {
err = udb.SetDefaultAgendaPreference(tx, version, agendaID, choiceID)
} else {
err = udb.SetTicketAgendaPreference(tx, ticketHash, version, agendaID, choiceID)
}
if err != nil {
return err
}
appliedChoices = append(appliedChoices, maskChoice{
mask: matchingAgenda.Mask,
bits: matchingChoice.Bits,
})
if ticketHash != nil {
// No need to check that this ticket has prefs set,
// we just saved the per-ticket vote bits.
ticketVoteBits, _ := w.readDBTicketVoteBits(tx, ticketHash)
voteBits = ticketVoteBits.Bits
}
}
return nil
})
if err != nil {
return 0, errors.E(op, err)
}
// With the DB update successful, modify the default votebits cached by the
// wallet structure. Per-ticket votebits are not cached.
if ticketHash == nil {
w.stakeSettingsLock.Lock()
for _, c := range appliedChoices {
w.defaultVoteBits.Bits &^= c.mask // Clear all bits from this agenda
w.defaultVoteBits.Bits |= c.bits // Set bits for this choice
}
voteBits = w.defaultVoteBits.Bits
w.stakeSettingsLock.Unlock()
}
return voteBits, nil
}
// TreasuryKeyPolicy returns a vote policy for provided Pi key. If there is
// no policy this method returns TreasuryVoteInvalid.
// A non-nil ticket hash may be used by a VSP to return per-ticket policies.
func (w *Wallet) TreasuryKeyPolicy(pikey []byte, ticket *chainhash.Hash) stake.TreasuryVoteT {
w.stakeSettingsLock.Lock()
defer w.stakeSettingsLock.Unlock()
// Zero value is abstain/invalid, just return as is.
if ticket != nil {
return w.vspTSpendKeyPolicy[udb.VSPTreasuryKey{
Ticket: *ticket,
TreasuryKey: string(pikey),
}]
}
return w.tspendKeyPolicy[string(pikey)]
}
// TSpendPolicy returns a vote policy for a tspend. If a policy is set for a
// particular tspend transaction, that policy is returned. Otherwise, if the
// tspend is known, any policy for the treasury key which signs the tspend is
// returned.
// A non-nil ticket hash may be used by a VSP to return per-ticket policies.
func (w *Wallet) TSpendPolicy(tspendHash, ticketHash *chainhash.Hash) stake.TreasuryVoteT {
w.stakeSettingsLock.Lock()
defer w.stakeSettingsLock.Unlock()
// Policy preferences for specific tspends override key policies.
if ticketHash != nil {
policy, ok := w.vspTSpendPolicy[udb.VSPTSpend{
Ticket: *ticketHash,
TSpend: *tspendHash,
}]
if ok {
return policy
}
}
if policy, ok := w.tspendPolicy[*tspendHash]; ok {
return policy
}
// If this tspend is known, the pi key can be extracted from it and its
// policy is returned.
tspend, ok := w.tspends[*tspendHash]
if !ok {
return 0 // invalid/abstain
}
pikey := tspend.TxIn[0].SignatureScript[66 : 66+secp256k1.PubKeyBytesLenCompressed]
// Zero value means abstain, just return as is.
if ticketHash != nil {
policy, ok := w.vspTSpendKeyPolicy[udb.VSPTreasuryKey{
Ticket: *ticketHash,
TreasuryKey: string(pikey),
}]
if ok {
return policy
}
}
return w.tspendKeyPolicy[string(pikey)]
}
// TreasuryKeyPolicy records the voting policy for treasury spend transactions
// by a particular key, and possibly for a particular ticket being voted on by a
// VSP.
type TreasuryKeyPolicy struct {
PiKey []byte
Ticket *chainhash.Hash // nil unless for per-ticket VSP policies
Policy stake.TreasuryVoteT
}
// TreasuryKeyPolicies returns all configured policies for treasury keys.
func (w *Wallet) TreasuryKeyPolicies() []TreasuryKeyPolicy {
w.stakeSettingsLock.Lock()
defer w.stakeSettingsLock.Unlock()
policies := make([]TreasuryKeyPolicy, 0, len(w.tspendKeyPolicy))
for pikey, policy := range w.tspendKeyPolicy {
policies = append(policies, TreasuryKeyPolicy{
PiKey: []byte(pikey),
Policy: policy,
})
}
for tuple, policy := range w.vspTSpendKeyPolicy {
ticketHash := tuple.Ticket // copy
pikey := []byte(tuple.TreasuryKey)
policies = append(policies, TreasuryKeyPolicy{
PiKey: pikey,
Ticket: &ticketHash,
Policy: policy,
})
}
return policies
}
// SetTreasuryKeyPolicy sets a tspend vote policy for a specific Politeia
// instance key.
// A non-nil ticket hash may be used by a VSP to set per-ticket policies.
func (w *Wallet) SetTreasuryKeyPolicy(ctx context.Context, pikey []byte,
policy stake.TreasuryVoteT, ticketHash *chainhash.Hash) error {
switch policy {
case stake.TreasuryVoteInvalid, stake.TreasuryVoteNo, stake.TreasuryVoteYes:
default:
err := errors.Errorf("invalid treasury vote policy %#x", policy)
return errors.E(errors.Invalid, err)
}
defer w.stakeSettingsLock.Unlock()
w.stakeSettingsLock.Lock()
err := walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
if ticketHash != nil {
return udb.SetVSPTreasuryKeyPolicy(dbtx, ticketHash,
pikey, policy)
}
return udb.SetTreasuryKeyPolicy(dbtx, pikey, policy)
})
if err != nil {
return err
}
if ticketHash != nil {
k := udb.VSPTreasuryKey{
Ticket: *ticketHash,
TreasuryKey: string(pikey),
}
if policy == stake.TreasuryVoteInvalid {
delete(w.vspTSpendKeyPolicy, k)
return nil
}
w.vspTSpendKeyPolicy[k] = policy
return nil
}
if policy == stake.TreasuryVoteInvalid {
delete(w.tspendKeyPolicy, string(pikey))
return nil
}
w.tspendKeyPolicy[string(pikey)] = policy
return nil
}
// SetTSpendPolicy sets a tspend vote policy for a specific tspend transaction
// hash.
// A non-nil ticket hash may be used by a VSP to set per-ticket policies.
func (w *Wallet) SetTSpendPolicy(ctx context.Context, tspendHash *chainhash.Hash,
policy stake.TreasuryVoteT, ticketHash *chainhash.Hash) error {
switch policy {
case stake.TreasuryVoteInvalid, stake.TreasuryVoteNo, stake.TreasuryVoteYes:
default:
err := errors.Errorf("invalid treasury vote policy %#x", policy)
return errors.E(errors.Invalid, err)
}
defer w.stakeSettingsLock.Unlock()
w.stakeSettingsLock.Lock()
err := walletdb.Update(ctx, w.db, func(dbtx walletdb.ReadWriteTx) error {
if ticketHash != nil {
return udb.SetVSPTSpendPolicy(dbtx, ticketHash,
tspendHash, policy)
}
return udb.SetTSpendPolicy(dbtx, tspendHash, policy)
})
if err != nil {
return err
}
if ticketHash != nil {
k := udb.VSPTSpend{
Ticket: *ticketHash,
TSpend: *tspendHash,
}
if policy == stake.TreasuryVoteInvalid {
delete(w.vspTSpendPolicy, k)
return nil
}
w.vspTSpendPolicy[k] = policy
return nil
}
if policy == stake.TreasuryVoteInvalid {
delete(w.tspendPolicy, *tspendHash)
return nil
}
w.tspendPolicy[*tspendHash] = policy
return nil
}
// RelayFee returns the current minimum relay fee (per kB of serialized
// transaction) used when constructing transactions.
func (w *Wallet) RelayFee() dcrutil.Amount {
w.relayFeeMu.Lock()
relayFee := w.relayFee
w.relayFeeMu.Unlock()
return relayFee
}
// SetRelayFee sets a new minimum relay fee (per kB of serialized
// transaction) used when constructing transactions.
func (w *Wallet) SetRelayFee(relayFee dcrutil.Amount) {
w.relayFeeMu.Lock()
w.relayFee = relayFee
w.relayFeeMu.Unlock()
}
// InitialHeight is the wallet's tip height prior to syncing with the network.
func (w *Wallet) InitialHeight() int32 {
return w.initialHeight
}
// MainChainTip returns the hash and height of the tip-most block in the main
// chain that the wallet is synchronized to.
func (w *Wallet) MainChainTip(ctx context.Context) (hash chainhash.Hash, height int32) {
// TODO: after the main chain tip is successfully updated in the db, it
// should be saved in memory. This will speed up access to it, and means
// there won't need to be an ignored error here for ergonomic access to the
// hash and height.
walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
hash, height = w.txStore.MainChainTip(dbtx)
return nil
})
return
}
// BlockInMainChain returns whether hash is a block hash of any block in the
// wallet's main chain. If the block is in the main chain, invalidated reports
// whether a child block in the main chain stake invalidates the queried block.
func (w *Wallet) BlockInMainChain(ctx context.Context, hash *chainhash.Hash) (haveBlock, invalidated bool, err error) {
const op errors.Op = "wallet.BlockInMainChain"
err = walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
haveBlock, invalidated = w.txStore.BlockInMainChain(dbtx, hash)
return nil
})
if err != nil {
return false, false, errors.E(op, err)
}
return haveBlock, invalidated, nil
}
// BlockHeader returns the block header for a block by it's identifying hash, if
// it is recorded by the wallet.
func (w *Wallet) BlockHeader(ctx context.Context, blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
var header *wire.BlockHeader
err := walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
var err error
header, err = w.txStore.GetBlockHeader(dbtx, blockHash)
return err
})
return header, err
}
// CFilterV2 returns the version 2 regular compact filter for a block along
// with the key required to query it for matches against committed scripts.
func (w *Wallet) CFilterV2(ctx context.Context, blockHash *chainhash.Hash) ([gcs2.KeySize]byte, *gcs2.FilterV2, error) {
var f *gcs2.FilterV2
var key [gcs2.KeySize]byte
err := walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
var err error
key, f, err = w.txStore.CFilterV2(dbtx, blockHash)
return err
})
return key, f, err
}
// RangeCFiltersV2 calls the function `f` for the set of version 2 committed
// filters for the main chain within the specificed block range.
//
// The default behavior for an unspecified range is to loop over the entire
// main chain.
//
// The function `f` may return true for the first argument to indicate no more
// items should be fetched. Any returned errors by `f` also cause the loop to
// fail.
//
// Note that the filter passed to `f` is safe for use after `f` returns.
func (w *Wallet) RangeCFiltersV2(ctx context.Context, startBlock, endBlock *BlockIdentifier, f func(chainhash.Hash, [gcs2.KeySize]byte, *gcs2.FilterV2) (bool, error)) error {
const op errors.Op = "wallet.RangeCFiltersV2"
err := walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
start, end, err := w.blockRange(dbtx, startBlock, endBlock)
if err != nil {
return err
}
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
rangeFn := func(block *udb.Block) (bool, error) {
key, filter, err := w.txStore.CFilterV2(dbtx, &block.Hash)
if err != nil {
return false, err
}
return f(block.Hash, key, filter)
}
return w.txStore.RangeBlocks(txmgrNs, start, end, rangeFn)
})
if err != nil {
return errors.E(op, err)
}
return nil
}
// watchHDAddrs loads the network backend's transaction filter with HD addresses
// for transaction notifications.
//
// This method does nothing if the wallet's rescan point is behind the main
// chain tip block and firstWatch is false. That is, it does not watch any
// addresses if the wallet's transactions are not synced with the best known
// block. There is no reason to watch addresses if there is a known possibility
// of not having all relevant transactions.
func (w *Wallet) watchHDAddrs(ctx context.Context, firstWatch bool, n NetworkBackend) (count uint64, err error) {
if !firstWatch {
rp, err := w.RescanPoint(ctx)
if err != nil {
return 0, err
}
if rp != nil {
return 0, nil
}
}
// Read branch keys and child counts for all derived and imported
// HD accounts.
type hdAccount struct {
externalKey, internalKey *hdkeychain.ExtendedKey
externalCount, internalCount uint32
lastWatchedExternal, lastWatchedInternal uint32
lastReturnedExternal, lastReturnedInternal uint32
lastUsedExternal, lastUsedInternal uint32
}
hdAccounts := make(map[uint32]hdAccount)
err = walletdb.View(ctx, w.db, func(dbtx walletdb.ReadTx) error {
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
var err error
lastAcct, err := w.manager.LastAccount(addrmgrNs)
if err != nil {
return err
}
lastImportedAcct, err := w.manager.LastImportedAccount(dbtx)
if err != nil {
return err
}
loadAccount := func(acct uint32) error {
props, err := w.manager.AccountProperties(addrmgrNs, acct)
if err != nil {
return err
}
hdAccounts[acct] = hdAccount{
externalCount: minUint32(props.LastReturnedExternalIndex+w.gapLimit, hdkeychain.HardenedKeyStart-1),
internalCount: minUint32(props.LastReturnedInternalIndex+w.gapLimit, hdkeychain.HardenedKeyStart-1),
lastReturnedExternal: props.LastReturnedExternalIndex,
lastReturnedInternal: props.LastReturnedInternalIndex,
lastUsedExternal: props.LastUsedExternalIndex,
lastUsedInternal: props.LastUsedInternalIndex,
}
return nil
}
for acct := uint32(0); acct <= lastAcct; acct++ {
err := loadAccount(acct)
if err != nil {
return err
}
}
for acct := uint32(udb.ImportedAddrAccount + 1); acct <= lastImportedAcct; acct++ {
err := loadAccount(acct)
if err != nil {
return err
}
}
return nil
})
if err != nil {
return 0, err
}
w.addressBuffersMu.Lock()
for acct, ad := range w.addressBuffers {
hd := hdAccounts[acct]
// Update the in-memory address tracking with the latest last
// used index retreived from the db.
// Because the cursor may be advanced ahead of what the database
// would otherwise record as the last returned address, due to
// delayed db updates during some operations, a delta is
// calculated between the in-memory and db last returned
// indexes, and this delta is added back to the new cursor.
//
// This is calculated as:
// delta := ad.albExternal.lastUsed + ad.albExternal.cursor - hd.lastReturnedExternal
// ad.albExternal.cursor = hd.lastReturnedExternal - hd.lastUsedExternal + delta
// which simplifies to the calculation below. An additional clamp
// is added to prevent the cursors from going negative.
if hd.lastUsedExternal+1 > ad.albExternal.lastUsed+1 {
ad.albExternal.cursor += ad.albExternal.lastUsed - hd.lastUsedExternal
if ad.albExternal.cursor > ^uint32(0)>>1 {
ad.albExternal.cursor = 0
}
ad.albExternal.lastUsed = hd.lastUsedExternal
}
if hd.lastUsedInternal+1 > ad.albInternal.lastUsed+1 {
ad.albInternal.cursor += ad.albInternal.lastUsed - hd.lastUsedInternal
if ad.albInternal.cursor > ^uint32(0)>>1 {
ad.albInternal.cursor = 0
}
ad.albInternal.lastUsed = hd.lastUsedInternal
}
hd.externalKey = ad.albExternal.branchXpub
hd.internalKey = ad.albInternal.branchXpub
if firstWatch {
ad.albExternal.lastWatched = hd.externalCount
ad.albInternal.lastWatched = hd.internalCount
} else {
hd.lastWatchedExternal = ad.albExternal.lastWatched
hd.lastWatchedInternal = ad.albInternal.lastWatched
}
hdAccounts[acct] = hd
}
w.addressBuffersMu.Unlock()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
watchAddrs := make(chan []stdaddr.Address, runtime.NumCPU())
watchError := make(chan error)
go func() {
for addrs := range watchAddrs {
count += uint64(len(addrs))
err := n.LoadTxFilter(ctx, false, addrs, nil)
if err != nil {