-
Notifications
You must be signed in to change notification settings - Fork 176
/
slashing.go
452 lines (367 loc) · 15 KB
/
slashing.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
package processor
import (
"bytes"
"encoding/hex"
"errors"
sdk "github.com/cosmos/cosmos-sdk/types"
jsoniter "github.com/json-iterator/go"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
authTypes "github.com/maticnetwork/heimdall/auth/types"
"github.com/maticnetwork/heimdall/bridge/setu/util"
chainmanagerTypes "github.com/maticnetwork/heimdall/chainmanager/types"
"github.com/maticnetwork/heimdall/contracts/stakinginfo"
"github.com/maticnetwork/heimdall/helper"
slashingTypes "github.com/maticnetwork/heimdall/slashing/types"
hmTypes "github.com/maticnetwork/heimdall/types"
)
// SlashingProcessor - process slashing related events
type SlashingProcessor struct {
BaseProcessor
stakingInfoAbi *abi.ABI
}
// SlashingContext represents slashing context
type SlashingContext struct {
ChainmanagerParams *chainmanagerTypes.Params
}
// NewSlashingProcessor - add abi to slashing processor
func NewSlashingProcessor(stakingInfoAbi *abi.ABI) *SlashingProcessor {
return &SlashingProcessor{
stakingInfoAbi: stakingInfoAbi,
}
}
// Start starts new block subscription
func (sp *SlashingProcessor) Start() error {
sp.Logger.Info("Starting")
return nil
}
// RegisterTasks - Registers slashing related tasks with machinery
func (sp *SlashingProcessor) RegisterTasks() {
sp.Logger.Info("Registering slashing related tasks")
if err := sp.queueConnector.Server.RegisterTask("sendTickToHeimdall", sp.sendTickToHeimdall); err != nil {
sp.Logger.Error("Failed to register sendTickToHeimdall task", "error", err)
}
if err := sp.queueConnector.Server.RegisterTask("sendTickToRootchain", sp.sendTickToRootchain); err != nil {
sp.Logger.Error("Failed to register sendTickToRootchain task", "error", err)
}
if err := sp.queueConnector.Server.RegisterTask("sendTickAckToHeimdall", sp.sendTickAckToHeimdall); err != nil {
sp.Logger.Error("Failed to register sendTickAckToHeimdall task", "error", err)
}
if err := sp.queueConnector.Server.RegisterTask("sendUnjailToHeimdall", sp.sendUnjailToHeimdall); err != nil {
sp.Logger.Error("Failed to register sendUnjailToHeimdall task", "error", err)
}
}
// processSlashLimitEvent - processes slash limit event
func (sp *SlashingProcessor) sendTickToHeimdall(eventBytes string, blockHeight int64) error {
sp.Logger.Info("Received sendTickToHeimdall request", "eventBytes", eventBytes, "blockHeight", blockHeight)
var event sdk.StringEvent
if err := jsoniter.ConfigFastest.Unmarshal([]byte(eventBytes), &event); err != nil {
sp.Logger.Error("Error unmarshalling event from heimdall", "error", err)
return err
}
//Get latestSlashInoBytes from HeimdallServer
latestSlashInoBytes, err := sp.fetchLatestSlashInoBytes()
if err != nil {
sp.Logger.Info("Error while fetching latestSlashInoBytes from HeimdallServer", "err", err)
return err
}
var tickCount uint64
//Get tickCount from HeimdallServer
if tickCount, err = sp.fetchTickCount(); err != nil {
sp.Logger.Info("Error while fetching tick count from HeimdallServer", "err", err)
return err
}
sp.Logger.Info("processing slash-limit event", "eventtype", event.Type)
sp.Logger.Info("✅ Creating and broadcasting Tick tx",
"id", tickCount+1,
"From", hmTypes.BytesToHeimdallAddress(helper.GetAddress()),
"latestSlashInoBytes", latestSlashInoBytes.String(),
)
// create msg Tick message
msg := slashingTypes.NewMsgTick(
tickCount+1,
hmTypes.BytesToHeimdallAddress(helper.GetAddress()),
latestSlashInoBytes,
)
// return broadcast to heimdall
if err = sp.txBroadcaster.BroadcastToHeimdall(msg, event); err != nil {
sp.Logger.Error("Error while broadcasting Tick msg to heimdall", "error", err)
return err
}
return nil
}
/*
sendTickToRootchain - create and submit tick tx to rootchain to slashing faulty validators
1. Fetch sigs from heimdall using txHash
2. Fetch slashing info from heimdall via Rest call
3. Verify if this tick tx is already submitted to rootchain using nonce data
4. create tick tx and submit to rootchain
*/
func (sp *SlashingProcessor) sendTickToRootchain(eventBytes string, blockHeight int64) (err error) {
sp.Logger.Info("Received sendTickToRootchain request", "eventBytes", eventBytes, "blockHeight", blockHeight)
var event sdk.StringEvent
if err = jsoniter.ConfigFastest.Unmarshal([]byte(eventBytes), &event); err != nil {
sp.Logger.Error("Error unmarshalling event from heimdall", "error", err)
return err
}
slashInfoBytes := hmTypes.HexBytes{}
proposerAddr := hmTypes.ZeroHeimdallAddress
for _, attr := range event.Attributes {
if attr.Key == slashingTypes.AttributeKeyProposer {
proposerAddr = hmTypes.HexToHeimdallAddress(attr.Value)
}
if attr.Key == slashingTypes.AttributeKeySlashInfoBytes {
slashInfoBytes = hmTypes.HexToHexBytes(attr.Value)
}
}
sp.Logger.Info("processing tick confirmation event", "eventtype", event.Type, "slashInfoBytes", slashInfoBytes.String(), "proposer", proposerAddr)
// TODO - slashing...who should submit tick to rootchain??
isCurrentProposer, err := util.IsCurrentProposer(sp.cliCtx)
if err != nil {
sp.Logger.Error("Error checking isCurrentProposer", "error", err)
return err
}
// Fetch Tick val slashing info
tickSlashInfoList, err := sp.fetchTickSlashInfoList()
if err != nil {
sp.Logger.Error("Error fetching tick slash info list", "error", err)
return err
}
// Validate tickSlashInfoList
isValidSlashInfo, err := sp.validateTickSlashInfo(tickSlashInfoList, slashInfoBytes)
if err != nil {
sp.Logger.Error("Error validating tick slash info list", "error", err)
return err
}
var txHash string
for _, attr := range event.Attributes {
if attr.Key == hmTypes.AttributeKeyTxHash {
txHash = attr.Value
}
}
if isValidSlashInfo && isCurrentProposer {
txHashStr := common.FromHex(txHash)
if err = sp.createAndSendTickToRootchain(blockHeight, txHashStr, tickSlashInfoList, proposerAddr); err != nil {
sp.Logger.Error("Error sending tick to rootchain", "error", err)
return err
}
}
sp.Logger.Info("I am not the current proposer or tick already sent or invalid tick data... Ignoring", "eventType", event.Type)
return nil
}
/*
sendTickAckToHeimdall - sends tick ack msg to heimdall
*/
func (sp *SlashingProcessor) sendTickAckToHeimdall(eventName string, logBytes string) error {
var vLog = types.Log{}
if err := jsoniter.ConfigFastest.Unmarshal([]byte(logBytes), &vLog); err != nil {
sp.Logger.Error("Error while unmarshalling event from rootchain", "error", err)
return err
}
event := new(stakinginfo.StakinginfoSlashed)
if err := helper.UnpackLog(sp.stakingInfoAbi, event, eventName, &vLog); err != nil {
sp.Logger.Error("Error while parsing event", "name", eventName, "error", err)
} else {
if isOld, _ := sp.isOldTx(sp.cliCtx, vLog.TxHash.String(), uint64(vLog.Index), util.SlashingEvent, event); isOld {
sp.Logger.Info("Ignoring task to send tick ack to heimdall as already processed",
"event", eventName,
"tickID", event.Nonce,
"totalSlashedAmount", event.Amount.Uint64(),
"txHash", hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()),
"logIndex", uint64(vLog.Index),
"blockNumber", vLog.BlockNumber,
)
return nil
}
sp.Logger.Info(
"✅ Received task to send tick-ack to heimdall",
"event", eventName,
"tickID", event.Nonce,
"totalSlashedAmount", event.Amount.Uint64(),
"txHash", hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()),
"logIndex", uint64(vLog.Index),
"blockNumber", vLog.BlockNumber,
)
// TODO - check if i am the proposer of this tick ack or not.
// create msg tick ack message
msg := slashingTypes.NewMsgTickAck(helper.GetFromAddress(sp.cliCtx), event.Nonce.Uint64(), event.Amount.Uint64(), hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()), uint64(vLog.Index), vLog.BlockNumber)
// return broadcast to heimdall
if err = sp.txBroadcaster.BroadcastToHeimdall(msg, event); err != nil {
sp.Logger.Error("Error while broadcasting tick-ack to heimdall", "error", err)
return err
}
}
return nil
}
/*
sendUnjailToHeimdall - sends unjail msg to heimdall
*/
func (sp *SlashingProcessor) sendUnjailToHeimdall(eventName string, logBytes string) error {
var vLog = types.Log{}
if err := jsoniter.ConfigFastest.Unmarshal([]byte(logBytes), &vLog); err != nil {
sp.Logger.Error("Error while unmarshalling event from rootchain", "error", err)
return err
}
event := new(stakinginfo.StakinginfoUnJailed)
if err := helper.UnpackLog(sp.stakingInfoAbi, event, eventName, &vLog); err != nil {
sp.Logger.Error("Error while parsing event", "name", eventName, "error", err)
} else {
if isOld, _ := sp.isOldTx(sp.cliCtx, vLog.TxHash.String(), uint64(vLog.Index), util.SlashingEvent, event); isOld {
sp.Logger.Info("Ignoring sending unjail to heimdall as already processed",
"event", eventName,
"ValidatorID", event.ValidatorId,
"txHash", hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()),
"logIndex", uint64(vLog.Index),
"blockNumber", vLog.BlockNumber,
)
return nil
}
sp.Logger.Info(
"✅ Received task to send unjail to heimdall",
"event", eventName,
"ValidatorID", event.ValidatorId,
"txHash", hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()),
"logIndex", uint64(vLog.Index),
"blockNumber", vLog.BlockNumber,
)
// TODO - check if i am the proposer of unjail or not.
// msg unjail
msg := slashingTypes.NewMsgUnjail(
hmTypes.BytesToHeimdallAddress(helper.GetAddress()),
event.ValidatorId.Uint64(),
hmTypes.BytesToHeimdallHash(vLog.TxHash.Bytes()),
uint64(vLog.Index),
vLog.BlockNumber,
)
// return broadcast to heimdall
if err := sp.txBroadcaster.BroadcastToHeimdall(msg, event); err != nil {
sp.Logger.Error("Error while broadcasting unjail to heimdall", "error", err)
return err
}
}
return nil
}
// createAndSendTickToRootchain prepares the data required for rootchain tick submission
// and sends a transaction to rootchain
func (sp *SlashingProcessor) createAndSendTickToRootchain(height int64, txHash []byte, _ []*hmTypes.ValidatorSlashingInfo, _ hmTypes.HeimdallAddress) error {
sp.Logger.Info("Preparing tick to be pushed on chain", "height", height, "txHash", hmTypes.BytesToHeimdallHash(txHash))
// proof
tx, err := helper.QueryTxWithProof(sp.cliCtx, txHash)
if err != nil {
sp.Logger.Error("Error querying tick tx proof", "txHash", txHash)
return err
}
// fetch side txs sigs
decoder := helper.GetTxDecoder(authTypes.ModuleCdc)
stdTx, err := decoder(tx.Tx)
if err != nil {
sp.Logger.Error("Error while decoding tick tx", "txHash", tx.Tx.Hash(), "error", err)
return err
}
cmsg := stdTx.GetMsgs()[0]
sideMsg, ok := cmsg.(hmTypes.SideTxMsg)
if !ok {
sp.Logger.Error("Invalid side-tx msg", "txHash", tx.Tx.Hash())
return err
}
// side-tx data
sideTxData := sideMsg.GetSideSignBytes()
sp.Logger.Info("sideTx data", "sideTxData", hex.EncodeToString(sideTxData))
// get sigs
// TODO pass sigs in proper form in `SendTick` for slashing
// sigs, err := helper.FetchSideTxSigs(sp.httpClient, height, tx.Tx.Hash(), sideTxData)
// if err != nil {
// sp.Logger.Error("Error fetching votes for tick tx", "height", height)
// return err
// }
// send tick to rootchain
slashingContrext, err := sp.getSlashingContext()
if err != nil {
return err
}
chainParams := slashingContrext.ChainmanagerParams.ChainParams
slashManagerAddress := chainParams.SlashManagerAddress.EthAddress()
// slashmanage instance
slashManagerInstance, err := sp.contractConnector.GetSlashManagerInstance(slashManagerAddress)
if err != nil {
sp.Logger.Info("Error while creating slashmanager instance", "error", err)
return err
}
// TODO pass sigs in proper form in `SendTick` for slashing
if err := sp.contractConnector.SendTick(sideTxData, nil, slashManagerAddress, slashManagerInstance); err != nil {
sp.Logger.Info("Error submitting tick to slashManager contract", "error", err)
return err
}
return nil
}
// fetchLatestSlashInoBytes - fetches latest slashInfoBytes
func (sp *SlashingProcessor) fetchLatestSlashInoBytes() (slashInfoBytes hmTypes.HexBytes, err error) {
sp.Logger.Info("Sending Rest call to Get Latest SlashInfoBytes")
response, err := helper.FetchFromAPI(sp.cliCtx, helper.GetHeimdallServerEndpoint(util.LatestSlashInfoBytesURL))
if err != nil {
sp.Logger.Error("Error Fetching slashInfoBytes from HeimdallServer ", "error", err)
return slashInfoBytes, err
}
sp.Logger.Info("Latest slashInfoBytes fetched")
if err := jsoniter.ConfigFastest.Unmarshal(response.Result, &slashInfoBytes); err != nil {
sp.Logger.Error("Error unmarshalling latest slashInfoBytes received from Heimdall Server", "error", err)
return slashInfoBytes, err
}
return slashInfoBytes, nil
}
// fetchTickCount - fetches tick count
func (sp *SlashingProcessor) fetchTickCount() (tickCount uint64, err error) {
sp.Logger.Info("Sending Rest call to Get Tick count")
response, err := helper.FetchFromAPI(sp.cliCtx, helper.GetHeimdallServerEndpoint(util.SlashingTickCountURL))
if err != nil {
sp.Logger.Error("Error while sending request for tick count", "Error", err)
return tickCount, err
}
if err = jsoniter.ConfigFastest.Unmarshal(response.Result, &tickCount); err != nil {
sp.Logger.Error("Error unmarshalling tick count data ", "error", err)
return tickCount, err
}
return tickCount, nil
}
// fetchTickSlashInfoList - fetches tick slash Info list
func (sp *SlashingProcessor) fetchTickSlashInfoList() (slashInfoList []*hmTypes.ValidatorSlashingInfo, err error) {
sp.Logger.Info("Sending Rest call to Get Tick SlashInfo list")
response, err := helper.FetchFromAPI(sp.cliCtx, helper.GetHeimdallServerEndpoint(util.TickSlashInfoListURL))
if err != nil {
sp.Logger.Error("Error Fetching Tick slashInfoList from HeimdallServer ", "error", err)
return slashInfoList, err
}
sp.Logger.Info("Tick SlashInfo List fetched")
if err = jsoniter.ConfigFastest.Unmarshal(response.Result, &slashInfoList); err != nil {
sp.Logger.Error("Error unmarshalling tick slashinfo list received from Heimdall Server", "error", err)
return slashInfoList, err
}
return slashInfoList, nil
}
func (sp *SlashingProcessor) validateTickSlashInfo(slashInfoList []*hmTypes.ValidatorSlashingInfo, slashInfoBytes hmTypes.HexBytes) (isValid bool, err error) {
tickSlashInfoBytes, err := slashingTypes.SortAndRLPEncodeSlashInfos(slashInfoList)
if err != nil {
sp.Logger.Error("Error generating tick slashinfo bytes", "error", err)
return
}
// compare tickSlashInfoBytes with slashInfoBytes
if bytes.Equal(tickSlashInfoBytes, slashInfoBytes.Bytes()) {
return true, nil
}
sp.Logger.Info("SlashingInfoBytes mismatch", "tickSlashInfoBytes", hex.EncodeToString(tickSlashInfoBytes), "slashInfoBytes", slashInfoBytes)
return false, errors.New("Validation failed. tickSlashInfoBytes mismatch")
}
//
// utils
//
func (sp *SlashingProcessor) getSlashingContext() (*SlashingContext, error) {
chainmanagerParams, err := util.GetChainmanagerParams(sp.cliCtx)
if err != nil {
sp.Logger.Error("Error while fetching chain manager params", "error", err)
return nil, err
}
return &SlashingContext{
ChainmanagerParams: chainmanagerParams,
}, nil
}