-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpow_client.go
More file actions
244 lines (217 loc) · 6.26 KB
/
pow_client.go
File metadata and controls
244 lines (217 loc) · 6.26 KB
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
package powclient
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"math/big"
"net/http"
"net/url"
"time"
)
var (
// ErrTooManyRequests is returned when the server responds 429.
ErrTooManyRequests = errors.New("too many requests")
// ErrEmptyToken is returned when the server responds success but token is empty.
ErrEmptyToken = errors.New("empty token from server")
// ErrInvalidChallenge is returned when the challenge string cannot be parsed as a base-10 big.Int.
ErrInvalidChallenge = errors.New("invalid challenge integer")
)
// HTTPStatusError is returned for non-200 responses (except 429 which maps to ErrTooManyRequests).
type HTTPStatusError struct {
Code int
Body string
}
func (e *HTTPStatusError) Error() string {
return fmt.Sprintf("http %d: %s", e.Code, e.Body)
}
// bodySnippet reads up to n bytes from r and returns it as string.
// Intended only for error reporting paths.
func bodySnippet(r io.Reader, n int64) string {
if n <= 0 {
n = 2048
}
b, _ := io.ReadAll(io.LimitReader(r, n))
return string(b)
}
type Challenge struct {
RequestID string `json:"request_id"`
Challenge string `json:"challenge"`
}
type RequestResponse struct {
Challenge Challenge `json:"challenge"`
RequestTime int64 `json:"request_time"`
}
type SubmitRequest struct {
Challenge Challenge `json:"challenge"`
Answer []string `json:"answer"`
RequestTime int64 `json:"request_time"`
}
type SubmitResponse struct {
Token string `json:"token"`
}
type GetTokenParams struct {
TimeoutSec time.Duration
BaseUrl string
RequestPath string
SubmitPath string
UserAgent string
SNI string
Host string
Proxy *url.URL /** 支持socks5:// http:// **/
}
func NewGetTokenParams() *GetTokenParams {
return &GetTokenParams{
TimeoutSec: 5 * time.Second, // 你的默认值
BaseUrl: "http://127.0.0.1:55000",
RequestPath: "/request_challenge",
SubmitPath: "/submit_answer",
UserAgent: "POW client",
SNI: "",
Host: "",
Proxy: nil,
}
}
type ChallengeParams struct {
BaseUrl string
RequestPath string
SubmitPath string
UserAgent string
Host string
Client *http.Client
}
func RetToken(getTokenParams *GetTokenParams) (string, error) {
// Build transport by cloning the default so we inherit sane defaults
tr := http.DefaultTransport.(*http.Transport).Clone()
// Keep environment proxy unless user explicitly passes one
if getTokenParams.Proxy != nil {
tr.Proxy = http.ProxyURL(getTokenParams.Proxy)
}
// Apply custom SNI if provided
if getTokenParams.SNI != "" {
if tr.TLSClientConfig == nil {
tr.TLSClientConfig = &tls.Config{}
}
tr.TLSClientConfig.ServerName = getTokenParams.SNI
}
client := &http.Client{
Timeout: getTokenParams.TimeoutSec,
Transport: tr,
}
challengeParams := &ChallengeParams{
BaseUrl: getTokenParams.BaseUrl,
RequestPath: getTokenParams.RequestPath,
SubmitPath: getTokenParams.SubmitPath,
UserAgent: getTokenParams.UserAgent,
Host: getTokenParams.Host,
Client: client,
}
// Get challenge
challengeResponse, err := requestChallenge(challengeParams)
if err != nil {
return "", err
}
// Solve challenge and submit answer
token, err := submitAnswer(challengeParams, challengeResponse)
if err != nil {
return "", err
}
return token, nil
}
func requestChallenge(challengeParams *ChallengeParams) (rr *RequestResponse, err error) {
req, err := http.NewRequest("GET", challengeParams.BaseUrl+challengeParams.RequestPath, nil)
if err != nil {
return nil, err
}
req.Header.Add("User-Agent", challengeParams.UserAgent)
//req.Header.Add("Host", getTokenParams.Host)
if challengeParams.Host != "" {
req.Host = challengeParams.Host
}
resp, err := challengeParams.Client.Do(req)
if err != nil {
return nil, err
}
defer func() {
if cerr := resp.Body.Close(); err == nil && cerr != nil {
err = fmt.Errorf("close response body: %w", cerr)
}
}()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusTooManyRequests {
return nil, ErrTooManyRequests
}
snippet := bodySnippet(resp.Body, 2048)
return nil, &HTTPStatusError{Code: resp.StatusCode, Body: snippet}
}
var challengeResponse RequestResponse
if err = json.NewDecoder(resp.Body).Decode(&challengeResponse); err != nil {
return nil, err
}
rr = &challengeResponse
return
}
func submitAnswer(challengeParams *ChallengeParams, challengeResponse *RequestResponse) (token string, err error) {
requestTime := challengeResponse.RequestTime
challenge := challengeResponse.Challenge.Challenge
requestId := challengeResponse.Challenge.RequestID
N, ok := new(big.Int).SetString(challenge, 10)
if !ok {
return "", fmt.Errorf("%w: %q", ErrInvalidChallenge, challenge)
}
factorsList := factors(N)
if len(factorsList) != 2 {
return "", errors.New("factors function did not return exactly two factors")
}
p1 := factorsList[0]
p2 := factorsList[1]
if p1.Cmp(p2) > 0 { // if p1 > p2
p1, p2 = p2, p1 // swap p1 and p2
}
submitRequest := SubmitRequest{
Challenge: Challenge{RequestID: requestId},
Answer: []string{p1.String(), p2.String()},
RequestTime: requestTime,
}
requestBody, err := json.Marshal(submitRequest)
if err != nil {
return "", err
}
req, err := http.NewRequest("POST", challengeParams.BaseUrl+challengeParams.SubmitPath, bytes.NewBuffer(requestBody))
if err != nil {
return "", err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Add("User-Agent", challengeParams.UserAgent)
//req.Header.Add("Host", getTokenParams.Host)
if challengeParams.Host != "" {
req.Host = challengeParams.Host
}
resp, err := challengeParams.Client.Do(req)
if err != nil {
return "", err
}
defer func() {
if cerr := resp.Body.Close(); err == nil && cerr != nil {
err = fmt.Errorf("close response body: %w", cerr)
}
}()
if resp.StatusCode != http.StatusOK {
if resp.StatusCode == http.StatusTooManyRequests {
return "", ErrTooManyRequests
}
snippet := bodySnippet(resp.Body, 2048)
return "", &HTTPStatusError{Code: resp.StatusCode, Body: snippet}
}
var submitResponse SubmitResponse
if err = json.NewDecoder(resp.Body).Decode(&submitResponse); err != nil {
return "", err
}
if submitResponse.Token == "" {
return "", ErrEmptyToken
}
token = submitResponse.Token
return
}