-
Notifications
You must be signed in to change notification settings - Fork 1
/
faucet.go
355 lines (288 loc) · 7.51 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
package main
import (
"encoding/json"
"errors"
"fmt"
"log"
"net/http"
"os"
"os/exec"
"regexp"
"strconv"
"sync"
"time"
"github.com/dpapathanasiou/go-recaptcha"
"github.com/rs/cors"
"github.com/syndtr/goleveldb/leveldb"
"github.com/tendermint/tmlibs/bech32"
"github.com/tomasen/realip"
//"github.com/tendermint/tendermint/crypto"
)
var recaptchaKey string
var palomad string
var port string
var chainID string
var rpcUrl string
var bankAddress string
var mtx sync.Mutex
var isClassic bool
const ( // new core hasn't these yet.
MicroUnit = int64(1e6)
fullFundraiserPath = "m/44'/330'/0'/0/0"
accountAddresPrefix = "paloma"
accountPubKeyPrefix = "palomapub"
validatorAddressPrefix = "palomavaloper"
validatorPubKeyPrefix = "palomavaloperpub"
consNodeAddressPrefix = "palomavalcons"
consNodePubKeyPrefix = "palomavalconspub"
)
var amountTable = map[string]int64{
"ugrain": 10 * MicroUnit,
}
const (
requestLimitSecs = 30
mnemonicVar = "MNEMONIC"
privkeyVar = "PRIV_KEY"
recaptchaKeyVar = "RECAPTCHA_KEY"
portVar = "PORT"
lcdUrlVar = "LCD_URL"
chainIDVar = "CHAIN_ID"
)
// Claim wraps a faucet claim
type Claim struct {
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"`
}
type CoreCoin struct {
Denom string `json:"denom"`
Amount string `json:"amount"`
}
type BalanceResponse struct {
Balance CoreCoin `json:"balance"`
}
func getBalance(address, denom string) (amount int64) {
cmd := exec.Command(
palomad,
"--node", rpcUrl,
"q", "bank", "balance",
"--output", "json",
"--chain-id", chainID,
address,
denom,
)
res, err := cmd.CombinedOutput()
if err != nil {
fmt.Println("error getting the balance information")
fmt.Println(string(res))
panic(err)
}
var balance struct {
Amount string `json:"amount"`
}
err = json.Unmarshal(res, &balance)
if err != nil {
panic(err)
}
if balance.Amount == "" {
return 0
}
amount, err = strconv.ParseInt(balance.Amount, 10, 64)
if err != nil {
panic(err)
}
return amount
}
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 {
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]*2 {
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 {
address, _ := bech32.ConvertAndEncode("paloma", account)
if getBalance(address, denom) >= amountTable[denom]*2 {
return errors.New("amount limit exceeded")
}
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 month was changed
if requestLog.Requested.Month() != now.Month() {
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 {
fmt.Printf("req error: %v\n", err)
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)
}
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)
}
if !captchaPassed {
err := errors.New("captcha failed, please refresh page and try again")
panic(err)
}
// send the coins!
// Limiting request speed
limitErr := checkAndUpdateLimit(db, decodedAddress, claim.Denom)
if limitErr != nil {
panic(limitErr)
}
mtx.Lock()
defer mtx.Unlock()
fmt.Println(time.Now().UTC().Format(time.RFC3339), "req", clientIP, encodedAddress, amount, claim.Denom)
cmd := exec.Command(
palomad,
"--node", rpcUrl,
"tx", "bank", "send",
"-y",
"--broadcast-mode", "sync",
"--chain-id", chainID,
"--fees", "200000ugrain",
bankAddress,
encodedAddress,
fmt.Sprintf("%d%s", amount, claim.Denom),
)
output, err := cmd.CombinedOutput()
if err != nil {
fmt.Printf("error running a command: %s\n", err)
fmt.Println("output:")
fmt.Println(string(output))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
fmt.Fprintf(w, `{"amount": %v}`, amount)
return
}
}
func main() {
bankAddress = os.Getenv("BANK_ADDR")
if bankAddress == "" {
panic("BANK_ADDR variable is required")
}
palomad = os.Getenv("PALOMA_CMD")
if palomad == "" {
panic("PALOMA_CMD variable is required")
}
rpcUrl = os.Getenv("NODE_RPC_URL")
if palomad == "" {
panic("NODE_RPC_URL variable is required")
}
recaptchaKey = os.Getenv(recaptchaKeyVar)
if recaptchaKey == "" {
panic("RECAPTCHA_KEY variable is required")
}
port = os.Getenv(portVar)
if port == "" {
port = "3000"
}
chainID = os.Getenv(chainIDVar)
if chainID == "" {
panic("CHAIN_ID variable is required")
}
db, err := leveldb.OpenFile("db/ipdb", nil)
if err != nil {
panic(err)
}
defer db.Close()
recaptcha.Init(recaptchaKey)
// 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.palomachain.com", "http://localhost", "localhost", "http://localhost:3000", "http://localhost:8080"},
AllowCredentials: true,
})
handler := c.Handler(mux)
if err := http.ListenAndServe(fmt.Sprintf(":%s", port), handler); err != nil {
log.Fatal("failed to start server", err)
}
}