This repository has been archived by the owner on Apr 2, 2024. It is now read-only.
generated from mrz1836/go-template
-
-
Notifications
You must be signed in to change notification settings - Fork 6
/
monitor_event_handler.go
466 lines (406 loc) · 14.8 KB
/
monitor_event_handler.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
package bux
import (
"context"
"encoding/json"
"fmt"
"runtime"
"strings"
"sync"
"time"
"github.com/BuxOrg/bux/chainstate"
"github.com/centrifugal/centrifuge-go"
"github.com/korovkin/limiter"
"github.com/libsv/go-bc"
"github.com/mrz1836/go-whatsonchain"
)
// MonitorEventHandler for handling transaction events from a monitor
type MonitorEventHandler struct {
blockSyncChannel chan bool
buxClient ClientInterface
ctx context.Context
debug bool
limit *limiter.ConcurrencyLimiter
logger chainstate.Logger
monitor chainstate.MonitorService
}
type blockSubscriptionHandler struct {
buxClient ClientInterface
ctx context.Context
debug bool
errors []error
logger chainstate.Logger
monitor chainstate.MonitorService
wg sync.WaitGroup
unsubscribed bool
}
func (b *blockSubscriptionHandler) OnPublish(subscription *centrifuge.Subscription, e centrifuge.PublishEvent) {
channelName := subscription.Channel()
if strings.HasPrefix(channelName, "block:sync:") {
// block subscription
tx, err := b.monitor.Processor().FilterTransactionPublishEvent(e.Data)
if err != nil {
b.errors = append(b.errors, err)
b.logger.Error(b.ctx, fmt.Sprintf("[MONITOR] Error processing block data: %s", err.Error()))
}
if tx == "" {
return
}
if _, err = recordMonitoredTransaction(b.ctx, b.buxClient, tx); err != nil {
b.logger.Error(b.ctx, fmt.Sprintf("[MONITOR] ERROR recording tx: %v", err))
b.errors = append(b.errors, err)
return
}
if b.debug {
b.logger.Info(b.ctx, fmt.Sprintf("[MONITOR] successfully recorded tx: %v", tx))
}
}
}
func (b *blockSubscriptionHandler) OnUnsubscribe(subscription *centrifuge.Subscription, e centrifuge.UnsubscribeEvent) {
b.logger.Info(b.ctx, fmt.Sprintf("[MONITOR] OnUnsubscribe: %s", subscription.Channel()))
// close wait group
if !b.unsubscribed {
b.wg.Done()
b.unsubscribed = true
}
}
// NewMonitorHandler create a new monitor handler
func NewMonitorHandler(ctx context.Context, buxClient ClientInterface, monitor chainstate.MonitorService) MonitorEventHandler {
return MonitorEventHandler{
buxClient: buxClient,
ctx: ctx,
debug: monitor.IsDebug(),
limit: limiter.NewConcurrencyLimiter(runtime.NumCPU()),
logger: monitor.Logger(),
monitor: monitor,
}
}
// OnConnect event when connected
func (h *MonitorEventHandler) OnConnect(client *centrifuge.Client, e centrifuge.ConnectEvent) {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] Connected to server: %s", e.ClientID))
agentClient := &chainstate.AgentClient{
Client: client,
}
filters := h.monitor.Processor().GetFilters()
for regex, bloomFilter := range filters {
if _, err := agentClient.SetFilter(regex, bloomFilter); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR processing mempool: %s", err.Error()))
}
}
if h.monitor.GetProcessMempoolOnConnect() {
h.logger.Info(h.ctx, "[MONITOR] PROCESS MEMPOOL")
go func() {
ctx := context.Background()
if err := h.monitor.ProcessMempool(ctx); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR processing mempool: %s", err.Error()))
}
}()
}
h.logger.Info(h.ctx, "[MONITOR] PROCESS BLOCK HEADERS")
if err := h.ProcessBlockHeaders(h.ctx, client); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR processing block headers: %s", err.Error()))
}
h.logger.Info(h.ctx, "[MONITOR] PROCESS BLOCKS")
h.blockSyncChannel = make(chan bool)
go func() {
ctx := context.Background()
if err := h.ProcessBlocks(ctx, client, h.blockSyncChannel); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR processing blocks: %s", err.Error()))
}
}()
h.monitor.Connected()
}
// ProcessBlocks processes all transactions in blocks that have not yet been synced
func (h *MonitorEventHandler) ProcessBlocks(ctx context.Context, client *centrifuge.Client, blockChannel chan bool) error {
h.logger.Info(ctx, "[MONITOR] ProcessBlocks start")
for {
// Check if channel has been closed
select {
case <-blockChannel:
h.logger.Info(ctx, "[MONITOR] block sync channel closed, stopping ProcessBlocks")
return nil
default:
// get all block headers that have not been marked as synced
blockHeaders, err := h.buxClient.GetUnsyncedBlockHeaders(ctx)
if err != nil {
h.logger.Error(ctx, err.Error())
} else {
h.logger.Info(ctx, fmt.Sprintf("[MONITOR] processing block headers: %d", len(blockHeaders)))
for _, blockHeader := range blockHeaders {
h.logger.Info(ctx, fmt.Sprintf("[MONITOR] Processing block %d: %s", blockHeader.Height, blockHeader.ID))
handler := &blockSubscriptionHandler{
buxClient: h.buxClient,
ctx: ctx,
debug: h.debug,
logger: h.logger,
monitor: h.monitor,
}
var subscription *centrifuge.Subscription
subscription, err = client.NewSubscription("block:sync:" + blockHeader.ID)
if err != nil {
h.logger.Error(ctx, err.Error())
} else {
h.logger.Info(ctx, fmt.Sprintf("[MONITOR] Starting block subscription: %v", subscription))
subscription.OnPublish(handler)
subscription.OnUnsubscribe(handler)
handler.wg.Add(1)
if err = subscription.Subscribe(); err != nil {
h.logger.Error(ctx, err.Error())
} else {
h.logger.Info(ctx, "[MONITOR] Waiting for wait group to finish")
handler.wg.Wait()
_ = subscription.Close()
if len(handler.errors) <= 0 {
// save that block header has been synced
blockHeader.Synced.Valid = true
blockHeader.Synced.Time = time.Now()
if err = blockHeader.Save(ctx); err != nil {
h.logger.Error(ctx, err.Error())
}
}
}
}
}
}
time.Sleep(defaultSleepForNewBlockHeaders)
}
}
}
// ProcessBlockHeaders processes all missing block headers
func (h *MonitorEventHandler) ProcessBlockHeaders(ctx context.Context, client *centrifuge.Client) error {
lastBlockHeader, err := h.buxClient.GetLastBlockHeader(ctx)
if err != nil {
h.logger.Error(h.ctx, err.Error())
return err
}
if lastBlockHeader == nil {
h.logger.Info(h.ctx, "no last block header found, skipping...")
return nil
}
var subscription *centrifuge.Subscription
subscription, err = client.NewSubscription("block:headers:history:" + fmt.Sprint(lastBlockHeader.Height))
if err != nil {
h.logger.Error(h.ctx, err.Error())
} else {
h.logger.Info(ctx, fmt.Sprintf("[MONITOR] Starting block header subscription: %v", subscription))
subscription.OnPublish(h)
if err = subscription.Subscribe(); err != nil {
h.logger.Error(h.ctx, err.Error())
}
}
return nil
}
// OnError on error event
func (h *MonitorEventHandler) OnError(_ *centrifuge.Client, e centrifuge.ErrorEvent) {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] Error: %s", e.Message))
}
// OnMessage on new message event
func (h *MonitorEventHandler) OnMessage(_ *centrifuge.Client, e centrifuge.MessageEvent) {
var data map[string]interface{}
err := json.Unmarshal(e.Data, &data)
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] failed unmarshalling data: %s", err.Error()))
}
if _, ok := data["time"]; !ok {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] OnMessage: %v", data))
}
}
// OnDisconnect when disconnected
func (h *MonitorEventHandler) OnDisconnect(_ *centrifuge.Client, _ centrifuge.DisconnectEvent) {
defer close(h.blockSyncChannel)
defer func(logger chainstate.Logger) {
ctx := context.Background()
rec := recover()
if rec != nil {
logger.Error(ctx, fmt.Sprintf("[MONITOR] Tried closing a closed channel: %v", rec))
}
}(h.logger)
h.monitor.Disconnected()
}
// OnJoin event when joining a server
func (h *MonitorEventHandler) OnJoin(_ *centrifuge.Subscription, e centrifuge.JoinEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnJoin: %v", e))
}
}
// OnLeave event when leaving a server
func (h *MonitorEventHandler) OnLeave(_ *centrifuge.Subscription, e centrifuge.LeaveEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnLeave: %v", e))
}
}
// OnPublish on publish event
func (h *MonitorEventHandler) OnPublish(subscription *centrifuge.Subscription, e centrifuge.PublishEvent) {
channelName := subscription.Channel()
if strings.HasPrefix(channelName, "block:headers:history:") {
bi := whatsonchain.BlockInfo{}
err := json.Unmarshal(e.Data, &bi)
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR unmarshalling block header: %v", err))
}
var existingBlock *BlockHeader
if existingBlock, err = h.buxClient.GetBlockHeaderByHeight(
h.ctx, uint32(bi.Height),
); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR getting block header by height: %v", err))
}
if existingBlock == nil {
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR unmarshalling block header: %v", err))
return
}
bh := bc.BlockHeader{
Bits: []byte(bi.Bits),
HashMerkleRoot: []byte(bi.MerkleRoot),
HashPrevBlock: []byte(bi.PreviousBlockHash),
Nonce: uint32(bi.Nonce),
Time: uint32(bi.Time),
Version: uint32(bi.Version),
}
if _, err = h.buxClient.RecordBlockHeader(
h.ctx, bi.Hash, uint32(bi.Height), bh,
); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR recording block header: %v", err))
return
}
}
} else {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnPublish: %v", e.Data))
}
}
}
// OnServerSubscribe on server subscribe event
func (h *MonitorEventHandler) OnServerSubscribe(_ *centrifuge.Client, e centrifuge.ServerSubscribeEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnServerSubscribe: %v", e))
}
}
// OnServerUnsubscribe on the unsubscribe event
func (h *MonitorEventHandler) OnServerUnsubscribe(_ *centrifuge.Client, e centrifuge.ServerUnsubscribeEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnServerUnsubscribe: %v", e))
}
}
// OnSubscribeSuccess on subscribe success
func (h *MonitorEventHandler) OnSubscribeSuccess(_ *centrifuge.Subscription, e centrifuge.SubscribeSuccessEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnSubscribeSuccess: %v", e))
}
}
// OnSubscribeError is for an error
func (h *MonitorEventHandler) OnSubscribeError(_ *centrifuge.Subscription, e centrifuge.SubscribeErrorEvent) {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] OnSubscribeError: %v", e))
}
// OnUnsubscribe will unsubscribe
func (h *MonitorEventHandler) OnUnsubscribe(_ *centrifuge.Subscription, e centrifuge.UnsubscribeEvent) {
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] OnUnsubscribe: %v", e))
}
}
// OnServerJoin event when joining a server
func (h *MonitorEventHandler) OnServerJoin(_ *centrifuge.Client, e centrifuge.ServerJoinEvent) {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] Joined server: %v", e))
}
// OnServerLeave event when leaving a server
func (h *MonitorEventHandler) OnServerLeave(_ *centrifuge.Client, e centrifuge.ServerLeaveEvent) {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] Left server: %v", e))
}
// OnServerPublish on server publish event
func (h *MonitorEventHandler) OnServerPublish(c *centrifuge.Client, e centrifuge.ServerPublishEvent) {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] Server publish to channel %s with data %v", e.Channel, string(e.Data)))
// todo make this configurable
// h.onServerPublishLinear(c, e)
h.onServerPublishParallel(c, e)
}
func (h *MonitorEventHandler) processMempoolPublish(_ *centrifuge.Client, e centrifuge.ServerPublishEvent) {
tx, err := h.monitor.Processor().FilterTransactionPublishEvent(e.Data)
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] failed to process server event: %v", err))
return
}
if h.monitor.SaveDestinations() {
// Process transaction and save outputs
// todo: replace printf
fmt.Printf("Should save the destination here...\n")
}
if tx == "" {
return
}
if _, err = recordMonitoredTransaction(h.ctx, h.buxClient, tx); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR recording tx: %v", err))
return
}
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] successfully recorded tx: %v", tx))
}
}
func (h *MonitorEventHandler) processBlockHeaderPublish(client *centrifuge.Client, e centrifuge.ServerPublishEvent) {
bi := whatsonchain.BlockInfo{}
err := json.Unmarshal(e.Data, &bi)
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR unmarshalling block header: %v", err))
return
}
bh := bc.BlockHeader{
HashPrevBlock: []byte(bi.PreviousBlockHash),
HashMerkleRoot: []byte(bi.MerkleRoot),
Nonce: uint32(bi.Nonce),
Version: uint32(bi.Version),
Time: uint32(bi.Time),
Bits: []byte(bi.Bits),
}
height := uint32(bi.Height)
var previousBlockHeader *BlockHeader
previousBlockHeader, err = getBlockHeaderByHeight(h.ctx, height-1, h.buxClient.DefaultModelOptions()...)
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR retreiving previous block header: %v", err))
return
}
if previousBlockHeader == nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR Previous block header not found: %d", height-1))
if err = h.ProcessBlockHeaders(h.ctx, client); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR processing block headers: %s", err.Error()))
}
return
}
if _, err = h.buxClient.RecordBlockHeader(h.ctx, bi.Hash, height, bh); err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR recording block header: %v", err))
return
}
if h.debug {
h.logger.Info(h.ctx, fmt.Sprintf("[MONITOR] successfully recorded blockheader: %v", bi.Hash))
}
}
func (h *MonitorEventHandler) onServerPublishLinear(c *centrifuge.Client, e centrifuge.ServerPublishEvent) {
switch e.Channel {
case "mempool:transactions":
h.processMempoolPublish(c, e)
case "block:headers":
h.processBlockHeaderPublish(c, e)
}
}
func (h *MonitorEventHandler) onServerPublishParallel(c *centrifuge.Client, e centrifuge.ServerPublishEvent) {
_, err := h.limit.Execute(func() {
h.onServerPublishLinear(c, e)
})
if err != nil {
h.logger.Error(h.ctx, fmt.Sprintf("[MONITOR] ERROR failed to start goroutine: %v", err))
}
}
// SetMonitor sets the monitor for the given handler
func (h *MonitorEventHandler) SetMonitor(monitor *chainstate.Monitor) {
h.monitor = monitor
}
// RecordTransaction records a transaction into bux
func (h *MonitorEventHandler) RecordTransaction(ctx context.Context, txHex string) error {
_, err := recordMonitoredTransaction(ctx, h.buxClient, txHex)
return err
}
// RecordBlockHeader records a block header into bux
func (h *MonitorEventHandler) RecordBlockHeader(_ context.Context, _ bc.BlockHeader) error {
return nil
}
// GetWhatsOnChain returns the WhatsOnChain client interface
func (h *MonitorEventHandler) GetWhatsOnChain() whatsonchain.ClientInterface {
return h.buxClient.Chainstate().WhatsOnChain()
}