-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpow_client.go
More file actions
293 lines (254 loc) · 7.29 KB
/
Copy pathpow_client.go
File metadata and controls
293 lines (254 loc) · 7.29 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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
package powclient
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"sync"
"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 is invalid or cannot be reduced to exactly two prime factors.
ErrInvalidChallenge = errors.New("invalid challenge integer")
errNilGetTokenParams = errors.New("nil GetTokenParams")
errInvalidBaseURL = errors.New("invalid BaseUrl")
transportCache sync.Map
)
// 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) {
if getTokenParams == nil {
return "", errNilGetTokenParams
}
baseURL, err := parseBaseURL(getTokenParams.BaseUrl)
if err != nil {
return "", err
}
ctx := context.Background()
if getTokenParams.TimeoutSec > 0 {
var cancel context.CancelFunc
ctx, cancel = context.WithTimeout(ctx, getTokenParams.TimeoutSec)
defer cancel()
}
client := &http.Client{
Transport: getTransport(getTokenParams),
}
challengeParams := &ChallengeParams{
BaseUrl: getTokenParams.BaseUrl,
RequestPath: getTokenParams.RequestPath,
SubmitPath: getTokenParams.SubmitPath,
UserAgent: getTokenParams.UserAgent,
Host: getTokenParams.Host,
Client: client,
}
requestURL := resolveURL(baseURL, getTokenParams.RequestPath)
submitURL := resolveURL(baseURL, getTokenParams.SubmitPath)
challengeResponse, err := requestChallenge(ctx, challengeParams, requestURL)
if err != nil {
return "", err
}
token, err := submitAnswer(ctx, challengeParams, submitURL, challengeResponse)
if err != nil {
return "", err
}
return token, nil
}
func parseBaseURL(raw string) (*url.URL, error) {
if strings.TrimSpace(raw) == "" {
return nil, errInvalidBaseURL
}
baseURL, err := url.Parse(raw)
if err != nil {
return nil, fmt.Errorf("%w: %v", errInvalidBaseURL, err)
}
if baseURL.Scheme == "" || baseURL.Host == "" {
return nil, fmt.Errorf("%w: %q", errInvalidBaseURL, raw)
}
return baseURL, nil
}
func resolveURL(baseURL *url.URL, endpointPath string) string {
if endpointPath == "" {
return baseURL.String()
}
resolved := *baseURL
resolved.Path = path.Join(strings.TrimSuffix(baseURL.Path, "/"), endpointPath)
return resolved.String()
}
func requestChallenge(ctx context.Context, challengeParams *ChallengeParams, requestURL string) (*RequestResponse, error) {
var challengeResponse RequestResponse
if err := doJSONRequest(ctx, challengeParams, http.MethodGet, requestURL, nil, "", &challengeResponse); err != nil {
return nil, err
}
return &challengeResponse, nil
}
func submitAnswer(ctx context.Context, challengeParams *ChallengeParams, submitURL string, challengeResponse *RequestResponse) (string, error) {
factors, err := solveSemiprime(ctx, challengeResponse.Challenge.Challenge)
if err != nil {
return "", err
}
submitRequest := SubmitRequest{
Challenge: Challenge{RequestID: challengeResponse.Challenge.RequestID},
Answer: []string{factors[0].String(), factors[1].String()},
RequestTime: challengeResponse.RequestTime,
}
requestBody, err := json.Marshal(submitRequest)
if err != nil {
return "", err
}
var submitResponse SubmitResponse
if err := doJSONRequest(ctx, challengeParams, http.MethodPost, submitURL, bytes.NewReader(requestBody), "application/json", &submitResponse); err != nil {
return "", err
}
if submitResponse.Token == "" {
return "", ErrEmptyToken
}
return submitResponse.Token, nil
}
func doJSONRequest(
ctx context.Context,
challengeParams *ChallengeParams,
method string,
endpoint string,
body io.Reader,
contentType string,
out any,
) (err error) {
req, err := http.NewRequestWithContext(ctx, method, endpoint, body)
if err != nil {
return err
}
if challengeParams.UserAgent != "" {
req.Header.Set("User-Agent", challengeParams.UserAgent)
}
if contentType != "" {
req.Header.Set("Content-Type", contentType)
}
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
}
return &HTTPStatusError{Code: resp.StatusCode, Body: bodySnippet(resp.Body, 2048)}
}
if out == nil {
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}
if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
return err
}
_, _ = io.Copy(io.Discard, resp.Body)
return nil
}
func getTransport(getTokenParams *GetTokenParams) *http.Transport {
key := transportCacheKey(getTokenParams)
if cached, ok := transportCache.Load(key); ok {
return cached.(*http.Transport)
}
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.MaxIdleConns = 128
transport.MaxIdleConnsPerHost = 32
if getTokenParams.Proxy != nil {
transport.Proxy = http.ProxyURL(getTokenParams.Proxy)
}
if getTokenParams.SNI != "" {
tlsConfig := &tls.Config{}
if transport.TLSClientConfig != nil {
tlsConfig = transport.TLSClientConfig.Clone()
}
tlsConfig.ServerName = getTokenParams.SNI
transport.TLSClientConfig = tlsConfig
}
actual, _ := transportCache.LoadOrStore(key, transport)
return actual.(*http.Transport)
}
func transportCacheKey(getTokenParams *GetTokenParams) string {
proxyURL := ""
if getTokenParams.Proxy != nil {
proxyURL = getTokenParams.Proxy.String()
}
return proxyURL + "\x00" + getTokenParams.SNI
}