package main import ( "bytes" "encoding/binary" "encoding/hex" "encoding/json" "fmt" address2 "git.gammaspectra.live/P2Pool/p2pool-observer/monero/address" "git.gammaspectra.live/P2Pool/p2pool-observer/monero/crypto" "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool" "git.gammaspectra.live/P2Pool/p2pool-observer/p2pool/sidechain" "git.gammaspectra.live/P2Pool/p2pool-observer/types" "git.gammaspectra.live/P2Pool/p2pool-observer/utils" "github.com/ake-persson/mapslice-json" "github.com/gorilla/mux" "github.com/tyler-sommer/stick" "github.com/tyler-sommer/stick/twig" "golang.org/x/exp/maps" "golang.org/x/exp/slices" "golang.org/x/net/html" "log" "math" "net/http" "os" "strconv" "strings" "time" ) func toUint64(t any) uint64 { if x, ok := t.(json.Number); ok { if n, err := x.Int64(); err == nil { return uint64(n) } } if x, ok := t.(uint64); ok { return x } else if x, ok := t.(int64); ok { return uint64(x) } else if x, ok := t.(uint); ok { return uint64(x) } else if x, ok := t.(int); ok { return uint64(x) } else if x, ok := t.(float64); ok { return uint64(x) } else if x, ok := t.(float32); ok { return uint64(x) } else if x, ok := t.(string); ok { if n, err := strconv.ParseUint(x, 10, 0); err == nil { return n } } return 0 } func toInt64(t any) int64 { if x, ok := t.(json.Number); ok { if n, err := x.Int64(); err == nil { return n } } if x, ok := t.(uint64); ok { return int64(x) } else if x, ok := t.(int64); ok { return x } else if x, ok := t.(uint); ok { return int64(x) } else if x, ok := t.(int); ok { return int64(x) } else if x, ok := t.(float64); ok { return int64(x) } else if x, ok := t.(float32); ok { return int64(x) } else if x, ok := t.(string); ok { if n, err := strconv.ParseInt(x, 10, 0); err == nil { return n } } return 0 } func toFloat64(t any) float64 { if x, ok := t.(json.Number); ok { if n, err := x.Float64(); err == nil { return n } } if x, ok := t.(float64); ok { return x } else if x, ok := t.(float32); ok { return float64(x) } else if x, ok := t.(uint64); ok { return float64(x) } else if x, ok := t.(int64); ok { return float64(x) } else if x, ok := t.(uint); ok { return float64(x) } else if x, ok := t.(int); ok { return float64(x) } else if x, ok := t.(string); ok { if n, err := strconv.ParseFloat(x, 0); err == nil { return n } } return 0 } func main() { env := twig.New(&loader{}) render := func(writer http.ResponseWriter, template string, ctx map[string]stick.Value) { w := bytes.NewBuffer(nil) defer func() { _, _ = writer.Write(w.Bytes()) }() defer func() { if err := recover(); err != nil { w = bytes.NewBuffer(nil) writer.WriteHeader(http.StatusInternalServerError) opts := make(map[string]stick.Value) e := make(map[string]stick.Value) opts["error"] = e e["code"] = http.StatusInternalServerError e["message"] = "Internal Server Error" e["content"] = "
" + html.EscapeString(fmt.Sprintf("%s", err)) + "" if err = env.Execute("error.html", w, opts); err != nil { w = bytes.NewBuffer(nil) writer.Header().Set("content-type", "text/plain") _, _ = w.Write([]byte(fmt.Sprintf("%s", err))) } } }() if err := env.Execute(template, w, ctx); err != nil { w = bytes.NewBuffer(nil) writer.WriteHeader(http.StatusInternalServerError) opts := make(map[string]stick.Value) e := make(map[string]stick.Value) opts["error"] = e e["code"] = http.StatusInternalServerError e["message"] = "Internal Server Error" e["content"] = "
" + html.EscapeString(err.Error()) + "" if err = env.Execute("error.html", w, opts); err != nil { w = bytes.NewBuffer(nil) writer.Header().Set("content-type", "text/plain") _, _ = w.Write([]byte(err.Error())) } } } env.Functions["getenv"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) == 0 { return "" } return os.Getenv(args[0].(string)) } env.Functions["diff_hashrate"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if d, err := types.DifficultyFromString(args[0].(string)); err == nil { return d.Div64(toUint64(args[1])).Lo } return 0 } env.Functions["diff_uint"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if d, err := types.DifficultyFromString(args[0].(string)); err == nil { return d.Lo } return 0 } env.Functions["monero_to_xmr"] = func(ctx stick.Context, args ...stick.Value) stick.Value { v := toUint64(args[0]) return fmt.Sprintf("%d.%012d", v/1000000000000, v%1000000000000) } env.Functions["utc_date"] = func(ctx stick.Context, args ...stick.Value) stick.Value { return time.Unix(int64(toUint64(args[0])), 0).UTC().Format("02-01-2006 15:04:05 MST") } env.Functions["time_elapsed"] = func(ctx stick.Context, args ...stick.Value) stick.Value { diff := time.Since(time.Unix(int64(toUint64(args[0])), 0).UTC()) days := int64(diff.Hours() / 24) hours := int64(diff.Hours()) % 24 minutes := int64(diff.Minutes()) % 60 seconds := int64(diff.Seconds()) % 60 var result []string if days > 0 { result = append(result, strconv.FormatInt(days, 10)+"d") } if hours > 0 { result = append(result, strconv.FormatInt(hours, 10)+"h") } if minutes > 0 { result = append(result, strconv.FormatInt(minutes, 10)+"m") } if seconds > 0 { result = append(result, strconv.FormatInt(seconds, 10)+"s") } if toUint64(args[0]) == 0 { return "never" } else if len(result) == 0 { return "just now" } else { return strings.Join(result, " ") + " ago" } } env.Functions["time_elapsed_short"] = func(ctx stick.Context, args ...stick.Value) stick.Value { diff := time.Since(time.Unix(int64(toUint64(args[0])), 0).UTC()) days := int64(diff.Hours() / 24) hours := int64(diff.Hours()) % 24 minutes := int64(diff.Minutes()) % 60 seconds := int64(diff.Seconds()) % 60 var result []string if days > 0 { result = append(result, strconv.FormatInt(days, 10)+"d") } if hours > 0 { result = append(result, strconv.FormatInt(hours, 10)+"h") } if minutes > 0 { result = append(result, strconv.FormatInt(minutes, 10)+"m") } if seconds > 0 { result = append(result, strconv.FormatInt(seconds, 10)+"s") } if toUint64(args[0]) == 0 { return "never" } else if len(result) == 0 { return "just now" } else { return strings.Join(result[0:1], " ") + " ago" } } env.Functions["time_duration_long"] = func(ctx stick.Context, args ...stick.Value) stick.Value { diff := time.Second * time.Duration(toUint64(args[0])) diff += time.Microsecond * time.Duration((toFloat64(toUint64(args[0]))-toFloat64(args[0]))*1000000) days := int64(diff.Hours() / 24) hours := int64(diff.Hours()) % 24 minutes := int64(diff.Minutes()) % 60 seconds := int64(diff.Seconds()) % 60 ms := int64(diff.Milliseconds()) % 1000 var result []string if days > 0 { result = append(result, strconv.FormatInt(days, 10)+"d") } if hours > 0 { result = append(result, strconv.FormatInt(hours, 10)+"h") } if minutes > 0 { result = append(result, strconv.FormatInt(minutes, 10)+"m") } if seconds > 0 { result = append(result, strconv.FormatInt(seconds, 10)+"s") } if len(result) == 0 || (len(result) == 1 && seconds > 0) { result = append(result, strconv.FormatInt(ms, 10)+"ms") } return strings.Join(result, " ") } env.Functions["add_uint"] = func(ctx stick.Context, args ...stick.Value) stick.Value { var result uint64 for _, v := range args { result += toUint64(v) } return result } env.Functions["sub_int"] = func(ctx stick.Context, args ...stick.Value) stick.Value { result := toInt64(args[0]) for _, v := range args[1:] { result -= toInt64(v) } return result } env.Functions["date_diff_short"] = func(ctx stick.Context, args ...stick.Value) stick.Value { diff := time.Since(time.Unix(int64(toUint64(args[0])), 0).UTC()) s := fmt.Sprintf("%02d:%02d:%02d", int64(diff.Hours())%24, int64(diff.Minutes())%60, int64(diff.Seconds())%60) days := int64(diff.Hours() / 24) if days > 0 { return strconv.FormatInt(days, 10) + ":" + s } return s } env.Functions["prove_output_number"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 2 { return nil } n := uint64(math.Ceil(math.Log2(p2pool.PPLNSWindow * 4))) //height | index return (toUint64(args[0]) << n) | toUint64(args[1]) } env.Functions["get_tx_proof"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 3 { return nil } h, _ := types.HashFromString(args[1].(string)) k, _ := types.HashFromString(args[2].(string)) keyBytes := crypto.PrivateKeyBytes(k) return address2.GetTxProofV2(address2.FromBase58(args[0].(string)), h, &keyBytes, "") } env.Functions["get_tx_proof_v1"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 3 { return nil } h, _ := types.HashFromString(args[1].(string)) k, _ := types.HashFromString(args[2].(string)) keyBytes := crypto.PrivateKeyBytes(k) return address2.GetTxProofV1(address2.FromBase58(args[0].(string)), h, &keyBytes, "") } env.Functions["get_ephemeral_pubkey"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 3 { return nil } k, _ := types.HashFromString(args[1].(string)) keyBytes := crypto.PrivateKeyBytes(k) return address2.GetEphemeralPublicKey(address2.FromBase58(args[0].(string)), &keyBytes, toUint64(args[2])) } env.Functions["coinbase_extra"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 1 { return nil } b, _ := args[0].(*sidechain.PoolBlock).Main.Coinbase.Extra.MarshalBinary() return b } env.Functions["extra_nonce"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 1 { return nil } return args[0].(*sidechain.PoolBlock).CoinbaseExtra(sidechain.SideExtraNonce) } env.Functions["attribute"] = func(ctx stick.Context, args ...stick.Value) stick.Value { if len(args) != 2 { return nil } if s, ok := args[0].([]any); ok { return s[toUint64(args[1])] } else if m, ok := args[0].(map[string]any); ok { return m[args[1].(string)] } return nil } env.Filters["slice_sum"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { var result uint64 stick.Iterate(val, func(k, v stick.Value, l stick.Loop) (brk bool, err error) { result += toUint64(v) return false, nil }) return result } env.Filters["diff_div"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if d, ok := val.(types.Difficulty); ok { return d.Div64(toUint64(args[0])).String() } else if d, err := types.DifficultyFromString(val.(string)); err == nil { return d.Div64(toUint64(args[0])).String() } log.Panic() return val } env.Filters["diff_int"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if d, ok := val.(types.Difficulty); ok { return d.Lo } else if d, err := types.DifficultyFromString(val.(string)); err == nil { return d.Lo } log.Panic() return 0 } env.Filters["benc"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if s, ok := val.(string); ok { if n, err := strconv.ParseUint(s, 10, 0); err == nil { return utils.EncodeBinaryNumber(n) } } else { return utils.EncodeBinaryNumber(toUint64(val)) } //TODO: remove this log.Panic() return "" } env.Filters["hex"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if s, ok := val.(string); ok { return s } else if s, ok := val.(types.Difficulty); ok { return s.String() } else if s, ok := val.(crypto.PrivateKey); ok { return s.String() } else if s, ok := val.(crypto.PublicKey); ok { return s.String() } else if s, ok := val.(crypto.PrivateKeyBytes); ok { return s.String() } else if s, ok := val.(crypto.PublicKeyBytes); ok { return s.String() } else if s, ok := val.(types.Hash); ok { return s.String() } else if s, ok := val.([]byte); ok { return hex.EncodeToString(s) } else if s, ok := val.(uint32); ok { var buf [4]byte binary.BigEndian.PutUint32(buf[:], s) return hex.EncodeToString(buf[:]) } else if s, ok := val.(uint64); ok { var buf [8]byte binary.BigEndian.PutUint64(buf[:], s) return hex.EncodeToString(buf[:]) } return val } env.Filters["henc"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if h, ok := val.(types.Hash); ok { return utils.EncodeHexBinaryNumber(h.String()) } else if s, ok := val.(string); ok { return utils.EncodeHexBinaryNumber(s) } //TODO: remove this log.Panic() return "" } env.Filters["effort_color"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { if effort, ok := val.(float64); ok { if effort < 100 { return "#00C000" } else if effort < 200 { return "#E0E000" } else { return "#FF0000" } } return "#000000" } env.Filters["si_units"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { v := toFloat64(val) if len(args) > 0 { return utils.SiUnits(v, int(toUint64(args[0]))) } else { return utils.SiUnits(v, 3) } } env.Filters["effort_color"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { effort := toFloat64(val) if effort < 100 { return "#00C000" } else if effort < 200 { return "#E0E000" } else { return "#FF0000" } } env.Filters["shorten"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { var value string if s, ok := val.(string); ok { value = s } else { value = fmt.Sprintf("%s", value) } n := int(toUint64(args[0])) if len(value) <= n*2+3 { return value } else { return value[:n] + "..." + value[len(value)-n:] } } env.Filters["intstr"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value { return strconv.FormatUint(toUint64(val), 10) } env.Tests["defined"] = func(ctx stick.Context, val stick.Value, args ...stick.Value) bool { return val != nil } serveMux := mux.NewRouter() serveMux.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { params := request.URL.Query() if params.Has("refresh") { writer.Header().Set("refresh", "120") } poolInfo := getFromAPI("pool_info", 5).(map[string]any) d1, _ := types.DifficultyFromString(poolInfo["mainchain"].(map[string]any)["difficulty"].(string)) d2, _ := types.DifficultyFromString(poolInfo["sidechain"].(map[string]any)["difficulty"].(string)) secondsPerBlock := float64(d1.Lo) / float64(d2.Div64(toUint64(poolInfo["sidechain"].(map[string]any)["block_time"])).Lo) blocksToFetch := uint64(math.Ceil((((time.Hour*24).Seconds()/secondsPerBlock)*2)/100) * 100) blocks := getFromAPI(fmt.Sprintf("found_blocks?coinbase&limit=%d", blocksToFetch), 5).([]any) shares := getFromAPI("shares?limit=20", 5).([]any) ctx := make(map[string]stick.Value) ctx["refresh"] = writer.Header().Get("refresh") blocksFound := NewPositionChart(30*4, p2pool.PPLNSWindow*4) tip := toInt64(poolInfo["sidechain"].(map[string]any)["height"]) for _, b := range blocks { blocksFound.Add(int(tip-toInt64(b.(map[string]any)["height"])), 1) } if len(blocks) > 0 { blocks = blocks[:20] } ctx["blocks_found"] = blocks ctx["blocks_found_position"] = blocksFound.String() ctx["shares"] = shares ctx["pool"] = poolInfo render(writer, "index.html", ctx) }) serveMux.HandleFunc("/api", func(writer http.ResponseWriter, request *http.Request) { render(writer, "api.html", nil) }) serveMux.HandleFunc("/calculate-share-time", func(writer http.ResponseWriter, request *http.Request) { poolInfo := getFromAPI("pool_info", 5) hashRate := float64(0) magnitude := float64(1000) params := request.URL.Query() if params.Has("hashrate") { hashRate = toFloat64(params.Get("hashrate")) } if params.Has("magnitude") { magnitude = toFloat64(params.Get("magnitude")) } ctx := make(map[string]stick.Value) ctx["hashrate"] = hashRate ctx["magnitude"] = magnitude ctx["pool"] = poolInfo render(writer, "calculate-share-time.html", ctx) }) serveMux.HandleFunc("/blocks", func(writer http.ResponseWriter, request *http.Request) { params := request.URL.Query() if params.Has("refresh") { writer.Header().Set("refresh", "600") } var miner map[string]any if params.Has("miner") { m := getFromAPI(fmt.Sprintf("miner_info/%s", params.Get("miner"))) if m == nil || m.(map[string]any)["address"] == nil { ctx := make(map[string]stick.Value) error := make(map[string]stick.Value) ctx["error"] = error ctx["code"] = http.StatusNotFound error["message"] = "Address Not Found" error["content"] = "