-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
105 lines (100 loc) · 2.56 KB
/
main.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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"math/big"
"net/http"
"os"
)
var (
port = flag.Int("p", 7076, "Listen port")
user = flag.String("u", "", "User")
apiKey = flag.String("k", "", "API key")
fallbackURL = flag.String("f", "", "Fallback RPC URL")
)
func main() {
flag.Parse()
if *user == "" || *apiKey == "" {
fmt.Println("User and API key are required")
os.Exit(1)
}
c := newClient()
if err := c.connect(); err != nil {
fmt.Println(err)
os.Exit(1)
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
writeError := func(err error) {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
writeError(err)
return
}
var v struct{ Action, Hash, Difficulty string }
if err := json.NewDecoder(bytes.NewReader(body)).Decode(&v); err != nil {
writeError(err)
return
}
if v.Action != "work_generate" {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]string{"message": "Action is not supported"})
return
}
v.Difficulty = multiplyDifficulty(v.Difficulty, 1.2)
if work, done, err := process(r.Context(), c, v.Hash, v.Difficulty); err == nil {
json.NewEncoder(w).Encode(map[string]string{"work": work})
} else if done {
return
} else if *fallbackURL != "" {
resp, err := http.Post(*fallbackURL, "application/json", bytes.NewReader(body))
if err != nil {
writeError(err)
return
}
w.WriteHeader(resp.StatusCode)
io.Copy(w, resp.Body)
resp.Body.Close()
} else {
writeError(err)
}
})
if err := http.ListenAndServe(fmt.Sprint(":", *port), nil); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func process(ctx context.Context, c *client, hash, difficulty string) (work string, done bool, err error) {
ch := make(chan *response, 1)
if err = c.request(hash, difficulty, ch); err != nil {
return
}
select {
case v := <-ch:
if v.Error != "" {
return "", false, errors.New(v.Error)
}
return v.Work, false, nil
case <-ctx.Done():
return "", true, ctx.Err()
}
}
func multiplyDifficulty(difficulty string, multiplier float64) string {
x, ok := new(big.Int).SetString(difficulty, 16)
if !ok {
return difficulty
}
y := new(big.Rat).SetInt(new(big.Int).Exp(big.NewInt(2), big.NewInt(64), nil))
z := new(big.Rat).SetFloat64(multiplier)
z.Sub(y, z.Quo(new(big.Rat).Sub(y, new(big.Rat).SetInt(x)), z))
new(big.Float).SetRat(z).Int(x)
return x.Text(16)
}