forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.go
476 lines (417 loc) · 10.2 KB
/
serve.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"net"
"net/http"
"strings"
"time"
"github.com/gnolang/gno/gno.land/pkg/gnoland"
"github.com/gnolang/gno/tm2/pkg/amino"
rpcclient "github.com/gnolang/gno/tm2/pkg/bft/rpc/client"
"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/crypto/keys"
"github.com/gnolang/gno/tm2/pkg/crypto/keys/client"
"github.com/gnolang/gno/tm2/pkg/errors"
"github.com/gnolang/gno/tm2/pkg/sdk/bank"
"github.com/gnolang/gno/tm2/pkg/std"
)
// url & struct for verify captcha
const siteVerifyURL = "https://www.google.com/recaptcha/api/siteverify"
type SiteVerifyResponse struct {
Success bool `json:"success"`
Score float64 `json:"score"`
Action string `json:"action"`
ChallengeTS time.Time `json:"challenge_ts"`
Hostname string `json:"hostname"`
ErrorCodes []string `json:"error-codes"`
}
type config struct {
client.BaseOptions // home, ...
ChainID string
GasWanted int64
GasFee string
Memo string
TestTo string
Send string
CaptchaSecret string
IsBehindProxy bool
InsecurePasswordStdin bool
}
func newServeCmd() *commands.Command {
cfg := &config{}
return commands.NewCommand(
commands.Metadata{
Name: "serve",
ShortUsage: "serve [flags] <key>",
LongHelp: "Serves the gno.land faucet to users",
},
cfg,
func(_ context.Context, args []string) error {
return execServe(cfg, args, commands.NewDefaultIO())
},
)
}
func (c *config) RegisterFlags(fs *flag.FlagSet) {
// Base config options
fs.StringVar(
&c.BaseOptions.Home,
"home",
client.DefaultBaseOptions.Home,
"home directory",
)
fs.StringVar(
&c.BaseOptions.Remote,
"remote",
client.DefaultBaseOptions.Remote,
"remote node URL",
)
fs.BoolVar(
&c.BaseOptions.Quiet,
"quiet",
client.DefaultBaseOptions.Quiet,
"for parsing output",
)
// Command options
fs.StringVar(
&c.ChainID,
"chain-id",
"",
"the ID of the chain",
)
fs.Int64Var(
&c.GasWanted,
"gas-wanted",
50000,
"gas requested for the tx",
)
fs.StringVar(
&c.GasFee,
"gas-fee",
"1000000ugnot",
"gas payment fee",
)
fs.StringVar(
&c.Memo,
"memo",
"",
"any descriptive text",
)
fs.StringVar(
&c.TestTo,
"test-to",
"",
"test address (optional)",
)
fs.StringVar(
&c.Send,
"send",
"1000000ugnot",
"send coins",
)
fs.StringVar(
&c.CaptchaSecret,
"captcha-secret",
"",
"recaptcha secret key (if empty, captcha are disabled)",
)
fs.BoolVar(
&c.IsBehindProxy,
"is-behind-proxy",
false,
"use X-Forwarded-For IP for throttling",
)
fs.BoolVar(
&c.InsecurePasswordStdin,
"insecure-password-stdin",
false,
"WARNING! take password from stdin",
)
}
func execServe(cfg *config, args []string, io *commands.IO) error {
if len(args) != 1 {
return flag.ErrHelp
}
if cfg.ChainID == "" {
return errors.New("chain-id not specified")
}
if cfg.GasWanted == 0 {
return errors.New("gas-wanted not specified")
}
if cfg.GasFee == "" {
return errors.New("gas-fee not specified")
}
remote := cfg.Remote
if remote == "" || remote == "y" {
return errors.New("missing remote url")
}
cli := rpcclient.NewHTTP(remote, "/websocket")
// XXX XXX
// Read supply account pubkey.
name := args[0]
kb, err := keys.NewKeyBaseFromDir(cfg.Home)
if err != nil {
return err
}
info, err := kb.GetByName(name)
if err != nil {
return err
}
fromAddr := info.GetAddress()
// query for initial number and sequence.
path := fmt.Sprintf("auth/accounts/%s", fromAddr.String())
data := []byte(nil)
opts2 := rpcclient.ABCIQueryOptions{}
qres, err := cli.ABCIQueryWithOptions(
path, data, opts2)
if err != nil {
return errors.Wrap(err, "querying")
}
if qres.Response.Error != nil {
fmt.Printf("Log: %s\n",
qres.Response.Log)
return qres.Response.Error
}
resdata := qres.Response.Data
var acc gnoland.GnoAccount
amino.MustUnmarshalJSON(resdata, &acc)
accountNumber := acc.BaseAccount.AccountNumber
sequence := acc.BaseAccount.Sequence
// Get password for supply account.
// Test by signing a dummy message;
const dummy = "test"
var pass string
if cfg.Quiet {
pass, err = io.GetPassword("", cfg.InsecurePasswordStdin)
} else {
pass, err = io.GetPassword("Enter password", cfg.InsecurePasswordStdin)
}
if err != nil {
return err
}
_, _, err = kb.Sign(name, pass, []byte(dummy))
if err != nil {
return err
}
// Parse send amount.
send, err := std.ParseCoins(cfg.Send)
if err != nil {
return errors.Wrap(err, "parsing send coins")
}
// Parse test-to address. If present, send and quit.
if cfg.TestTo != "" {
testToAddr, err := crypto.AddressFromBech32(cfg.TestTo)
if err != nil {
return err
}
err = sendAmountTo(cfg, cli, io, name, pass, testToAddr, accountNumber, sequence, send)
return err
}
// Start throttled faucet.
st := NewSubnetThrottler()
st.Start()
// handle route using handler function
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
host := ""
if !cfg.IsBehindProxy {
addr := r.RemoteAddr
host_, _, err := net.SplitHostPort(addr)
if err != nil {
return
}
host = host_
} else if xff, found := r.Header["X-Forwarded-For"]; found && len(xff) > 0 {
host = xff[0]
}
// if can't identify the IP, everyone is in the same pool.
// if host using ipv6 loopback addr, make it ipv4
if host == "" || host == "::1" || host == "0:0:0:0:0:0:0:1" {
host = "127.0.0.1"
}
ip := net.ParseIP(host)
if ip == nil {
fmt.Println("no ip found")
w.Write([]byte("no ip found"))
return
}
allowed, reason := st.Request(ip)
if !allowed {
msg := fmt.Sprintf("abuse protection system (%s)", reason)
fmt.Println(ip, msg)
w.Write([]byte(msg))
return
}
r.ParseForm()
// only when command line argument 'captcha-secret' has entered > captcha are enabled.
// verify captcha
if cfg.CaptchaSecret != "" {
passedMsg := r.Form["g-recaptcha-response"]
if passedMsg == nil {
fmt.Println(ip, "no 'captcha' request")
w.Write([]byte("check captcha request"))
return
}
capMsg := strings.TrimSpace(passedMsg[0])
if err := checkRecaptcha(cfg.CaptchaSecret, capMsg); err != nil {
fmt.Printf("%s recaptcha failed; %v\n", ip, err)
w.Write([]byte("Unauthorized"))
return
}
}
passedAddr := r.Form["toaddr"]
if passedAddr == nil {
fmt.Println(ip, "no address found")
w.Write([]byte("no address found"))
return
}
toAddrStr := strings.TrimSpace(passedAddr[0])
// OK.
toAddr, err := crypto.AddressFromBech32(toAddrStr)
if err != nil {
fmt.Println(ip, "invalid address format", err)
w.Write([]byte("invalid address format"))
return
}
err = sendAmountTo(cfg, cli, io, name, pass, toAddr, accountNumber, sequence, send)
if err != nil {
fmt.Println(ip, "faucet failed", err)
w.Write([]byte("faucet failed"))
return
} else {
sequence += 1
fmt.Println(ip, "faucet success")
w.Write([]byte("faucet success"))
}
})
// listen to port
fmt.Println("Starting server at port 5050")
server := &http.Server{
Addr: ":5050",
ReadHeaderTimeout: 60 * time.Second,
}
server.ListenAndServe()
return nil
}
func sendAmountTo(
cfg *config,
cli rpcclient.Client,
io *commands.IO,
name,
pass string,
toAddr crypto.Address,
accountNumber,
sequence uint64,
send std.Coins,
) error {
// Read supply account pubkey.
kb, err := keys.NewKeyBaseFromDir(cfg.Home)
if err != nil {
return err
}
info, err := kb.GetByName(name)
if err != nil {
return err
}
fromAddr := info.GetAddress()
pub := info.GetPubKey()
// parse gas wanted & fee.
gaswanted := cfg.GasWanted
gasfee, err := std.ParseCoin(cfg.GasFee)
if err != nil {
return errors.Wrap(err, "parsing gas fee coin")
}
// construct msg & tx and marshal.
msg := bank.MsgSend{
FromAddress: fromAddr,
ToAddress: toAddr,
Amount: send,
}
tx := std.Tx{
Msgs: []std.Msg{msg},
Fee: std.NewFee(gaswanted, gasfee),
Signatures: nil,
Memo: cfg.Memo,
}
// fill tx signatures.
signers := tx.GetSigners()
if tx.Signatures == nil {
for range signers {
tx.Signatures = append(tx.Signatures, std.Signature{
PubKey: nil, // zero signature
Signature: nil, // zero signature
})
}
}
err = tx.ValidateBasic()
if err != nil {
return err
}
// fmt.Println("will sign:", string(amino.MustMarshalJSON(tx)))
// get sign-bytes and make signature.
chainID := cfg.ChainID
signbz := tx.GetSignBytes(chainID, accountNumber, sequence)
sig, _, err := kb.Sign(name, pass, signbz)
if err != nil {
return err
}
found := false
for i := range tx.Signatures {
// override signature for matching slot.
if signers[i] == fromAddr {
found = true
tx.Signatures[i] = std.Signature{
PubKey: pub,
Signature: sig,
}
}
}
if !found {
return errors.New("addr %v (%s) not in signer set",
fromAddr, name)
}
fmt.Println("will deliver:", string(amino.MustMarshalJSON(tx)))
// construct tx serialized bytes.
txbz := amino.MustMarshal(tx)
// broadcast tx bytes.
bres, err := cli.BroadcastTxCommit(txbz)
if err != nil {
return errors.Wrap(err, "broadcasting bytes")
}
if bres.CheckTx.IsErr() {
return errors.New("transaction failed %#v\nlog %s", bres, bres.CheckTx.Log)
} else if bres.DeliverTx.IsErr() {
return errors.New("transaction failed %#v\nlog %s", bres, bres.DeliverTx.Log)
} else {
io.Println(string(bres.DeliverTx.Data))
io.Println("OK!")
io.Println("GAS WANTED:", bres.DeliverTx.GasWanted)
io.Println("GAS USED: ", bres.DeliverTx.GasUsed)
}
return nil
}
func checkRecaptcha(secret, response string) error {
req, err := http.NewRequest(http.MethodPost, siteVerifyURL, nil)
if err != nil {
return err
}
q := req.URL.Query()
q.Add("secret", secret)
q.Add("response", response)
req.URL.RawQuery = q.Encode()
resp, err := http.DefaultClient.Do(req) // 200 OK
if err != nil {
return err
}
defer resp.Body.Close()
var body SiteVerifyResponse
if err = json.NewDecoder(resp.Body).Decode(&body); err != nil {
return errors.New("fail, decode response")
}
if !body.Success {
return errors.New("unsuccessful recaptcha verify request")
}
return nil
}