/
maticchain.go
82 lines (64 loc) · 2.37 KB
/
maticchain.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
package listener
import (
"context"
"time"
"github.com/RichardKnop/machinery/v1/tasks"
"github.com/maticnetwork/heimdall/helper"
)
// MaticChainListener - Listens to and process headerblocks from maticchain
type MaticChainListener struct {
BaseListener
}
// NewMaticChainListener - constructor func
func NewMaticChainListener() *MaticChainListener {
return &MaticChainListener{}
}
// Start starts new block subscription
func (ml *MaticChainListener) Start() error {
ml.Logger.Info("Starting")
// create cancellable context
ctx, cancelSubscription := context.WithCancel(context.Background())
ml.cancelSubscription = cancelSubscription
// create cancellable context
headerCtx, cancelHeaderProcess := context.WithCancel(context.Background())
ml.cancelHeaderProcess = cancelHeaderProcess
// start header process
go ml.StartHeaderProcess(headerCtx)
// start go routine to poll for new header using client object
ml.Logger.Info("Start polling for header blocks", "pollInterval", helper.GetConfig().CheckpointerPollInterval)
// start polling for the latest block in child chain (replace with finalized block once we have it implemented)
go ml.StartPolling(ctx, helper.GetConfig().CheckpointerPollInterval, nil)
return nil
}
// ProcessHeader - process headerblock from maticchain
func (ml *MaticChainListener) ProcessHeader(newHeader *blockHeader) {
ml.Logger.Debug("New block detected", "blockNumber", newHeader.header.Number)
// Marshall header block and publish to queue
headerBytes, err := newHeader.header.MarshalJSON()
if err != nil {
ml.Logger.Error("Error marshalling header block", "error", err)
return
}
ml.sendTaskWithDelay("sendCheckpointToHeimdall", headerBytes, 0)
}
func (ml *MaticChainListener) sendTaskWithDelay(taskName string, headerBytes []byte, delay time.Duration) {
// create machinery task
signature := &tasks.Signature{
Name: taskName,
Args: []tasks.Arg{
{
Type: "string",
Value: string(headerBytes),
},
},
}
signature.RetryCount = 3
// add delay for task so that multiple validators won't send same transaction at same time
eta := time.Now().Add(delay)
signature.ETA = &eta
ml.Logger.Debug("Sending task", "taskname", taskName, "currentTime", time.Now(), "delayTime", eta)
_, err := ml.queueConnector.Server.SendTask(signature)
if err != nil {
ml.Logger.Error("Error sending task", "taskName", taskName, "error", err)
}
}