/
rootchain.go
241 lines (196 loc) · 7.12 KB
/
rootchain.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
package listener
import (
"context"
"math/big"
"strconv"
"time"
"github.com/RichardKnop/machinery/v1/tasks"
ethereum "github.com/ethereum/go-ethereum"
"github.com/ethereum/go-ethereum/accounts/abi"
ethCommon "github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/rpc"
"github.com/maticnetwork/heimdall/bridge/setu/util"
chainmanagerTypes "github.com/maticnetwork/heimdall/chainmanager/types"
"github.com/maticnetwork/heimdall/helper"
)
// RootChainListenerContext root chain listener context
type RootChainListenerContext struct {
ChainmanagerParams *chainmanagerTypes.Params
}
// RootChainListener - Listens to and process events from rootchain
type RootChainListener struct {
BaseListener
// ABIs
abis []*abi.ABI
stakingInfoAbi *abi.ABI
stateSenderAbi *abi.ABI
// For self-heal, Will be only initialised if sub_graph_url is provided
subGraphClient *subGraphClient
}
const (
lastRootBlockKey = "rootchain-last-block" // storage key
)
// NewRootChainListener - constructor func
func NewRootChainListener() *RootChainListener {
contractCaller, err := helper.NewContractCaller()
if err != nil {
panic(err)
}
abis := []*abi.ABI{
&contractCaller.RootChainABI,
&contractCaller.StateSenderABI,
&contractCaller.StakingInfoABI,
}
return &RootChainListener{
abis: abis,
stakingInfoAbi: &contractCaller.StakingInfoABI,
stateSenderAbi: &contractCaller.StateSenderABI,
}
}
// Start starts new block subscription
func (rl *RootChainListener) Start() error {
rl.Logger.Info("Starting")
// create cancellable context
ctx, cancelSubscription := context.WithCancel(context.Background())
rl.cancelSubscription = cancelSubscription
// create cancellable context
headerCtx, cancelHeaderProcess := context.WithCancel(context.Background())
rl.cancelHeaderProcess = cancelHeaderProcess
// start header process
go rl.StartHeaderProcess(headerCtx)
// start go routine to poll for new header using client object
rl.Logger.Info("Start polling for rootchain header blocks", "pollInterval", helper.GetConfig().SyncerPollInterval)
// start polling for the finalized block in main chain (available post-merge)
go rl.StartPolling(ctx, helper.GetConfig().SyncerPollInterval, big.NewInt(int64(rpc.FinalizedBlockNumber)))
// Start self-healing process
go rl.startSelfHealing(ctx)
return nil
}
// ProcessHeader - process headerblock from rootchain
func (rl *RootChainListener) ProcessHeader(newHeader *blockHeader) {
rl.Logger.Debug("New block detected", "blockNumber", newHeader.header.Number)
// fetch context
rootchainContext, err := rl.getRootChainContext()
if err != nil {
return
}
requiredConfirmations := rootchainContext.ChainmanagerParams.MainchainTxConfirmations
headerNumber := newHeader.header.Number
from := headerNumber
// If incoming header is a `finalized` header, it can directly be considered as
// the upper cap (i.e. the `to` value)
//
// If incoming header is a `latest` header, rely on `requiredConfirmations` to get
// finalized block range.
if !newHeader.isFinalized {
// This check is only useful when the L1 blocks received are < requiredConfirmations
// just for the below headerNumber -= requiredConfirmations math operation
confirmationBlocks := big.NewInt(0).SetUint64(requiredConfirmations)
if headerNumber.Cmp(confirmationBlocks) <= 0 {
rl.Logger.Error("Block number less than Confirmations required", "blockNumber", headerNumber.Uint64, "confirmationsRequired", confirmationBlocks.Uint64)
return
}
// subtract the `confirmationBlocks` to only consider blocks before that
headerNumber = headerNumber.Sub(headerNumber, confirmationBlocks)
// update the `from` value
from = headerNumber
}
// get last block from storage
hasLastBlock, _ := rl.storageClient.Has([]byte(lastRootBlockKey), nil)
if hasLastBlock {
lastBlockBytes, err := rl.storageClient.Get([]byte(lastRootBlockKey), nil)
if err != nil {
rl.Logger.Info("Error while fetching last block bytes from storage", "error", err)
return
}
rl.Logger.Debug("Got last block from bridge storage", "lastBlock", string(lastBlockBytes))
if result, err := strconv.ParseUint(string(lastBlockBytes), 10, 64); err == nil {
if result >= headerNumber.Uint64() {
return
}
from = big.NewInt(0).SetUint64(result + 1)
}
}
to := headerNumber
// Prepare block range
if to.Cmp(from) == -1 {
from = to
}
// Set last block to storage
if err = rl.storageClient.Put([]byte(lastRootBlockKey), []byte(to.String()), nil); err != nil {
rl.Logger.Error("rl.storageClient.Put", "Error", err)
}
// Handle events
rl.queryAndBroadcastEvents(rootchainContext, from, to)
}
// queryAndBroadcastEvents fetches supported events from the rootchain and handles all of them
func (rl *RootChainListener) queryAndBroadcastEvents(rootchainContext *RootChainListenerContext, fromBlock *big.Int, toBlock *big.Int) {
rl.Logger.Info("Query rootchain event logs", "fromBlock", fromBlock, "toBlock", toBlock)
ctx, cancel := context.WithTimeout(context.Background(), rl.contractConnector.MainChainTimeout)
defer cancel()
// get chain params
chainParams := rootchainContext.ChainmanagerParams.ChainParams
// Fetch events from the rootchain
logs, err := rl.contractConnector.MainChainClient.FilterLogs(ctx, ethereum.FilterQuery{
FromBlock: fromBlock,
ToBlock: toBlock,
Addresses: []ethCommon.Address{
chainParams.RootChainAddress.EthAddress(),
chainParams.StakingInfoAddress.EthAddress(),
chainParams.StateSenderAddress.EthAddress(),
},
})
if err != nil {
rl.Logger.Error("Error while filtering logs", "error", err)
return
} else if len(logs) > 0 {
rl.Logger.Debug("New logs found", "numberOfLogs", len(logs))
}
// Process filtered log
for _, vLog := range logs {
topic := vLog.Topics[0].Bytes()
for _, abiObject := range rl.abis {
selectedEvent := helper.EventByID(abiObject, topic)
if selectedEvent == nil {
continue
}
rl.handleLog(vLog, selectedEvent)
}
}
}
func (rl *RootChainListener) SendTaskWithDelay(taskName string, eventName string, logBytes []byte, delay time.Duration, event interface{}) {
defer util.LogElapsedTimeForStateSyncedEvent(event, "SendTaskWithDelay", time.Now())
signature := &tasks.Signature{
Name: taskName,
Args: []tasks.Arg{
{
Type: "string",
Value: eventName,
},
{
Type: "string",
Value: string(logBytes),
},
},
}
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
rl.Logger.Info("Sending task", "taskName", taskName, "currentTime", time.Now(), "delayTime", eta)
_, err := rl.queueConnector.Server.SendTask(signature)
if err != nil {
rl.Logger.Error("Error sending task", "taskName", taskName, "error", err)
}
}
// getRootChainContext returns the root chain context
func (rl *RootChainListener) getRootChainContext() (*RootChainListenerContext, error) {
chainmanagerParams, err := util.GetChainmanagerParams(rl.cliCtx)
if err != nil {
rl.Logger.Error("Error while fetching chain manager params", "error", err)
return nil, err
}
return &RootChainListenerContext{
ChainmanagerParams: chainmanagerParams,
}, nil
}