Last active
June 2, 2021 03:59
-
-
Save Howard3/27fd000fd28e1e1b281c4f2f78efc7fc to your computer and use it in GitHub Desktop.
Check your recent hashrate, throw an error if it's low.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"net/http" | |
"os" | |
"strconv" | |
) | |
const DATAPOINTS_TO_AVG = 10 | |
const DATAPOINT_END_OFFSET = 2 | |
type HashrateResponseBody []BlockHashRate | |
type BlockHashRate struct { | |
BlockHeight int64 `json:"blockHeight,string"` | |
Time string `json:"time"` | |
Rate int `json:"rate,string"` | |
} | |
func main() { | |
req, err := http.NewRequest("GET", "https://staging.myriade.io/metrics/v1/stats/hashrates", nil) | |
if err != nil { | |
panic("Why does this happen to me?") | |
} | |
req.Header.Set("Authorization", getToken()) | |
client := &http.Client{} | |
res, err := client.Do(req) | |
if err != nil { | |
panic("Request Failed") | |
} | |
body, err := ioutil.ReadAll(res.Body) | |
if err != nil { | |
panic (fmt.Sprintf("Failed to read the body: %v", err)) | |
} | |
marshalledData := HashrateResponseBody{} | |
err = json.Unmarshal(body, &marshalledData) | |
if err != nil { | |
panic(fmt.Sprintf("Failed to unmarshal data: %v", err)) | |
} | |
datapoints := len(marshalledData) | |
fmt.Println(fmt.Sprintf("Received %d datapoints", datapoints)) | |
sumHR := 0 | |
for i := 0; i < DATAPOINTS_TO_AVG; i++ { | |
thisDP := marshalledData[datapoints-DATAPOINT_END_OFFSET-i] | |
fmt.Println(fmt.Sprintf("Adding datapoint %s: %d", thisDP.Time, thisDP.Rate)) | |
sumHR += thisDP.Rate | |
} | |
avgHR := sumHR / DATAPOINTS_TO_AVG | |
fmt.Println(fmt.Sprintf("Sum hashrate %d; Average hashrate %d", sumHR, avgHR)) | |
if avgHR < minHashrate() { | |
panic(fmt.Sprintf("HASHRATE BELOW MIN SPECIFIED, IS: %d, WANT: %d", avgHR, minHashrate())) | |
} | |
} | |
func getToken() string { | |
token := os.Getenv("AUTH_TOKEN") | |
if token == "" { | |
panic("AUTH_TOKEN is not set in the environment.") | |
} | |
return token | |
} | |
func minHashrate() int { | |
mh := os.Getenv("MIN_HASHRATE") | |
if mh == "" { | |
panic( "MIN_HASHRATE is not set in the environment") | |
} | |
i, _ := strconv.Atoi(mh) | |
return i | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment