forked from decred/dcrwallet
/
chain.go
489 lines (439 loc) · 13.2 KB
/
chain.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
// Copyright (c) 2013-2015 The btcsuite developers
// Copyright (c) 2015-2016 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"
"errors"
"fmt"
"sync"
"time"
"github.com/decred/dcrd/chaincfg"
"github.com/decred/dcrd/chaincfg/chainhash"
dcrrpcclient "github.com/decred/dcrd/rpcclient"
)
var requiredChainServerAPI = semver{major: 3, minor: 1, patch: 0}
// RPCClient represents a persistent client connection to a decred RPC server
// for information regarding the current best block chain.
type RPCClient struct {
*dcrrpcclient.Client
connConfig *dcrrpcclient.ConnConfig // Work around unexported field
chainParams *chaincfg.Params
enqueueNotification chan interface{}
dequeueNotification chan interface{}
enqueueVotingNotification chan interface{}
dequeueVotingNotification chan interface{}
quit chan struct{}
wg sync.WaitGroup
started bool
quitMtx sync.Mutex
}
// NewRPCClient creates a client connection to the server described by the
// connect string. If disableTLS is false, the remote RPC certificate must be
// provided in the certs slice. The connection is not established immediately,
// but must be done using the Start method. If the remote server does not
// operate on the same decred network as described by the passed chain
// parameters, the connection will be disconnected.
func NewRPCClient(chainParams *chaincfg.Params, connect, user, pass string, certs []byte,
disableTLS bool) (*RPCClient, error) {
client := &RPCClient{
connConfig: &dcrrpcclient.ConnConfig{
Host: connect,
Endpoint: "ws",
User: user,
Pass: pass,
Certificates: certs,
DisableAutoReconnect: true,
DisableConnectOnNew: true,
DisableTLS: disableTLS,
},
chainParams: chainParams,
enqueueNotification: make(chan interface{}),
dequeueNotification: make(chan interface{}),
enqueueVotingNotification: make(chan interface{}),
dequeueVotingNotification: make(chan interface{}),
quit: make(chan struct{}),
}
ntfnCallbacks := &dcrrpcclient.NotificationHandlers{
OnBlockConnected: client.onBlockConnected,
OnBlockDisconnected: client.onBlockDisconnected,
OnRelevantTxAccepted: client.onRelevantTxAccepted,
OnReorganization: client.onReorganization,
OnWinningTickets: client.onWinningTickets,
OnSpentAndMissedTickets: client.onSpentAndMissedTickets,
OnStakeDifficulty: client.onStakeDifficulty,
}
rpcClient, err := dcrrpcclient.New(client.connConfig, ntfnCallbacks)
if err != nil {
return nil, err
}
client.Client = rpcClient
return client, nil
}
// Start attempts to establish a client connection with the remote server.
// If successful, handler goroutines are started to process notifications
// sent by the server. After a limited number of connection attempts, this
// function gives up, and therefore will not block forever waiting for the
// connection to be established to a server that may not exist.
func (c *RPCClient) Start(ctx context.Context, retry bool) (err error) {
err = c.Client.Connect(ctx, retry)
if err != nil {
return err
}
defer func() {
if err != nil {
c.Disconnect()
}
}()
// Verify that the server is running on the expected network.
net, err := c.Client.GetCurrentNet()
if err != nil {
return err
}
if net != c.chainParams.Net {
return errors.New("mismatched networks")
}
// Ensure the RPC server has a compatible API version.
var serverAPI semver
versions, err := c.Client.Version()
if err == nil {
versionResult := versions["dcrdjsonrpcapi"]
serverAPI = semver{
major: versionResult.Major,
minor: versionResult.Minor,
patch: versionResult.Patch,
}
}
if !semverCompatible(requiredChainServerAPI, serverAPI) {
return fmt.Errorf("consensus JSON-RPC server does not have a "+
"compatible API version: advertises %v but require %v",
serverAPI, requiredChainServerAPI)
}
c.quitMtx.Lock()
c.started = true
c.quitMtx.Unlock()
c.wg.Add(2)
go c.handler()
go c.handlerVoting()
return nil
}
// Stop disconnects the client and signals the shutdown of all goroutines
// started by Start.
func (c *RPCClient) Stop() {
c.quitMtx.Lock()
select {
case <-c.quit:
default:
close(c.quit)
c.Client.Shutdown()
if !c.started {
close(c.dequeueNotification)
close(c.dequeueVotingNotification)
}
}
c.quitMtx.Unlock()
}
// WaitForShutdown blocks until both the client has finished disconnecting
// and all handlers have exited.
func (c *RPCClient) WaitForShutdown() {
c.Client.WaitForShutdown()
c.wg.Wait()
}
// Notification types. These are defined here and processed from from reading
// a notificationChan to avoid handling these notifications directly in
// dcrrpcclient callbacks, which isn't very Go-like and doesn't allow
// blocking client calls.
type (
// blockConnected is a notification for a newly-attached block to the
// best chain.
blockConnected struct {
blockHeader []byte
transactions [][]byte
}
// blockDisconnected is a notifcation that the block described by the header
// was reorganized out of the best chain.
blockDisconnected struct {
blockHeader []byte
}
// relevantTxAccepted is a notification that a transaction accepted by
// mempool passed the client's transaction filter.
relevantTxAccepted struct {
transaction []byte
}
// reorganization is a notification that a reorg has happen with the new
// old and new tip included.
reorganization struct {
oldHash *chainhash.Hash
oldHeight int64
newHash *chainhash.Hash
newHeight int64
}
// winningTickets is a notification with the winning tickets (and the
// block they are in.
winningTickets struct {
blockHash *chainhash.Hash
blockHeight int64
tickets []*chainhash.Hash
}
// missedTickets is a notifcation for tickets that have been missed.
missedTickets struct {
blockHash *chainhash.Hash
blockHeight int64
tickets []*chainhash.Hash
}
// stakeDifficulty is a notification for the current stake difficulty.
stakeDifficulty struct {
blockHash *chainhash.Hash
blockHeight int64
stakeDiff int64
}
)
// notifications returns a channel of parsed notifications sent by the remote
// decred RPC server. This channel must be continually read or the process
// may abort for running out memory, as unread notifications are queued for
// later reads.
func (c *RPCClient) notifications() <-chan interface{} {
return c.dequeueNotification
}
// notificationsVoting returns a channel of parsed voting notifications sent
// by the remote RPC server. This channel must be continually read or the
// process may abort for running out memory, as unread notifications are
// queued for later reads.
func (c *RPCClient) notificationsVoting() <-chan interface{} {
return c.dequeueVotingNotification
}
func (c *RPCClient) onBlockConnected(header []byte, transactions [][]byte) {
select {
case c.enqueueNotification <- blockConnected{
blockHeader: header,
transactions: transactions,
}:
case <-c.quit:
}
}
func (c *RPCClient) onBlockDisconnected(header []byte) {
select {
case c.enqueueNotification <- blockDisconnected{
blockHeader: header,
}:
case <-c.quit:
}
}
func (c *RPCClient) onRelevantTxAccepted(transaction []byte) {
select {
case c.enqueueNotification <- relevantTxAccepted{
transaction: transaction,
}:
case <-c.quit:
}
}
// onReorganization handles reorganization notifications and passes them
// downstream to the notifications queue.
func (c *RPCClient) onReorganization(oldHash *chainhash.Hash, oldHeight int32,
newHash *chainhash.Hash, newHeight int32) {
select {
case c.enqueueNotification <- reorganization{
oldHash,
int64(oldHeight),
newHash,
int64(newHeight),
}:
case <-c.quit:
}
}
// onWinningTickets handles winning tickets notifications data and passes it
// downstream to the notifications queue.
func (c *RPCClient) onWinningTickets(hash *chainhash.Hash, height int64, tickets []*chainhash.Hash) {
select {
case c.enqueueVotingNotification <- winningTickets{
blockHash: hash,
blockHeight: height,
tickets: tickets,
}:
case <-c.quit:
}
}
// onSpentAndMissedTickets handles missed tickets notifications data and passes
// it downstream to the notifications queue.
func (c *RPCClient) onSpentAndMissedTickets(blockHash *chainhash.Hash, height int64, sdiff int64, tickets map[chainhash.Hash]bool) {
var missed []*chainhash.Hash
// Copy the missed ticket hashes to a slice.
for ticketHash, spent := range tickets {
if !spent {
ticketHash := ticketHash
missed = append(missed, &ticketHash)
}
}
if len(missed) == 0 {
return
}
select {
case c.enqueueNotification <- missedTickets{
blockHash: blockHash,
blockHeight: height,
tickets: missed,
}:
case <-c.quit:
}
}
// onStakeDifficulty handles stake difficulty notifications data and passes it
// downstream to the notification queue.
func (c *RPCClient) onStakeDifficulty(hash *chainhash.Hash,
height int64,
stakeDiff int64) {
select {
case c.enqueueNotification <- stakeDifficulty{
hash,
height,
stakeDiff,
}:
case <-c.quit:
}
}
// handler maintains a queue of notifications and the current state (best
// block) of the chain.
func (c *RPCClient) handler() {
// TODO: Rather than leaving this as an unbounded queue for all types of
// notifications, try dropping ones where a later enqueued notification
// can fully invalidate one waiting to be processed. For example,
// blockconnected notifications for greater block heights can remove the
// need to process earlier blockconnected notifications still waiting
// here.
var notifications []interface{}
enqueue := c.enqueueNotification
var dequeue chan interface{}
var next interface{}
pingChan := time.After(time.Minute)
pingChanReset := make(chan (<-chan time.Time))
out:
for {
select {
case n, ok := <-enqueue:
if !ok {
// If no notifications are queued for handling,
// the queue is finished.
if len(notifications) == 0 {
break out
}
// nil channel so no more reads can occur.
enqueue = nil
continue
}
if len(notifications) == 0 {
next = n
dequeue = c.dequeueNotification
}
notifications = append(notifications, n)
pingChan = time.After(time.Minute)
case dequeue <- next:
notifications[0] = nil
notifications = notifications[1:]
if len(notifications) != 0 {
next = notifications[0]
} else {
// If no more notifications can be enqueued, the
// queue is finished.
if enqueue == nil {
break out
}
dequeue = nil
}
case <-pingChan:
// No notifications were received in the last 60s. Ensure the
// connection is still active by making a new request to the server.
//
// This MUST wait for the response in a new goroutine so as to not
// block channel sends enqueueing more notifications. Doing so
// would cause a deadlock and after the timeout expires, the client
// would be shut down.
//
// TODO: A minute timeout is used to prevent the handler loop from
// blocking here forever, but this is much larger than it needs to
// be due to dcrd processing websocket requests synchronously (see
// https://github.com/btcsuite/btcd/issues/504). Decrease this to
// something saner like 3s when the above issue is fixed.
type sessionResult struct {
err error
}
sessionResponse := make(chan sessionResult, 1)
go func() {
_, err := c.Session()
sessionResponse <- sessionResult{err}
}()
go func() {
select {
case resp := <-sessionResponse:
if resp.err != nil {
log.Errorf("Failed to receive session "+
"result: %v", resp.err)
c.Stop()
}
pingChanReset <- time.After(time.Minute)
case <-time.After(time.Minute):
log.Errorf("Timeout waiting for session RPC")
c.Stop()
}
}()
case ch := <-pingChanReset:
pingChan = ch
case <-c.quit:
break out
}
}
c.Stop()
close(c.dequeueNotification)
c.wg.Done()
}
// handler maintains a queue of notifications and the current state (best
// block) of the chain.
func (c *RPCClient) handlerVoting() {
var notifications []interface{}
enqueue := c.enqueueVotingNotification
var dequeue chan interface{}
var next interface{}
out:
for {
select {
case n, ok := <-enqueue:
if !ok {
// If no notifications are queued for handling,
// the queue is finished.
if len(notifications) == 0 {
break out
}
// nil channel so no more reads can occur.
enqueue = nil
continue
}
if len(notifications) == 0 {
next = n
dequeue = c.dequeueVotingNotification
}
notifications = append(notifications, n)
case dequeue <- next:
notifications[0] = nil
notifications = notifications[1:]
if len(notifications) != 0 {
next = notifications[0]
} else {
// If no more notifications can be enqueued, the
// queue is finished.
if enqueue == nil {
break out
}
dequeue = nil
}
case <-c.quit:
break out
}
}
close(c.dequeueVotingNotification)
c.wg.Done()
}
// POSTClient creates the equivalent HTTP POST dcrrpcclient.Client.
func (c *RPCClient) POSTClient() (*dcrrpcclient.Client, error) {
configCopy := *c.connConfig
configCopy.HTTPPostMode = true
return dcrrpcclient.New(&configCopy, nil)
}