/
wallet.go
4476 lines (4045 loc) · 133 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-2019 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"
"sort"
"strconv"
"strings"
"sync"
"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/dcrec"
"github.com/decred/dcrd/dcrec/secp256k1"
"github.com/decred/dcrd/dcrjson/v2"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/gcs"
"github.com/decred/dcrd/hdkeychain"
"github.com/decred/dcrd/rpcclient/v2"
"github.com/decred/dcrd/txscript"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrwallet/deployments"
"github.com/decred/dcrwallet/errors"
"github.com/decred/dcrwallet/rpc/jsonrpc/types"
"github.com/decred/dcrwallet/wallet/v2/txrules"
"github.com/decred/dcrwallet/wallet/v2/udb"
"github.com/decred/dcrwallet/wallet/v2/walletdb"
"github.com/jrick/bitset"
"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")
wstakemgrNamespaceKey = []byte("wstakemgr")
)
// StakeDifficultyInfo is a container for stake difficulty information updates.
type StakeDifficultyInfo struct {
BlockHash *chainhash.Hash
BlockHeight int64
StakeDifficulty int64
}
// 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 {
// Data stores
db walletdb.DB
Manager *udb.Manager
TxStore *udb.Store
StakeMgr *udb.StakeStore
// Handlers for stake system.
stakeSettingsLock sync.Mutex
voteBits stake.VoteBits
votingEnabled bool
balanceToMaintain dcrutil.Amount
poolAddress dcrutil.Address
poolFees float64
stakePoolEnabled bool
stakePoolColdAddrs map[string]struct{}
subsidyCache *blockchain.SubsidyCache
// Start up flags/settings
gapLimit int
accountGapLimit int
networkBackend NetworkBackend
networkBackendMu sync.Mutex
lockedOutpoints map[wire.OutPoint]struct{}
lockedOutpointMu sync.Mutex
relayFee dcrutil.Amount
relayFeeMu sync.Mutex
ticketFeeIncrementLock sync.Mutex
ticketFeeIncrement dcrutil.Amount
DisallowFree bool
AllowHighFees bool
disableCoinTypeUpgrades bool
// Internal address handling.
addressReuse bool
ticketAddress dcrutil.Address
addressBuffers map[uint32]*bip0044AccountData
addressBuffersMu sync.Mutex
// Passphrase unlock
passphraseUsedMu sync.RWMutex
passphraseTimeoutMu sync.Mutex
passphraseTimeoutCancel chan struct{}
NtfnServer *NotificationServer
chainParams *chaincfg.Params
}
// Config represents the configuration options needed to initialize a wallet.
type Config struct {
DB DB
PubPassphrase []byte
VotingEnabled bool
AddressReuse bool
VotingAddress dcrutil.Address
PoolAddress dcrutil.Address
PoolFees float64
TicketFee float64
GapLimit int
AccountGapLimit int
DisableCoinTypeUpgrades bool
StakePoolColdExtKey string
AllowHighFees bool
RelayFee float64
Params *chaincfg.Params
}
// FetchOutput fetches the associated transaction output given an outpoint.
// It cannot be used to fetch multi-signature outputs.
func (w *Wallet) FetchOutput(outPoint *wire.OutPoint) (*wire.TxOut, error) {
const op errors.Op = "wallet.FetchOutput"
var out *wire.TxOut
err := walletdb.View(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
}
// BalanceToMaintain is used to get the current balancetomaintain for the wallet.
func (w *Wallet) BalanceToMaintain() dcrutil.Amount {
w.stakeSettingsLock.Lock()
balance := w.balanceToMaintain
w.stakeSettingsLock.Unlock()
return balance
}
// SetBalanceToMaintain is used to set the current w.balancetomaintain for the wallet.
func (w *Wallet) SetBalanceToMaintain(balance dcrutil.Amount) {
w.stakeSettingsLock.Lock()
w.balanceToMaintain = balance
w.stakeSettingsLock.Unlock()
}
// 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
}
func voteVersion(params *chaincfg.Params) uint32 {
switch params.Net {
case wire.MainNet:
return 6
case 0x48e7a065: // TestNet2
return 6
case wire.TestNet3:
return 7
case wire.SimNet:
return 7
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.AgendaPreference(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
}
// 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.voteBits
w.stakeSettingsLock.Unlock()
return vb
}
// AgendaChoice describes a user's choice for a consensus deployment agenda.
type AgendaChoice struct {
AgendaID string
ChoiceID string
}
// AgendaChoices returns the choice IDs for every agenda of the supported stake
// version. Abstains are included.
func (w *Wallet) AgendaChoices() (choices []AgendaChoice, voteBits uint16, err error) {
const op errors.Op = "wallet.AgendaChoices"
version, deployments := CurrentAgendas(w.chainParams)
if len(deployments) == 0 {
return nil, 0, nil
}
choices = make([]AgendaChoice, len(deployments))
for i := range choices {
choices[i].AgendaID = deployments[i].Vote.Id
choices[i].ChoiceID = "abstain"
}
voteBits = 1
err = walletdb.View(w.db, func(tx walletdb.ReadTx) error {
for i := range deployments {
agenda := &deployments[i].Vote
choice := udb.AgendaPreference(tx, version, agenda.Id)
if choice == "" {
continue
}
choices[i].ChoiceID = 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)
}
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.
func (w *Wallet) SetAgendaChoices(choices ...AgendaChoice) (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")
}
type maskChoice struct {
mask uint16
bits uint16
}
var appliedChoices []maskChoice
err = walletdb.Update(w.db, func(tx walletdb.ReadWriteTx) error {
for _, c := range choices {
var matchingAgenda *chaincfg.Vote
for i := range deployments {
if deployments[i].Vote.Id == c.AgendaID {
matchingAgenda = &deployments[i].Vote
break
}
}
if matchingAgenda == nil {
return errors.E(errors.Invalid, errors.Errorf("no agenda with ID %q", c.AgendaID))
}
var matchingChoice *chaincfg.Choice
for i := range matchingAgenda.Choices {
if matchingAgenda.Choices[i].Id == c.ChoiceID {
matchingChoice = &matchingAgenda.Choices[i]
break
}
}
if matchingChoice == nil {
return errors.E(errors.Invalid, errors.Errorf("agenda %q has no choice ID %q", c.AgendaID, c.ChoiceID))
}
err := udb.SetAgendaPreference(tx, version, c.AgendaID, c.ChoiceID)
if err != nil {
return err
}
appliedChoices = append(appliedChoices, maskChoice{
mask: matchingAgenda.Mask,
bits: matchingChoice.Bits,
})
}
return nil
})
if err != nil {
return 0, errors.E(op, err)
}
// With the DB update successful, modify the actual votebits cached by the
// wallet structure.
w.stakeSettingsLock.Lock()
for _, c := range appliedChoices {
w.voteBits.Bits &^= c.mask // Clear all bits from this agenda
w.voteBits.Bits |= c.bits // Set bits for this choice
}
voteBits = w.voteBits.Bits
w.stakeSettingsLock.Unlock()
return voteBits, nil
}
// TicketAddress gets the ticket address for the wallet to give the ticket
// voting rights to.
func (w *Wallet) TicketAddress() dcrutil.Address {
return w.ticketAddress
}
// PoolAddress gets the pool address for the wallet to give ticket fees to.
func (w *Wallet) PoolAddress() dcrutil.Address {
return w.poolAddress
}
// PoolFees gets the per-ticket pool fee for the wallet.
func (w *Wallet) PoolFees() float64 {
return w.poolFees
}
// Start was previously required to start necessary management goroutines of the wallet.
//
// Deprecated: This method is no longer necessary.
func (w *Wallet) Start() {
}
// 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()
}
// TicketFeeIncrement is used to get the current feeIncrement for the wallet.
func (w *Wallet) TicketFeeIncrement() dcrutil.Amount {
w.ticketFeeIncrementLock.Lock()
fee := w.ticketFeeIncrement
w.ticketFeeIncrementLock.Unlock()
return fee
}
// SetTicketFeeIncrement is used to set the current w.ticketFeeIncrement for the wallet.
func (w *Wallet) SetTicketFeeIncrement(fee dcrutil.Amount) {
w.ticketFeeIncrementLock.Lock()
w.ticketFeeIncrement = fee
w.ticketFeeIncrementLock.Unlock()
}
// Stop used to signal all wallet goroutines to shutdown.
//
// Deprecated: This method is no longer necessary.
func (w *Wallet) Stop() {
}
// WaitForShutdown used to block until all wallet goroutines have finished executing.
//
// Deprecated: This method is no longer necessary.
func (w *Wallet) WaitForShutdown() {
}
// 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() (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(w.db, func(tx walletdb.ReadTx) error {
txmgrNs := tx.ReadBucket(wtxmgrNamespaceKey)
hash, height = w.TxStore.MainChainTip(txmgrNs)
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(hash *chainhash.Hash) (haveBlock, invalidated bool, err error) {
const op errors.Op = "wallet.BlockInMainChain"
err = walletdb.View(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(blockHash *chainhash.Hash) (*wire.BlockHeader, error) {
var header *wire.BlockHeader
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
header, err = w.TxStore.GetBlockHeader(dbtx, blockHash)
return err
})
return header, err
}
// CFilter returns the regular compact filter for a block.
func (w *Wallet) CFilter(blockHash *chainhash.Hash) (*gcs.Filter, error) {
var f *gcs.Filter
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
f, err = w.TxStore.CFilter(dbtx, blockHash)
return err
})
return f, err
}
// loadActiveAddrs loads the consensus RPC server with active addresses for
// transaction notifications. For logging purposes, it returns the total number
// of addresses loaded.
func (w *Wallet) loadActiveAddrs(ctx context.Context, dbtx walletdb.ReadTx, nb NetworkBackend) (uint64, error) {
// loadBranchAddrs loads addresses for the branch with the child range [0,n].
loadBranchAddrs := func(branchKey *hdkeychain.ExtendedKey, n uint32, errs chan<- error) {
const step = 256
var g errgroup.Group
for child := uint32(0); child <= n; child += step {
child := child
g.Go(func() error {
addrs := make([]dcrutil.Address, 0, step)
stop := minUint32(n+1, child+step)
for ; child < stop; child++ {
addr, err := deriveChildAddress(branchKey, child, w.chainParams)
if err == hdkeychain.ErrInvalidChild {
continue
}
if err != nil {
return err
}
addrs = append(addrs, addr)
}
return nb.LoadTxFilter(ctx, false, addrs, nil)
})
}
errs <- g.Wait()
}
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
lastAcct, err := w.Manager.LastAccount(addrmgrNs)
if err != nil {
return 0, err
}
errs := make(chan error, int(lastAcct+1)*2+1)
var bip0044AddrCount, importedAddrCount uint64
for acct := uint32(0); acct <= lastAcct; acct++ {
props, err := w.Manager.AccountProperties(addrmgrNs, acct)
if err != nil {
return 0, err
}
acctXpub, err := w.Manager.AccountExtendedPubKey(dbtx, acct)
if err != nil {
return 0, err
}
extKey, intKey, err := deriveBranches(acctXpub)
if err != nil {
return 0, err
}
gapLimit := uint32(w.gapLimit)
extn := minUint32(props.LastReturnedExternalIndex+gapLimit, hdkeychain.HardenedKeyStart-1)
intn := minUint32(props.LastReturnedInternalIndex+gapLimit, hdkeychain.HardenedKeyStart-1)
// pre-cache the pubkey results so concurrent access does not race.
extKey.ECPubKey()
intKey.ECPubKey()
go loadBranchAddrs(extKey, extn, errs)
go loadBranchAddrs(intKey, intn, errs)
// loadBranchAddrs loads addresses through extn/intn, and the actual
// number of watched addresses is one more for each branch due to zero
// indexing.
bip0044AddrCount += uint64(extn) + uint64(intn) + 2
}
go func() {
// Imported addresses are still sent as a single slice for now. Could
// use the optimization above to avoid appends and reallocations.
var addrs []dcrutil.Address
err := w.Manager.ForEachAccountAddress(addrmgrNs, udb.ImportedAddrAccount,
func(a udb.ManagedAddress) error {
addrs = append(addrs, a.Address())
return nil
})
if err != nil {
errs <- err
return
}
importedAddrCount = uint64(len(addrs))
errs <- nb.LoadTxFilter(ctx, false, addrs, nil)
}()
for i := 0; i < cap(errs); i++ {
err := <-errs
if err != nil {
return 0, err
}
}
return bip0044AddrCount + importedAddrCount, nil
}
// CoinType returns the active BIP0044 coin type. For watching-only wallets,
// which do not save the coin type keys, this method will return an error with
// code errors.WatchingOnly.
func (w *Wallet) CoinType() (uint32, error) {
const op errors.Op = "wallet.CoinType"
var coinType uint32
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
var err error
coinType, err = w.Manager.CoinType(tx)
return err
})
if err != nil {
return coinType, errors.E(op, err)
}
return coinType, nil
}
// CoinTypePrivKey returns the BIP0044 coin type private key.
func (w *Wallet) CoinTypePrivKey() (*hdkeychain.ExtendedKey, error) {
const op errors.Op = "wallet.CoinTypePrivKey"
var coinTypePrivKey *hdkeychain.ExtendedKey
err := walletdb.View(w.db, func(tx walletdb.ReadTx) error {
var err error
coinTypePrivKey, err = w.Manager.CoinTypePrivKey(tx)
return err
})
if err != nil {
return nil, errors.E(op, err)
}
return coinTypePrivKey, nil
}
// LoadActiveDataFilters loads filters for all active addresses and unspent
// outpoints for this wallet.
func (w *Wallet) LoadActiveDataFilters(ctx context.Context, n NetworkBackend, reload bool) error {
const op errors.Op = "wallet.LoadActiveDataFilters"
log.Infof("Loading active addresses and unspent outputs...")
if reload {
err := n.LoadTxFilter(ctx, true, nil, nil)
if err != nil {
return err
}
}
var addrCount, utxoCount uint64
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
addrCount, err = w.loadActiveAddrs(ctx, dbtx, n)
if err != nil {
return err
}
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
unspent, err := w.TxStore.UnspentOutpoints(txmgrNs)
if err != nil {
return err
}
utxoCount = uint64(len(unspent))
return n.LoadTxFilter(ctx, false, nil, unspent)
})
if err != nil {
return errors.E(op, err)
}
log.Infof("Registered for transaction notifications for %v address(es) "+
"and %v output(s)", addrCount, utxoCount)
return nil
}
// CommittedTickets takes a list of tickets and returns a filtered list of
// tickets that are controlled by this wallet.
func (w *Wallet) CommittedTickets(tickets []*chainhash.Hash) ([]*chainhash.Hash, []dcrutil.Address, error) {
const op errors.Op = "wallet.CommittedTickets"
hashes := make([]*chainhash.Hash, 0, len(tickets))
addresses := make([]dcrutil.Address, 0, len(tickets))
// Verify we own this ticket
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
txmgrNs := dbtx.ReadBucket(wtxmgrNamespaceKey)
addrmgrNs := dbtx.ReadBucket(waddrmgrNamespaceKey)
for _, v := range tickets {
// Make sure ticket exists
tx, err := w.TxStore.Tx(txmgrNs, v)
if err != nil {
log.Debugf("%v", err)
continue
}
if !stake.IsSStx(tx) {
continue
}
// Commitment outputs are at alternating output
// indexes, starting at 1.
var bestAddr dcrutil.Address
var bestAmount dcrutil.Amount
for i := 1; i < len(tx.TxOut); i += 2 {
scr := tx.TxOut[i].PkScript
addr, err := stake.AddrFromSStxPkScrCommitment(scr,
w.chainParams)
if err != nil {
log.Debugf("%v", err)
break
}
if _, ok := addr.(*dcrutil.AddressPubKeyHash); !ok {
log.Tracef("Skipping commitment at "+
"index %v: address is not "+
"P2PKH", i)
continue
}
amt, err := stake.AmountFromSStxPkScrCommitment(scr)
if err != nil {
log.Debugf("%v", err)
break
}
if amt > bestAmount {
bestAddr = addr
bestAmount = amt
}
}
if bestAddr == nil {
log.Debugf("no best address")
continue
}
if !w.Manager.ExistsHash160(addrmgrNs,
bestAddr.Hash160()[:]) {
log.Debugf("not our address: %x",
bestAddr.Hash160())
continue
}
ticketHash := tx.TxHash()
log.Tracef("Ticket purchase %v: best commitment"+
" address %v amount %v", &ticketHash, bestAddr,
bestAmount)
hashes = append(hashes, v)
addresses = append(addresses, bestAddr)
}
return nil
})
if err != nil {
return nil, nil, errors.E(op, err)
}
return hashes, addresses, nil
}
// fetchMissingCFilters checks to see if there are any missing committed filters
// then, if so requests them from the given peer. The progress channel, if
// non-nil, is sent the first height and last height of the range of filters
// that were retrieved in that peer request.
func (w *Wallet) fetchMissingCFilters(ctx context.Context, p Peer, progress chan<- MissingCFilterProgress) error {
var missing bool
var height int32
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
missing = w.TxStore.IsMissingMainChainCFilters(dbtx)
if missing {
height, err = w.TxStore.MissingCFiltersHeight(dbtx)
}
return err
})
if err != nil {
return err
}
if !missing {
return nil
}
const span = 2000
storage := make([]chainhash.Hash, span)
storagePtrs := make([]*chainhash.Hash, span)
for i := range storage {
storagePtrs[i] = &storage[i]
}
for {
if err := ctx.Err(); err != nil {
return err
}
var hashes []chainhash.Hash
var get []*chainhash.Hash
var cont bool
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
ns := dbtx.ReadBucket(wtxmgrNamespaceKey)
var err error
missing = w.TxStore.IsMissingMainChainCFilters(dbtx)
if !missing {
return nil
}
hash, err := w.TxStore.GetMainChainBlockHashForHeight(ns, height)
if err != nil {
return err
}
_, err = w.TxStore.CFilter(dbtx, &hash)
if err == nil {
height += span
cont = true
return nil
}
storage = storage[:cap(storage)]
hashes, err = w.TxStore.GetMainChainBlockHashes(ns, &hash, true, storage)
if err != nil {
return err
}
if len(hashes) == 0 {
const op errors.Op = "udb.GetMainChainBlockHashes"
return errors.E(op, errors.Bug, "expected over 0 results")
}
get = storagePtrs[:len(hashes)]
if get[0] != &hashes[0] {
const op errors.Op = "udb.GetMainChainBlockHashes"
return errors.E(op, errors.Bug, "unexpected slice reallocation")
}
return nil
})
if err != nil {
return err
}
if !missing {
return nil
}
if cont {
continue
}
filters, err := p.GetCFilters(ctx, get)
if err != nil {
return err
}
err = walletdb.Update(w.db, func(dbtx walletdb.ReadWriteTx) error {
_, err := w.TxStore.CFilter(dbtx, get[len(get)-1])
if err == nil {
cont = true
return nil
}
return w.TxStore.InsertMissingCFilters(dbtx, get, filters)
})
if err != nil {
return err
}
if cont {
continue
}
if progress != nil {
progress <- MissingCFilterProgress{BlockHeightStart: height, BlockHeightEnd: height + span - 1}
}
log.Infof("Fetched cfilters for blocks %v-%v", height, height+span-1)
}
}
// FetchMissingCFilters records any missing compact filters for main chain
// blocks. A database upgrade requires all compact filters to be recorded for
// the main chain before any more blocks may be attached, but this information
// must be fetched at runtime after the upgrade as it is not already known at
// the time of upgrade.
func (w *Wallet) FetchMissingCFilters(ctx context.Context, p Peer) error {
const opf = "wallet.FetchMissingCFilters(%v)"
err := w.fetchMissingCFilters(ctx, p, nil)
if err != nil {
op := errors.Opf(opf, p)
return errors.E(op, err)
}
return nil
}
// MissingCFilterProgress records the first and last height of the progress
// that was received and any errors that were received during the fetching.
type MissingCFilterProgress struct {
Err error
BlockHeightStart int32
BlockHeightEnd int32
}
// FetchMissingCFiltersWithProgress records any missing compact filters for main chain
// blocks. A database upgrade requires all compact filters to be recorded for
// the main chain before any more blocks may be attached, but this information
// must be fetched at runtime after the upgrade as it is not already known at
// the time of upgrade. This function reports to a channel with any progress
// that may have seen.
func (w *Wallet) FetchMissingCFiltersWithProgress(ctx context.Context, p Peer, progress chan<- MissingCFilterProgress) {
const opf = "wallet.FetchMissingCFilters(%v)"
defer close(progress)
err := w.fetchMissingCFilters(ctx, p, progress)
if err != nil {
op := errors.Opf(opf, p)
progress <- MissingCFilterProgress{Err: errors.E(op, err)}
}
}
// createHeaderData creates the header data to process from hex-encoded
// serialized block headers.
func createHeaderData(headers []*wire.BlockHeader) ([]udb.BlockHeaderData, error) {
data := make([]udb.BlockHeaderData, len(headers))
var buf bytes.Buffer
for i, header := range headers {
var headerData udb.BlockHeaderData
headerData.BlockHash = header.BlockHash()
buf.Reset()
err := header.Serialize(&buf)
if err != nil {
return nil, err
}
copy(headerData.SerializedHeader[:], buf.Bytes())
data[i] = headerData
}
return data, nil
}
// log2 calculates an integer approximation of log2(x). This is used to
// approximate the cap to use when allocating memory for the block locators.
func log2(x int) int {
res := 0
for x != 0 {
x /= 2
res++
}
return res
}
// BlockLocators returns block locators, suitable for use in a getheaders wire
// message or dcrd JSON-RPC request, for the blocks in sidechain and saved in
// the wallet's main chain. For memory and lookup efficiency, many older hashes
// are skipped, with increasing gaps between included hashes.
//
// When sidechain has zero length, locators for only main chain blocks starting
// from the tip are returned. Otherwise, locators are created starting with the
// best (last) block of sidechain and sidechain[0] must be a child of a main
// chain block (sidechain may not contain orphan blocks).
func (w *Wallet) BlockLocators(sidechain []*BlockNode) ([]*chainhash.Hash, error) {
const op errors.Op = "wallet.BlockLocators"
var locators []*chainhash.Hash
err := walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
locators, err = w.blockLocators(dbtx, sidechain)
return err
})
if err != nil {
return nil, errors.E(op, err)
}
return locators, nil
}
func (w *Wallet) blockLocators(dbtx walletdb.ReadTx, sidechain []*BlockNode) ([]*chainhash.Hash, error) {
ns := dbtx.ReadBucket(wtxmgrNamespaceKey)
var hash chainhash.Hash
var height int32
if len(sidechain) == 0 {
hash, height = w.TxStore.MainChainTip(ns)
} else {
n := sidechain[len(sidechain)-1]
hash = *n.Hash
height = int32(n.Header.Height)
}
locators := make([]*chainhash.Hash, 1, 10+log2(int(height)))
locators[0] = &hash
var step int32 = 1
for height >= 0 {
if len(sidechain) > 0 && height-int32(sidechain[0].Header.Height) >= 0 {
n := sidechain[height-int32(sidechain[0].Header.Height)]
hash := n.Hash
locators = append(locators, hash)
} else {
hash, err := w.TxStore.GetMainChainBlockHashForHeight(ns, height)
if err != nil {
return nil, err
}
locators = append(locators, &hash)
}
height -= step
if len(locators) > 10 {
step *= 2
}
}
return locators, nil
}
func (w *Wallet) fetchHeaders(ctx context.Context, op errors.Op, p Peer) (firstNew chainhash.Hash, err error) {
var blockLocators []*chainhash.Hash
err = walletdb.View(w.db, func(dbtx walletdb.ReadTx) error {
var err error
blockLocators, err = w.blockLocators(dbtx, nil)
return err
})
if err != nil {
return firstNew, err
}
// Fetch and process headers until no more are returned.
hashStop := chainhash.Hash{}
for {
var chainBuilder SidechainForest
headers, err := p.GetHeaders(ctx, blockLocators, &hashStop)
if err != nil {
return firstNew, err
}
headerHashes := make([]*chainhash.Hash, 0, len(headers))
for _, h := range headers {
hash := h.BlockHash()
headerHashes = append(headerHashes, &hash)
}