forked from decred/dcrdata
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ntfnhandlers.go
243 lines (216 loc) · 6.46 KB
/
ntfnhandlers.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
// Copyright (c) 2017, Jonathan Chappelow
// See LICENSE for details.
package main
import (
"strings"
"sync"
"time"
"github.com/decred/dcrd/chaincfg/chainhash"
"github.com/decred/dcrd/dcrjson"
"github.com/decred/dcrd/dcrutil"
"github.com/decred/dcrd/rpcclient"
"github.com/decred/dcrd/wire"
"github.com/decred/dcrdata/blockdata"
"github.com/decred/dcrdata/db/dcrsqlite"
"github.com/decred/dcrdata/explorer"
"github.com/decred/dcrdata/mempool"
"github.com/decred/dcrdata/stakedb"
"github.com/decred/dcrwallet/wallet/udb"
)
func registerNodeNtfnHandlers(dcrdClient *rpcclient.Client) *ContextualError {
var err error
// Register for block connection and chain reorg notifications.
if err = dcrdClient.NotifyBlocks(); err != nil {
return newContextualError("block notification "+
"registration failed", err)
}
// Register for tx accepted into mempool ntfns
if err = dcrdClient.NotifyNewTransactions(true); err != nil {
return newContextualError("new transaction verbose notification registration failed", err)
}
// For OnNewTickets
// Commented since there is a bug in rpcclient/notify.go
// dcrdClient.NotifyNewTickets()
if err = dcrdClient.NotifyWinningTickets(); err != nil {
return newContextualError("winning ticket "+
"notification registration failed", err)
}
// Register a Tx filter for addresses (receiving). The filter applies to
// OnRelevantTxAccepted.
// TODO: register outpoints (third argument).
// if len(addresses) > 0 {
// if err = dcrdClient.LoadTxFilter(true, addresses, nil); err != nil {
// return newContextualError("load tx filter failed", err)
// }
// }
return nil
}
type blockHashHeight struct {
hash chainhash.Hash
height int64
}
type collectionQueue struct {
sync.Mutex
q chan *blockHashHeight
syncHandlers []func(hash *chainhash.Hash)
}
// newCollectionQueue creates a new collectionQueue with a queue channel large
// enough for 10 million block pointers.
func newCollectionQueue() *collectionQueue {
return &collectionQueue{
q: make(chan *blockHashHeight, 1e7),
}
}
func (q *collectionQueue) SetSynchronousHandlers(syncHandlers []func(hash *chainhash.Hash)) {
q.syncHandlers = syncHandlers
}
func (q *collectionQueue) ProcessBlocks() {
// process queued blocks one at a time
for bh := range q.q {
hash := bh.hash
height := bh.height
start := time.Now()
// Run synchronous block connected handlers in order
for _, h := range q.syncHandlers {
h(&hash)
}
log.Debugf("Synchronous handlers of collectionQueue.ProcessBlocks() completed in %v", time.Since(start))
// Signal to mempool monitors that a block was mined
select {
case ntfnChans.newTxChan <- &mempool.NewTx{
Hash: nil,
T: time.Now(),
}:
default:
}
select {
case ntfnChans.expNewTxChan <- &explorer.NewMempoolTx{
Hex: "",
}:
default:
}
// API status update handler
select {
case ntfnChans.updateStatusNodeHeight <- uint32(height):
default:
}
}
}
// func (q *collectionQueue) PushBlock(b *blockHashHeight) {
// q.blockQueue = append(q.blockQueue, b)
// }
// func (q *collectionQueue) PopBlock() *blockHashHeight {
// if len(q.blockQueue) == 0 {
// return nil
// }
// b := q.blockQueue[0]
// q.blockQueue = q.blockQueue[1:]
// return b
// }
// Define notification handlers
func makeNodeNtfnHandlers(cfg *config) (*rpcclient.NotificationHandlers, *collectionQueue) {
blockQueue := newCollectionQueue()
go blockQueue.ProcessBlocks()
return &rpcclient.NotificationHandlers{
OnBlockConnected: func(blockHeaderSerialized []byte, transactions [][]byte) {
blockHeader := new(wire.BlockHeader)
err := blockHeader.FromBytes(blockHeaderSerialized)
if err != nil {
log.Error("Failed to serialize blockHeader in new block notification.")
}
height := int32(blockHeader.Height)
hash := blockHeader.BlockHash()
// queue this block
blockQueue.q <- &blockHashHeight{
hash: hash,
height: int64(height),
}
},
OnReorganization: func(oldHash *chainhash.Hash, oldHeight int32,
newHash *chainhash.Hash, newHeight int32) {
// Send reorg data to dcrsqlite's monitor
select {
case ntfnChans.reorgChanWiredDB <- &dcrsqlite.ReorgData{
OldChainHead: *oldHash,
OldChainHeight: oldHeight,
NewChainHead: *newHash,
NewChainHeight: newHeight,
}:
default:
}
// Send reorg data to blockdata's monitor (so that it stops collecting)
select {
case ntfnChans.reorgChanBlockData <- &blockdata.ReorgData{
OldChainHead: *oldHash,
OldChainHeight: oldHeight,
NewChainHead: *newHash,
NewChainHeight: newHeight,
}:
default:
}
// Send reorg data to stakedb's monitor
select {
case ntfnChans.reorgChanStakeDB <- &stakedb.ReorgData{
OldChainHead: *oldHash,
OldChainHeight: oldHeight,
NewChainHead: *newHash,
NewChainHeight: newHeight,
}:
default:
}
},
OnWinningTickets: func(blockHash *chainhash.Hash, blockHeight int64,
tickets []*chainhash.Hash) {
var txstr []string
for _, t := range tickets {
txstr = append(txstr, t.String())
}
log.Tracef("Winning tickets: %v", strings.Join(txstr, ", "))
},
// maturing tickets. Thanks for fixing the tickets type bug, jolan!
OnNewTickets: func(hash *chainhash.Hash, height int64, stakeDiff int64,
tickets []*chainhash.Hash) {
for _, tick := range tickets {
log.Tracef("Mined new ticket: %v", tick.String())
}
},
// OnRelevantTxAccepted is invoked when a transaction containing a
// registered address is inserted into mempool.
OnRelevantTxAccepted: func(transaction []byte) {
rec, err := udb.NewTxRecord(transaction, time.Now())
if err != nil {
return
}
tx := dcrutil.NewTx(&rec.MsgTx)
txHash := rec.Hash
select {
case ntfnChans.relevantTxMempoolChan <- tx:
log.Debugf("Detected transaction %v in mempool containing registered address.",
txHash.String())
default:
}
},
// OnTxAcceptedVerbose is invoked same as OnTxAccepted but is used here
// for the mempool monitors to avoid an extra call to dcrd for
// the tx details
OnTxAcceptedVerbose: func(txDetails *dcrjson.TxRawResult) {
select {
case ntfnChans.expNewTxChan <- &explorer.NewMempoolTx{
Time: time.Now().Unix(),
Hex: txDetails.Hex,
}:
default:
log.Warn("expNewTxChan buffer full!")
}
hash, _ := chainhash.NewHashFromStr(txDetails.Txid)
select {
case ntfnChans.newTxChan <- &mempool.NewTx{
Hash: hash,
T: time.Now(),
}:
default:
log.Warn("newTxChan buffer full!")
}
},
}, blockQueue
}