forked from solarlabsteam/missed-blocks-checker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtelegram.go
536 lines (447 loc) · 15.7 KB
/
telegram.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
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"strings"
"time"
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
"github.com/BurntSushi/toml"
tb "gopkg.in/tucnak/telebot.v2"
)
type TelegramReporter struct {
TelegramToken string
TelegramChat int
TelegramConfigPath string
TelegramConfig TelegramConfig
TelegramBot *tb.Bot
}
type NotificationInfo struct {
ValidatorAddress string
Notifiers []string
}
type TelegramConfig struct {
NotiticationInfos []*NotificationInfo
}
func (i *NotificationInfo) addNotifier(notifier string) error {
if stringInSlice(notifier, i.Notifiers) {
return fmt.Errorf("You are already subscribed to this validator's notifications.") //nolint
}
i.Notifiers = append(i.Notifiers, notifier)
return nil
}
func (i *NotificationInfo) removeNotifier(notifier string) error {
if !stringInSlice(notifier, i.Notifiers) {
return fmt.Errorf("You are not subscribed to this validator's notifications.") //nolint
}
i.Notifiers = removeFromSlice(i.Notifiers, notifier)
return nil
}
func (c *TelegramConfig) getNotifiedValidators(notifier string) []string {
validators := []string{}
for _, info := range c.NotiticationInfos {
if stringInSlice(notifier, info.Notifiers) {
validators = append(validators, info.ValidatorAddress)
}
}
return validators
}
func (c *TelegramConfig) addNotifier(validatorAddress string, notifierToAdd string) error {
for _, notifier := range c.NotiticationInfos {
if notifier.ValidatorAddress == validatorAddress {
return notifier.addNotifier(notifierToAdd)
}
}
newNotificationInfo := NotificationInfo{ValidatorAddress: validatorAddress, Notifiers: []string{notifierToAdd}}
c.NotiticationInfos = append(c.NotiticationInfos, &newNotificationInfo)
return nil
}
func (c *TelegramConfig) removeNotifier(validatorAddress string, notifierToAdd string) error {
for _, notifier := range c.NotiticationInfos {
if notifier.ValidatorAddress == validatorAddress {
return notifier.removeNotifier(notifierToAdd)
}
}
return fmt.Errorf("You are not subscribed to this validator's notifications.") //nolint
}
func (c *TelegramConfig) getNotifiersSerialized(address string) string {
var sb strings.Builder
for _, validator := range c.NotiticationInfos {
if validator.ValidatorAddress == address {
for _, notifier := range validator.Notifiers {
sb.WriteString("@" + notifier + " ")
}
}
}
return sb.String()
}
func (r TelegramReporter) Serialize(report Report) string {
var sb strings.Builder
for _, entry := range report.Entries {
var (
emoji string
status string
validatorLink string
timeToJail string = ""
)
switch entry.Direction {
case START_MISSING_BLOCKS:
emoji = "🚨"
status = "is missing blocks"
timeToJail = fmt.Sprintf(" (%s till jail)", entry.GetTimeToJail())
case MISSING_BLOCKS:
emoji = "🔴"
status = "is missing blocks"
timeToJail = fmt.Sprintf(" (%s till jail)", entry.GetTimeToJail())
case STOPPED_MISSING_BLOCKS:
emoji = "🟡"
status = "stopped missing blocks"
case WENT_BACK_TO_NORMAL:
emoji = "🟢"
status = "went back to normal"
case JAILED:
emoji = "❌"
status = "was jailed"
}
if entry.ValidatorAddress != "" && entry.ValidatorMoniker != "" {
validatorLink = fmt.Sprintf(
"<a href=\"https://www.mintscan.io/%s/validators/%s\">%s</a>",
MintscanPrefix,
entry.ValidatorAddress,
entry.ValidatorMoniker,
)
} else if entry.ValidatorMoniker == "" { // validator with empty moniker, can happen
validatorLink = fmt.Sprintf(
"<a href=\"https://www.mintscan.io/%s/validators/%s\">%s</a>",
MintscanPrefix,
entry.ValidatorAddress,
entry.ValidatorAddress,
)
} else {
validatorLink = fmt.Sprintf("<code>%s</code>", entry.Pubkey)
}
notifiers := r.TelegramConfig.getNotifiersSerialized(entry.ValidatorAddress)
sb.WriteString(fmt.Sprintf(
"%s <strong>%s %s</strong>: %d -> %d%s %s\n",
emoji,
validatorLink,
status,
entry.BeforeBlocksMissing,
entry.NowBlocksMissing,
timeToJail,
notifiers,
))
}
return sb.String()
}
func (r *TelegramReporter) Init() {
if r.TelegramToken == "" || r.TelegramChat == 0 || r.TelegramConfigPath == "" {
log.Debug().Msg("Telegram credentials or config path not set, not creating Telegram reporter.")
return
}
bot, err := tb.NewBot(tb.Settings{
Token: TelegramToken,
Poller: &tb.LongPoller{Timeout: 10 * time.Second},
})
if err != nil {
log.Warn().Err(err).Msg("Could not create Telegram bot")
return
}
r.TelegramBot = bot
r.TelegramBot.Handle("/start", r.getHelp)
r.TelegramBot.Handle("/help", r.getHelp)
r.TelegramBot.Handle("/status", r.getValidatorStatus)
r.TelegramBot.Handle("/subscribe", r.subscribeToValidatorUpdates)
r.TelegramBot.Handle("/unsubscribe", r.unsubscribeFromValidatorUpdates)
go r.TelegramBot.Start()
r.loadConfigFromYaml()
}
func (r TelegramReporter) Enabled() bool {
return r.TelegramBot != nil
}
func (r TelegramReporter) SendReport(report Report) error {
serializedReport := r.Serialize(report)
_, err := r.TelegramBot.Send(
&tb.User{
ID: r.TelegramChat,
},
serializedReport,
tb.ModeHTML,
)
return err
}
func (r TelegramReporter) Name() string {
return "TelegramReporter"
}
func (r TelegramReporter) sendMessage(message *tb.Message, text string) {
_, err := r.TelegramBot.Send(
message.Chat,
text,
&tb.SendOptions{
ParseMode: tb.ModeHTML,
ReplyTo: message,
},
)
if err != nil {
log.Error().Err(err).Msg("Could not send Telegram message")
}
}
func (r TelegramReporter) getHelp(message *tb.Message) {
var sb strings.Builder
sb.WriteString("<strong>missed-block-checker</strong>\n\n")
sb.WriteString(fmt.Sprintf("Query for the %s network info.\n", MintscanPrefix))
sb.WriteString("Can understand the following commands:\n")
sb.WriteString("- /subscribe <validator address> - be notified on validator's missed block in a Telegram channel\n")
sb.WriteString("- /unsubscribe <validator address> - undo the subscription given at the previous step\n")
sb.WriteString("- /status <validator address> - get validator missed blocks\n")
sb.WriteString("- /status - get the missed blocks of the validator(s) you're subscribed to\n\n")
sb.WriteString("Created by <a href=\"https://validator.solar\">SOLAR Labs</a> with ❤️.\n")
sb.WriteString("This bot is open-sourced, you can get the source code at https://github.com/solarlabsteam/missed-blocks-checker.\n\n")
sb.WriteString("We also maintain the following tools for Cosmos ecosystem:\n")
sb.WriteString("- <a href=\"https://github.com/solarlabsteam/cosmos-interacter\">cosmos-interacter</a> - a bot that can return info about Cosmos-based blockchain params.\n")
sb.WriteString("- <a href=\"https://github.com/solarlabsteam/cosmos-exporter\">cosmos-exporter</a> - scrape the blockchain data from the local node and export it to Prometheus\n")
sb.WriteString("- <a href=\"https://github.com/solarlabsteam/coingecko-exporter\">coingecko-exporter</a> - scrape the Coingecko exchange rate and export it to Prometheus\n")
sb.WriteString("- <a href=\"https://github.com/solarlabsteam/cosmos-transactions-bot\">cosmos-transactions-bot</a> - monitor the incoming transactions for a given filter\n\n")
sb.WriteString("If you like what we're doing, consider staking with us!\n")
sb.WriteString("- <a href=\"https://www.mintscan.io/sentinel/validators/sentvaloper1sazxkmhym0zcg9tmzvc4qxesqegs3q4u66tpmf\">Sentinel</a>\n")
sb.WriteString("- <a href=\"https://www.mintscan.io/persistence/validators/persistencevaloper1kp2sype5n0ky3f8u50pe0jlfcgwva9y79qlpgy\">Persistence</a>\n")
sb.WriteString("- <a href=\"https://www.mintscan.io/osmosis/validators/osmovaloper16jn3383fn4v4vuuvgclr3q7rumeglw8kdq6e48\">Osmosis</a>\n")
r.sendMessage(message, sb.String())
log.Info().
Str("user", message.Sender.Username).
Msg("Successfully returned help info")
}
func (r *TelegramReporter) getValidatorStatus(message *tb.Message) {
args := strings.SplitAfterN(message.Text, " ", 2)
if len(args) < 2 {
r.getSubscribedValidatorsStatuses(message)
return
}
address := args[1]
log.Debug().Str("address", address).Msg("getValidatorStatus: address")
validator, err := getValidator(address)
if err != nil {
log.Error().
Str("address", address).
Err(err).
Msg("Could not get validators")
r.sendMessage(message, "Could not find validator")
return
}
signingInfo, err := getSigningInfo(validator)
if err != nil {
r.sendMessage(message, "Could not get missed blocks info")
return
}
r.sendMessage(message, getValidatorWithMissedBlocksSerialized(validator, signingInfo))
log.Info().
Str("user", message.Sender.Username).
Str("address", address).
Msg("Successfully returned validator status")
}
func (r *TelegramReporter) getSubscribedValidatorsStatuses(message *tb.Message) {
log.Debug().Msg("getSubscribedValidatorsStatuses")
subscribedValidators := r.TelegramConfig.getNotifiedValidators(message.Sender.Username)
if len(subscribedValidators) == 0 {
r.sendMessage(message, "You are not subscribed to any validator's missed blocks notifications.")
return
}
var sb strings.Builder
for _, address := range subscribedValidators {
validator, err := getValidator(address)
if err != nil {
log.Error().
Str("address", address).
Err(err).
Msg("Could not get validators")
r.sendMessage(message, "Could not find validator")
return
}
signingInfo, err := getSigningInfo(validator)
if err != nil {
r.sendMessage(message, "Could not get missed blocks info")
return
}
sb.WriteString(getValidatorWithMissedBlocksSerialized(validator, signingInfo))
sb.WriteString("\n")
}
r.sendMessage(message, sb.String())
log.Info().
Str("user", message.Sender.Username).
Msg("Successfully returned subscribed validator statuses")
}
func getValidatorWithMissedBlocksSerialized(validator stakingtypes.Validator, signingInfo slashingtypes.ValidatorSigningInfo) string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("<code>%s</code>\n", validator.Description.Moniker))
sb.WriteString(fmt.Sprintf(
"Missed blocks: %d/%d (%.2f%%)\n",
signingInfo.MissedBlocksCounter,
SignedBlocksWindow,
float64(signingInfo.MissedBlocksCounter)/float64(SignedBlocksWindow)*100,
))
sb.WriteString(fmt.Sprintf(
"<a href=\"https://mintscan.io/%s/validators/%s\">Mintscan</a>\n",
MintscanPrefix,
validator.OperatorAddress,
))
return sb.String()
}
func (r *TelegramReporter) subscribeToValidatorUpdates(message *tb.Message) {
if message.Sender.Username == "" {
r.sendMessage(message, "Please set your Telegram username first.")
return
}
args := strings.SplitAfterN(message.Text, " ", 2)
if len(args) < 2 {
r.sendMessage(message, "Usage: /subscribe <validator address>")
return
}
address := args[1]
log.Debug().Str("address", address).Msg("subscribeToValidatorUpdates: address")
validator, err := getValidator(address)
if err != nil {
log.Error().
Str("address", address).
Err(err).
Msg("Could not get validator")
r.sendMessage(message, "Could not find validator")
return
}
err = r.TelegramConfig.addNotifier(address, message.Sender.Username)
r.saveYamlConfig()
if err != nil {
r.sendMessage(message, err.Error())
r.saveYamlConfig()
return
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Subscribed to the notification of <code>%s</code> ", validator.Description.Moniker))
sb.WriteString(fmt.Sprintf(
"<a href=\"https://mintscan.io/%s/validators/%s\">Mintscan</a>\n",
MintscanPrefix,
validator.OperatorAddress,
))
r.sendMessage(message, sb.String())
log.Info().
Str("user", message.Sender.Username).
Str("address", address).
Msg("Successfully subscribed to validator's notifications.")
}
func (r *TelegramReporter) unsubscribeFromValidatorUpdates(message *tb.Message) {
if message.Sender.Username == "" {
r.sendMessage(message, "Please set your Telegram username first.")
return
}
args := strings.SplitAfterN(message.Text, " ", 2)
if len(args) < 2 {
r.sendMessage(message, "Usage: /unsubscribe <validator address>")
return
}
address := args[1]
log.Debug().Str("address", address).Msg("unsubscribeFromValidatorUpdates: address")
validator, err := getValidator(address)
if err != nil {
log.Error().
Str("address", address).
Err(err).
Msg("Could not get validator")
r.sendMessage(message, "Could not find validator")
return
}
err = r.TelegramConfig.removeNotifier(address, message.Sender.Username)
r.saveYamlConfig()
if err != nil {
r.sendMessage(message, err.Error())
r.saveYamlConfig()
return
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Unsubscribed from the notification of <code>%s</code> ", validator.Description.Moniker))
sb.WriteString(fmt.Sprintf(
"<a href=\"https://mintscan.io/%s/validators/%s\">Mintscan</a>\n",
MintscanPrefix,
validator.OperatorAddress,
))
r.sendMessage(message, sb.String())
log.Info().
Str("user", message.Sender.Username).
Str("address", address).
Msg("Successfully unsubscribed from validator's notifications.")
}
func (r *TelegramReporter) loadConfigFromYaml() {
if _, err := os.Stat(r.TelegramConfigPath); os.IsNotExist(err) {
log.Info().Str("path", r.TelegramConfigPath).Msg("Telegram config file does not exist, creating.")
if _, err = os.Create(r.TelegramConfigPath); err != nil {
log.Fatal().Err(err).Msg("Could not create Telegram config!")
}
} else if err != nil {
log.Fatal().Err(err).Msg("Could not fetch Telegram config!")
}
bytes, err := ioutil.ReadFile(r.TelegramConfigPath)
if err != nil {
log.Fatal().Err(err).Msg("Could not read Telegram config!")
}
var conf TelegramConfig
if _, err := toml.Decode(string(bytes), &conf); err != nil {
log.Fatal().Err(err).Msg("Could not load Telegram config!")
}
r.TelegramConfig = conf
log.Debug().Msg("Telegram config is loaded successfully.")
}
func (r *TelegramReporter) saveYamlConfig() {
f, err := os.Create(r.TelegramConfigPath)
if err != nil {
log.Fatal().Err(err).Msg("Could not open Telegram config when saving")
}
if err := toml.NewEncoder(f).Encode(r.TelegramConfig); err != nil {
log.Fatal().Err(err).Msg("Could not save Telegram config")
}
if err := f.Close(); err != nil {
log.Fatal().Err(err).Msg("Could not close Telegram config when saving")
}
log.Debug().Msg("Telegram config is updated successfully.")
}
func getValidator(address string) (stakingtypes.Validator, error) {
stakingClient := stakingtypes.NewQueryClient(grpcConn)
validatorResponse, err := stakingClient.Validator(
context.Background(),
&stakingtypes.QueryValidatorRequest{ValidatorAddr: address},
)
if err != nil {
return stakingtypes.Validator{}, err
}
return validatorResponse.Validator, nil
}
func getSigningInfo(validator stakingtypes.Validator) (slashingtypes.ValidatorSigningInfo, error) {
slashingClient := slashingtypes.NewQueryClient(grpcConn)
err := validator.UnpackInterfaces(interfaceRegistry) // Unpack interfaces, to populate the Anys' cached values
if err != nil {
log.Error().
Str("address", validator.OperatorAddress).
Err(err).
Msg("Could not get unpack validator inferfaces")
return slashingtypes.ValidatorSigningInfo{}, err
}
pubKey, err := validator.GetConsAddr()
if err != nil {
log.Error().
Str("address", validator.OperatorAddress).
Err(err).
Msg("Could not get validator pubkey")
return slashingtypes.ValidatorSigningInfo{}, err
}
signingInfosResponse, err := slashingClient.SigningInfo(
context.Background(),
&slashingtypes.QuerySigningInfoRequest{ConsAddress: pubKey.String()},
)
if err != nil {
log.Error().
Str("address", validator.OperatorAddress).
Err(err).
Msg("Could not get signing info")
return slashingtypes.ValidatorSigningInfo{}, err
}
return signingInfosResponse.ValSigningInfo, nil
}