Skip to content

Commit

Permalink
feat: network health command (#7)
Browse files Browse the repository at this point in the history
  • Loading branch information
kehiy authored Nov 21, 2023
1 parent 3dd8d31 commit 65783dc
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
17 changes: 17 additions & 0 deletions client/client_mgr.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,23 @@ func (cm *Mgr) GetBlockchainHeight() (uint32, error) {
return 0, errors.New("unable to get blockchain height")
}

func (cm *Mgr) GetAllBlockchainHeight() ([]uint32, error) {
result := []uint32{}
for _, c := range cm.clients {
height, err := c.GetBlockchainHeight()
if err != nil {
continue
}
result = append(result, height)
}

if len(result) != 0 {
return result, nil
}

return []uint32{}, errors.New("unable to get blockchain height")
}

func (cm *Mgr) GetNetworkInfo() (*pactus.GetNetworkInfoResponse, error) {
for _, c := range cm.clients {
info, err := c.GetNetworkInfo()
Expand Down
31 changes: 31 additions & 0 deletions discord/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@ func (b *Bot) Stop() error {

// This function will be called (due to AddHandler above) every time a new
// message is created on any channel that the authenticated bot has access to.
//nolint
func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
p := message.NewPrinter(language.English)

Expand Down Expand Up @@ -106,6 +107,36 @@ func (b *Bot) messageHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
return
}

if strings.ToLower(m.Content) == "health" {
var genesisTime int64 = 1697328000
currentTime := time.Now().Unix()
timeDifference := currentTime - genesisTime
blocks := (timeDifference / 10)
acceptableHeight := (blocks / 100) * 5 // 5% is acceptable number.
heights, err := b.cm.GetAllBlockchainHeight()
if err != nil {
msg := p.Sprintf("Network is unhealthy\nNon of nodes responding")
_, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference())
return
}

heightsAddition := 0
for _, h := range heights {
heightsAddition += int(h)
}
averageHeight := heightsAddition / len(heights)

if (blocks - int64(averageHeight)) > acceptableHeight {
msg := p.Sprintf("Network is unhealthy\ncurrent height: %v\naverage of nodes height: %v\nDifference is more than 5%", blocks, averageHeight)
_, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference())
return
}

msg := p.Sprintf("Network is **healthy**\ncurrent height: %v\naverage of nodes height: %v\n", blocks, averageHeight)
_, _ = s.ChannelMessageSendReply(m.ChannelID, msg, m.Reference())
return
}

if strings.Contains(strings.ToLower(m.Content), "peer-info") {
trimmedPrefix := strings.TrimPrefix(strings.ToLower(m.Content), "peer-info")
trimmedAddress := strings.Trim(trimmedPrefix, " ")
Expand Down

0 comments on commit 65783dc

Please sign in to comment.