forked from terra-money/faucet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
faucet.go
443 lines (361 loc) · 9.83 KB
/
faucet.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
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"regexp"
"strconv"
"strings"
"time"
"github.com/dpapathanasiou/go-recaptcha"
"github.com/syndtr/goleveldb/leveldb"
"github.com/tendermint/tmlibs/bech32"
"github.com/tomasen/realip"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/x/auth"
"github.com/cosmos/cosmos-sdk/x/bank"
bip39 "github.com/cosmos/go-bip39"
"github.com/terra-project/core/app"
core "github.com/terra-project/core/types"
"github.com/rs/cors"
"github.com/tendermint/tendermint/crypto"
"github.com/tendermint/tendermint/crypto/secp256k1"
)
var mnemonic string
var recaptchaKey string
var port string
var lcdURL string
var chainID string
var privKey crypto.PrivKey
var address string
var sequence uint64
var accountNumber uint64
var cdc *codec.Codec
var amountTable = map[string]int64{
core.MicroLunaDenom: 1000 * core.MicroUnit,
core.MicroKRWDenom: 1000 * core.MicroUnit,
core.MicroUSDDenom: 5000 * core.MicroUnit,
core.MicroSDRDenom: 1000 * core.MicroUnit,
core.MicroMNTDenom: 1000 * core.MicroUnit,
}
const (
requestLimitSecs = 30
mnemonicVar = "MNEMONIC"
recaptchaKeyVar = "RECAPTCHA_KEY"
portVar = "PORT"
)
// Claim wraps a faucet claim
type Claim struct {
ChainID string `json:"chain_id"`
LcdURL string `json:"lcd_url"`
Address string `json:"address"`
Response string `json:"response"`
Denom string `json:"denom"`
}
// Coin is the same as sdk.Coin
type Coin struct {
Denom string `json:"denom"`
Amount int64 `json:"amount"`
}
func newCodec() *codec.Codec {
cdc := app.MakeCodec()
config := sdk.GetConfig()
config.SetCoinType(core.CoinType)
config.SetFullFundraiserPath(core.FullFundraiserPath)
config.SetBech32PrefixForAccount(core.Bech32PrefixAccAddr, core.Bech32PrefixAccPub)
config.SetBech32PrefixForValidator(core.Bech32PrefixValAddr, core.Bech32PrefixValPub)
config.SetBech32PrefixForConsensusNode(core.Bech32PrefixConsAddr, core.Bech32PrefixConsPub)
config.Seal()
return cdc
}
func main() {
db, err := leveldb.OpenFile("db/ipdb", nil)
if err != nil {
panic(err)
}
defer db.Close()
mnemonic = os.Getenv(mnemonicVar)
if mnemonic == "" {
panic("MNEMONIC variable is required")
}
recaptchaKey = os.Getenv(recaptchaKeyVar)
if recaptchaKey == "" {
panic("RECAPTCHA_KEY variable is required")
}
port = os.Getenv(portVar)
if port == "" {
port = "3000"
}
cdc = newCodec()
seed := bip39.NewSeed(mnemonic, "")
masterPriv, ch := hd.ComputeMastersFromSeed(seed)
derivedPriv, err := hd.DerivePrivateKeyForPath(masterPriv, ch, core.FullFundraiserPath)
if err != nil {
fmt.Println(err.Error())
return
}
privKey = secp256k1.PrivKeySecp256k1(derivedPriv)
pubk := privKey.PubKey()
address, err = bech32.ConvertAndEncode("terra", pubk.Address())
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(address)
recaptcha.Init(recaptchaKey)
// Pprof server.
go func() {
log.Fatal(http.ListenAndServe("localhost:8081", nil))
}()
// Application server.
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
})
mux.HandleFunc("/claim", createGetCoinsHandler(db))
c := cors.New(cors.Options{
AllowedOrigins: []string{"https://faucet.terra.money"},
AllowCredentials: true,
})
handler := c.Handler(mux)
if err := http.ListenAndServe(fmt.Sprintf(":%s", port), handler); err != nil {
log.Fatal("failed to start server", err)
}
}
func loadAccountInfo() {
// Query current faucet sequence
url := fmt.Sprintf("%v/auth/accounts/%v", lcdURL, address)
response, err := http.Get(url)
if err != nil {
fmt.Println(err.Error())
return
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Println(err.Error())
return
}
bodyStr := string(body)
if strings.Contains(bodyStr, `"sequence"`) {
sequence, _ = strconv.ParseUint(parseRegexp(`"sequence":"?(\d+)"?`, bodyStr), 10, 64)
} else {
sequence = 0
}
if strings.Contains(bodyStr, `"account_number"`) {
accountNumber, _ = strconv.ParseUint(parseRegexp(`"account_number":"?(\d+)"?`, bodyStr), 10, 64)
} else {
accountNumber = 0
}
return
}
func parseRegexp(regexpStr string, target string) (data string) {
// Capture seqeunce string from json
r := regexp.MustCompile(regexpStr)
groups := r.FindStringSubmatch(string(target))
if len(groups) != 2 {
fmt.Printf("cannot find data")
os.Exit(1)
}
// Convert sequence string to int64
data = groups[1]
return
}
// RequestLog stores the Log of a Request
type RequestLog struct {
Coins []Coin `json:"coin"`
Requested time.Time `json:"updated"`
}
func (requestLog *RequestLog) dripCoin(denom string) error {
amount := amountTable[denom]
// try to update coin
for idx, coin := range requestLog.Coins {
if coin.Denom == denom {
if (requestLog.Coins[idx].Amount + amount) > amountTable[denom]*10 {
return errors.New("amount limit exceeded")
}
requestLog.Coins[idx].Amount += amount
return nil
}
}
// first drip for denom
requestLog.Coins = append(requestLog.Coins, Coin{Denom: denom, Amount: amount})
return nil
}
func checkAndUpdateLimit(db *leveldb.DB, account []byte, denom string) error {
var requestLog RequestLog
logBytes, _ := db.Get(account, nil)
now := time.Now()
if logBytes != nil {
jsonErr := json.Unmarshal(logBytes, &requestLog)
if jsonErr != nil {
return jsonErr
}
// check interval limt
intervalSecs := now.Sub(requestLog.Requested).Seconds()
if intervalSecs < requestLimitSecs {
return errors.New("please wait a while for another tap")
}
// reset log if date was changed
if requestLog.Requested.Day() != now.Day() {
requestLog.Coins = []Coin{}
}
// check amount limit
dripErr := requestLog.dripCoin(denom)
if dripErr != nil {
return dripErr
}
}
// update requested time
requestLog.Requested = now
logBytes, _ = json.Marshal(requestLog)
updateErr := db.Put(account, logBytes, nil)
if updateErr != nil {
return updateErr
}
return nil
}
func createGetCoinsHandler(db *leveldb.DB) http.HandlerFunc {
return func(w http.ResponseWriter, request *http.Request) {
defer func() {
if err := recover(); err != nil {
http.Error(w, err.(error).Error(), 400)
}
}()
var claim Claim
// decode JSON response from front end
decoder := json.NewDecoder(request.Body)
decoderErr := decoder.Decode(&claim)
if decoderErr != nil {
panic(decoderErr)
}
chainID = claim.ChainID
lcdURL = claim.LcdURL
loadAccountInfo()
amount, ok := amountTable[claim.Denom]
if !ok {
panic(fmt.Errorf("Invalid Denom; %v", claim.Denom))
}
// make sure address is bech32
readableAddress, decodedAddress, decodeErr := bech32.DecodeAndConvert(claim.Address)
if decodeErr != nil {
panic(decodeErr)
}
// re-encode the address in bech32
encodedAddress, encodeErr := bech32.ConvertAndEncode(readableAddress, decodedAddress)
if encodeErr != nil {
panic(encodeErr)
}
// make sure captcha is valid
clientIP := realip.FromRequest(request)
captchaResponse := claim.Response
captchaPassed, captchaErr := recaptcha.Confirm(clientIP, captchaResponse)
if captchaErr != nil {
panic(captchaErr)
}
// Limiting request speed
limitErr := checkAndUpdateLimit(db, decodedAddress, claim.Denom)
if limitErr != nil {
panic(limitErr)
}
// send the coins!
if captchaPassed {
url := fmt.Sprintf("%v/bank/accounts/%v/transfers", lcdURL, encodedAddress)
data := strings.TrimSpace(fmt.Sprintf(`{
"base_req": {
"from": "%v",
"memo": "%v",
"chain_id": "%v",
"sequence": "%v",
"gas": "auto",
"gas_adjustment": "2.0",
"gas_prices": [
{
"denom": "ukrw",
"amount": "178.05"
}
]
},
"coins": [
{
"denom": "%v",
"amount": "%v"
}
]
}`, address, "faucet", chainID, sequence, claim.Denom, amount))
response, err := http.Post(url, "application/json", bytes.NewReader([]byte(data)))
if err != nil {
panic(err)
}
if response.StatusCode != 200 {
err := errors.New(response.Status)
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
resJSON := signAndBroadcast(body)
fmt.Println(time.Now().UTC().Format(time.RFC3339), encodedAddress, "[1] ", amount, claim.Denom)
fmt.Println(resJSON)
sequence = sequence + 1
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"amount": %v, "response": %v}`, amount, resJSON)
} else {
err := errors.New("captcha failed, please refresh page and try again")
panic(err)
}
return
}
}
// BroadcastReq defines a tx broadcasting request.
type BroadcastReq struct {
Tx auth.StdTx `json:"tx"`
Mode string `json:"mode"`
}
func signAndBroadcast(txJSON []byte) string {
var broadcastReq BroadcastReq
var stdTx auth.StdTx
cdc.MustUnmarshalJSON(txJSON, &stdTx)
// Sort denom
for _, msg := range stdTx.Msgs {
msg, ok := msg.(bank.MsgSend)
if ok {
msg.Amount.Sort()
}
}
signBytes := auth.StdSignBytes(chainID, accountNumber, sequence, stdTx.Fee, stdTx.Msgs, stdTx.Memo)
sig, err := privKey.Sign(signBytes)
if err != nil {
panic(err)
}
sigs := []auth.StdSignature{{
PubKey: privKey.PubKey(),
Signature: sig}}
tx := auth.NewStdTx(stdTx.Msgs, stdTx.Fee, sigs, stdTx.Memo)
broadcastReq.Tx = tx
broadcastReq.Mode = "block"
bz := cdc.MustMarshalJSON(broadcastReq)
url := fmt.Sprintf("%v/txs", lcdURL)
response, err := http.Post(url, "application/json", bytes.NewReader(bz))
if err != nil {
panic(err)
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
panic(err)
}
if response.StatusCode != 200 {
err := fmt.Errorf("status: %v, message: %v", response.Status, string(body))
panic(err)
}
return string(body)
}