forked from decred/dcrwallet
/
sync.go
227 lines (195 loc) · 6.19 KB
/
sync.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
// Copyright (c) 2017 The Decred developers
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package chain
import (
"context"
"fmt"
"github.com/decred/dcrwallet/apperrors"
"github.com/decred/dcrwallet/wallet"
"golang.org/x/sync/errgroup"
)
// RPCSyncer implements wallet synchronization services by processing
// notifications from a dcrd JSON-RPC server.
type RPCSyncer struct {
wallet *wallet.Wallet
rpcClient *RPCClient
}
// NewRPCSyncer creates an RPCSyncer that will sync the wallet using the RPC
// client.
func NewRPCSyncer(w *wallet.Wallet, rpcClient *RPCClient) *RPCSyncer {
return &RPCSyncer{w, rpcClient}
}
// Run synchronizes the wallet, returning when synchronization fails or the
// context is cancelled. If startupSync is true, all synchronization tasks
// needed to fully register the wallet for notifications and synchronize it with
// the dcrd server are performed. Otherwise, it will listen for notifications
// but not register for any updates.
func (s *RPCSyncer) Run(ctx context.Context, startupSync bool) error {
// TODO: handling of voting notifications should be done sequentially with
// every other notification (voters must know the blocks they are voting
// on). Until then, a couple notification processing goroutines must be
// started and errors merged.
g, ctx := errgroup.WithContext(ctx)
g.Go(func() error {
if startupSync {
err := s.startupSync(ctx)
if err != nil {
return err
}
}
return s.handleNotifications(ctx)
})
g.Go(func() error {
return s.handleVoteNotifications(ctx)
})
g.Go(func() error {
err := s.rpcClient.NotifySpentAndMissedTickets()
if err != nil {
return fmt.Errorf("failed to register for spentandmissedtickets "+
"notifications: %v", err)
}
if s.wallet.VotingEnabled() {
// Request notifications for winning tickets.
err := s.rpcClient.NotifyWinningTickets()
if err != nil {
return fmt.Errorf("failed to register for winningtickets "+
"notifications: %v", err)
}
vb := s.wallet.VoteBits()
log.Infof("Wallet voting enabled: vote bits = %#04x, "+
"extended vote bits = %x", vb.Bits, vb.ExtendedBits)
log.Infof("Please ensure your wallet remains unlocked so it may vote")
}
return nil
})
return g.Wait()
}
func (s *RPCSyncer) handleNotifications(ctx context.Context) error {
// connectingBlocks keeps track of whether any blocks have been successfully
// attached to the main chain. Once any blocks have attached, if a future
// block fails to attach, the error is fatal. Otherwise, errors are logged.
connectingBlocks := false
c := s.rpcClient.notifications()
for {
select {
case <-ctx.Done():
return ctx.Err()
case n, ok := <-c:
if !ok {
return apperrors.New(apperrors.ErrDisconnected, "RPC client disconnected")
}
var notificationName string
var err error
nonFatal := false
switch n := n.(type) {
case blockConnected:
notificationName = "blockconnected"
err = s.wallet.ConnectBlock(n.blockHeader, n.transactions)
if err == nil {
connectingBlocks = true
}
nonFatal = !connectingBlocks
case blockDisconnected:
continue // These notifications are ignored
case reorganization:
notificationName = "reorganizing"
err = s.wallet.StartReorganize(n.oldHash, n.newHash, n.oldHeight, n.newHeight)
case relevantTxAccepted:
notificationName = "relevanttxaccepted"
err = s.wallet.AcceptMempoolTx(n.transaction)
nonFatal = true
case missedTickets:
notificationName = "spentandmissedtickets"
err = s.wallet.RevokeOwnedTickets(n.tickets)
nonFatal = true
default:
log.Warnf("Notification handler received unknown notification type %T", n)
continue
}
switch {
case err == nil:
case nonFatal:
log.Errorf("Failed to process consensus server notification "+
"(name: `%s`, detail: `%v`)", notificationName, err)
default:
return fmt.Errorf("failed to process consensus server notification "+
"(name: `%s`, detail: `%v`)", notificationName, err)
}
}
}
}
func (s *RPCSyncer) handleVoteNotifications(ctx context.Context) error {
c := s.rpcClient.notificationsVoting()
for {
select {
case <-ctx.Done():
return ctx.Err()
case n, ok := <-c:
if !ok {
return apperrors.New(apperrors.ErrDisconnected, "RPC client disconnected")
}
var notificationName string
var err error
switch n := n.(type) {
case winningTickets:
notificationName = "winningtickets"
err = s.wallet.VoteOnOwnedTickets(n.tickets, n.blockHash, int32(n.blockHeight))
default:
log.Warnf("Voting handler received unknown notification type %T", n)
}
if err != nil {
log.Errorf("Failed to handle %s notification: %v", notificationName, err)
}
}
}
}
// startupSync brings the wallet up to date with the current chain server
// connection. It creates a rescan request and blocks until the rescan has
// finished.
func (s *RPCSyncer) startupSync(ctx context.Context) error {
// Request notifications for connected and disconnected blocks.
err := s.rpcClient.NotifyBlocks()
if err != nil {
return err
}
n := BackendFromRPCClient(s.rpcClient.Client)
// Discover any addresses for this wallet that have not yet been created.
err = s.wallet.DiscoverActiveAddresses(n, !s.wallet.Locked())
if err != nil {
return err
}
// Load transaction filters with all active addresses and watched outpoints.
err = s.wallet.LoadActiveDataFilters(n)
if err != nil {
return err
}
// Fetch headers for unseen blocks in the main chain, determine whether a
// rescan is necessary, and when to begin it.
fetchedHeaderCount, rescanStart, _, _, _, err := s.wallet.FetchHeaders(n)
if err != nil {
return err
}
// Rescan when necessary.
if fetchedHeaderCount != 0 {
err := s.wallet.Rescan(ctx, n, &rescanStart)
if err != nil {
return err
}
}
// Rebroadcast unmined transactions
err = s.wallet.PublishUnminedTransactions(ctx, n)
if err != nil {
return err
}
_, err = s.rpcClient.RawRequest("rebroadcastwinners", nil)
if err != nil {
return err
}
_, err = s.rpcClient.RawRequest("rebroadcastmissed", nil)
if err != nil {
return err
}
log.Infof("Blockchain sync completed, wallet ready for general usage.")
return nil
}