github.com/Elemental-core/elementalcore@v0.0.0-20191206075037-63891242267a/cmd/faucet/faucet.go (about) 1 // Copyright 2017 The elementalcore Authors 2 // This file is part of elementalcore. 3 // 4 // elementalcore is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // elementalcore is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with elementalcore. If not, see <http://www.gnu.org/licenses/>. 16 17 // faucet is a Ether faucet backed by a light client. 18 package main 19 20 //go:generate go-bindata -nometadata -o website.go faucet.html 21 22 import ( 23 "bytes" 24 "compress/zlib" 25 "context" 26 "encoding/json" 27 "errors" 28 "flag" 29 "fmt" 30 "html/template" 31 "io/ioutil" 32 "math" 33 "math/big" 34 "net/http" 35 "net/url" 36 "os" 37 "path/filepath" 38 "regexp" 39 "strconv" 40 "strings" 41 "sync" 42 "time" 43 44 "github.com/Elemental-core/elementalcore/accounts" 45 "github.com/Elemental-core/elementalcore/accounts/keystore" 46 "github.com/Elemental-core/elementalcore/common" 47 "github.com/Elemental-core/elementalcore/core" 48 "github.com/Elemental-core/elementalcore/core/types" 49 "github.com/Elemental-core/elementalcore/eth" 50 "github.com/Elemental-core/elementalcore/eth/downloader" 51 "github.com/Elemental-core/elementalcore/ethclient" 52 "github.com/Elemental-core/elementalcore/ethstats" 53 "github.com/Elemental-core/elementalcore/les" 54 "github.com/Elemental-core/elementalcore/log" 55 "github.com/Elemental-core/elementalcore/node" 56 "github.com/Elemental-core/elementalcore/p2p" 57 "github.com/Elemental-core/elementalcore/p2p/discover" 58 "github.com/Elemental-core/elementalcore/p2p/discv5" 59 "github.com/Elemental-core/elementalcore/p2p/nat" 60 "github.com/Elemental-core/elementalcore/params" 61 "golang.org/x/net/websocket" 62 ) 63 64 var ( 65 genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with") 66 apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection") 67 ethPortFlag = flag.Int("ethport", 30303, "Listener port for the devp2p connection") 68 bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with") 69 netFlag = flag.Uint64("network", 0, "Network ID to use for the Ethereum protocol") 70 statsFlag = flag.String("ethstats", "", "Ethstats network monitoring auth string") 71 72 netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet") 73 payoutFlag = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request") 74 minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds") 75 tiersFlag = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)") 76 77 accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with") 78 accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds") 79 80 githubUser = flag.String("github.user", "", "GitHub user to authenticate with for Gist access") 81 githubToken = flag.String("github.token", "", "GitHub personal token to access Gists with") 82 83 captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side") 84 captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side") 85 86 logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet") 87 ) 88 89 var ( 90 ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) 91 ) 92 93 func main() { 94 // Parse the flags and set up the logger to print everything requested 95 flag.Parse() 96 log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) 97 98 // Construct the payout tiers 99 amounts := make([]string, *tiersFlag) 100 periods := make([]string, *tiersFlag) 101 for i := 0; i < *tiersFlag; i++ { 102 // Calculate the amount for the next tier and format it 103 amount := float64(*payoutFlag) * math.Pow(2.5, float64(i)) 104 amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64)) 105 if amount == 1 { 106 amounts[i] = strings.TrimSuffix(amounts[i], "s") 107 } 108 // Calculate the period for the next tier and format it 109 period := *minutesFlag * int(math.Pow(3, float64(i))) 110 periods[i] = fmt.Sprintf("%d mins", period) 111 if period%60 == 0 { 112 period /= 60 113 periods[i] = fmt.Sprintf("%d hours", period) 114 115 if period%24 == 0 { 116 period /= 24 117 periods[i] = fmt.Sprintf("%d days", period) 118 } 119 } 120 if period == 1 { 121 periods[i] = strings.TrimSuffix(periods[i], "s") 122 } 123 } 124 // Load up and render the faucet website 125 tmpl, err := Asset("faucet.html") 126 if err != nil { 127 log.Crit("Failed to load the faucet template", "err", err) 128 } 129 website := new(bytes.Buffer) 130 err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{ 131 "Network": *netnameFlag, 132 "Amounts": amounts, 133 "Periods": periods, 134 "Recaptcha": *captchaToken, 135 }) 136 if err != nil { 137 log.Crit("Failed to render the faucet template", "err", err) 138 } 139 // Load and parse the genesis block requested by the user 140 blob, err := ioutil.ReadFile(*genesisFlag) 141 if err != nil { 142 log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err) 143 } 144 genesis := new(core.Genesis) 145 if err = json.Unmarshal(blob, genesis); err != nil { 146 log.Crit("Failed to parse genesis block json", "err", err) 147 } 148 // Convert the bootnodes to internal enode representations 149 var enodes []*discv5.Node 150 for _, boot := range strings.Split(*bootFlag, ",") { 151 if url, err := discv5.ParseNode(boot); err == nil { 152 enodes = append(enodes, url) 153 } else { 154 log.Error("Failed to parse bootnode URL", "url", boot, "err", err) 155 } 156 } 157 // Load up the account key and decrypt its password 158 if blob, err = ioutil.ReadFile(*accPassFlag); err != nil { 159 log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err) 160 } 161 pass := string(blob) 162 163 ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP) 164 if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil { 165 log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err) 166 } 167 acc, err := ks.Import(blob, pass, pass) 168 if err != nil { 169 log.Crit("Failed to import faucet signer account", "err", err) 170 } 171 ks.Unlock(acc, pass) 172 173 // Assemble and start the faucet light service 174 faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes()) 175 if err != nil { 176 log.Crit("Failed to start faucet", "err", err) 177 } 178 defer faucet.close() 179 180 if err := faucet.listenAndServe(*apiPortFlag); err != nil { 181 log.Crit("Failed to launch faucet API", "err", err) 182 } 183 } 184 185 // request represents an accepted funding request. 186 type request struct { 187 Avatar string `json:"avatar"` // Avatar URL to make the UI nicer 188 Account common.Address `json:"account"` // Ethereum address being funded 189 Time time.Time `json:"time"` // Timestamp when the request was accepted 190 Tx *types.Transaction `json:"tx"` // Transaction funding the account 191 } 192 193 // faucet represents a crypto faucet backed by an Ethereum light client. 194 type faucet struct { 195 config *params.ChainConfig // Chain configurations for signing 196 stack *node.Node // Ethereum protocol stack 197 client *ethclient.Client // Client connection to the Ethereum chain 198 index []byte // Index page to serve up on the web 199 200 keystore *keystore.KeyStore // Keystore containing the single signer 201 account accounts.Account // Account funding user faucet requests 202 nonce uint64 // Current pending nonce of the faucet 203 price *big.Int // Current gas price to issue funds with 204 205 conns []*websocket.Conn // Currently live websocket connections 206 timeouts map[string]time.Time // History of users and their funding timeouts 207 reqs []*request // Currently pending funding requests 208 update chan struct{} // Channel to signal request updates 209 210 lock sync.RWMutex // Lock protecting the faucet's internals 211 } 212 213 func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) { 214 // Assemble the raw devp2p protocol stack 215 stack, err := node.New(&node.Config{ 216 Name: "geth", 217 Version: params.Version, 218 DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"), 219 P2P: p2p.Config{ 220 NAT: nat.Any(), 221 NoDiscovery: true, 222 DiscoveryV5: true, 223 ListenAddr: fmt.Sprintf(":%d", port), 224 DiscoveryV5Addr: fmt.Sprintf(":%d", port+1), 225 MaxPeers: 25, 226 BootstrapNodesV5: enodes, 227 }, 228 }) 229 if err != nil { 230 return nil, err 231 } 232 // Assemble the Ethereum light client protocol 233 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 234 cfg := eth.DefaultConfig 235 cfg.SyncMode = downloader.LightSync 236 cfg.NetworkId = network 237 cfg.Genesis = genesis 238 return les.New(ctx, &cfg) 239 }); err != nil { 240 return nil, err 241 } 242 // Assemble the ethstats monitoring and reporting service' 243 if stats != "" { 244 if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) { 245 var serv *les.LightEthereum 246 ctx.Service(&serv) 247 return ethstats.New(stats, nil, serv) 248 }); err != nil { 249 return nil, err 250 } 251 } 252 // Boot up the client and ensure it connects to bootnodes 253 if err := stack.Start(); err != nil { 254 return nil, err 255 } 256 for _, boot := range enodes { 257 old, _ := discover.ParseNode(boot.String()) 258 stack.Server().AddPeer(old) 259 } 260 // Attach to the client and retrieve and interesting metadatas 261 api, err := stack.Attach() 262 if err != nil { 263 stack.Stop() 264 return nil, err 265 } 266 client := ethclient.NewClient(api) 267 268 return &faucet{ 269 config: genesis.Config, 270 stack: stack, 271 client: client, 272 index: index, 273 keystore: ks, 274 account: ks.Accounts()[0], 275 timeouts: make(map[string]time.Time), 276 update: make(chan struct{}, 1), 277 }, nil 278 } 279 280 // close terminates the Ethereum connection and tears down the faucet. 281 func (f *faucet) close() error { 282 return f.stack.Stop() 283 } 284 285 // listenAndServe registers the HTTP handlers for the faucet and boots it up 286 // for service user funding requests. 287 func (f *faucet) listenAndServe(port int) error { 288 go f.loop() 289 290 http.HandleFunc("/", f.webHandler) 291 http.Handle("/api", websocket.Handler(f.apiHandler)) 292 293 return http.ListenAndServe(fmt.Sprintf(":%d", port), nil) 294 } 295 296 // webHandler handles all non-api requests, simply flattening and returning the 297 // faucet website. 298 func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) { 299 w.Write(f.index) 300 } 301 302 // apiHandler handles requests for Ether grants and transaction statuses. 303 func (f *faucet) apiHandler(conn *websocket.Conn) { 304 // Start tracking the connection and drop at the end 305 defer conn.Close() 306 307 f.lock.Lock() 308 f.conns = append(f.conns, conn) 309 f.lock.Unlock() 310 311 defer func() { 312 f.lock.Lock() 313 for i, c := range f.conns { 314 if c == conn { 315 f.conns = append(f.conns[:i], f.conns[i+1:]...) 316 break 317 } 318 } 319 f.lock.Unlock() 320 }() 321 // Gather the initial stats from the network to report 322 var ( 323 head *types.Header 324 balance *big.Int 325 nonce uint64 326 err error 327 ) 328 for { 329 // Attempt to retrieve the stats, may error on no faucet connectivity 330 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) 331 head, err = f.client.HeaderByNumber(ctx, nil) 332 if err == nil { 333 balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number) 334 if err == nil { 335 nonce, err = f.client.NonceAt(ctx, f.account.Address, nil) 336 } 337 } 338 cancel() 339 340 // If stats retrieval failed, wait a bit and retry 341 if err != nil { 342 if err = sendError(conn, errors.New("Faucet offline: "+err.Error())); err != nil { 343 log.Warn("Failed to send faucet error to client", "err", err) 344 return 345 } 346 time.Sleep(3 * time.Second) 347 continue 348 } 349 // Initial stats reported successfully, proceed with user interaction 350 break 351 } 352 // Send over the initial stats and the latest header 353 if err = send(conn, map[string]interface{}{ 354 "funds": balance.Div(balance, ether), 355 "funded": nonce, 356 "peers": f.stack.Server().PeerCount(), 357 "requests": f.reqs, 358 }, 3*time.Second); err != nil { 359 log.Warn("Failed to send initial stats to client", "err", err) 360 return 361 } 362 if err = send(conn, head, 3*time.Second); err != nil { 363 log.Warn("Failed to send initial header to client", "err", err) 364 return 365 } 366 // Keep reading requests from the websocket until the connection breaks 367 for { 368 // Fetch the next funding request and validate against github 369 var msg struct { 370 URL string `json:"url"` 371 Tier uint `json:"tier"` 372 Captcha string `json:"captcha"` 373 } 374 if err = websocket.JSON.Receive(conn, &msg); err != nil { 375 return 376 } 377 if !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") && 378 !strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") { 379 if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil { 380 log.Warn("Failed to send URL error to client", "err", err) 381 return 382 } 383 continue 384 } 385 if msg.Tier >= uint(*tiersFlag) { 386 if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil { 387 log.Warn("Failed to send tier error to client", "err", err) 388 return 389 } 390 continue 391 } 392 log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier) 393 394 // If captcha verifications are enabled, make sure we're not dealing with a robot 395 if *captchaToken != "" { 396 form := url.Values{} 397 form.Add("secret", *captchaSecret) 398 form.Add("response", msg.Captcha) 399 400 res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form) 401 if err != nil { 402 if err = sendError(conn, err); err != nil { 403 log.Warn("Failed to send captcha post error to client", "err", err) 404 return 405 } 406 continue 407 } 408 var result struct { 409 Success bool `json:"success"` 410 Errors json.RawMessage `json:"error-codes"` 411 } 412 err = json.NewDecoder(res.Body).Decode(&result) 413 res.Body.Close() 414 if err != nil { 415 if err = sendError(conn, err); err != nil { 416 log.Warn("Failed to send captcha decode error to client", "err", err) 417 return 418 } 419 continue 420 } 421 if !result.Success { 422 log.Warn("Captcha verification failed", "err", string(result.Errors)) 423 if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil { 424 log.Warn("Failed to send captcha failure to client", "err", err) 425 return 426 } 427 continue 428 } 429 } 430 // Retrieve the Ethereum address to fund, the requesting user and a profile picture 431 var ( 432 username string 433 avatar string 434 address common.Address 435 ) 436 switch { 437 case strings.HasPrefix(msg.URL, "https://gist.github.com/"): 438 username, avatar, address, err = authGitHub(msg.URL) 439 case strings.HasPrefix(msg.URL, "https://twitter.com/"): 440 username, avatar, address, err = authTwitter(msg.URL) 441 case strings.HasPrefix(msg.URL, "https://plus.google.com/"): 442 username, avatar, address, err = authGooglePlus(msg.URL) 443 case strings.HasPrefix(msg.URL, "https://www.facebook.com/"): 444 username, avatar, address, err = authFacebook(msg.URL) 445 default: 446 err = errors.New("Something funky happened, please open an issue at https://github.com/Elemental-core/elementalcore/issues") 447 } 448 if err != nil { 449 if err = sendError(conn, err); err != nil { 450 log.Warn("Failed to send prefix error to client", "err", err) 451 return 452 } 453 continue 454 } 455 log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address) 456 457 // Ensure the user didn't request funds too recently 458 f.lock.Lock() 459 var ( 460 fund bool 461 timeout time.Time 462 ) 463 if timeout = f.timeouts[username]; time.Now().After(timeout) { 464 // User wasn't funded recently, create the funding transaction 465 amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether) 466 amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil)) 467 amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil)) 468 469 tx := types.NewTransaction(types.Binary, f.nonce+uint64(len(f.reqs)), address, amount, big.NewInt(21000), f.price, nil) 470 signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainId) 471 if err != nil { 472 f.lock.Unlock() 473 if err = sendError(conn, err); err != nil { 474 log.Warn("Failed to send transaction creation error to client", "err", err) 475 return 476 } 477 continue 478 } 479 // Submit the transaction and mark as funded if successful 480 if err := f.client.SendTransaction(context.Background(), signed); err != nil { 481 f.lock.Unlock() 482 if err = sendError(conn, err); err != nil { 483 log.Warn("Failed to send transaction transmission error to client", "err", err) 484 return 485 } 486 continue 487 } 488 f.reqs = append(f.reqs, &request{ 489 Avatar: avatar, 490 Account: address, 491 Time: time.Now(), 492 Tx: signed, 493 }) 494 f.timeouts[username] = time.Now().Add(time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute) 495 fund = true 496 } 497 f.lock.Unlock() 498 499 // Send an error if too frequent funding, othewise a success 500 if !fund { 501 if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))); err != nil { 502 log.Warn("Failed to send funding error to client", "err", err) 503 return 504 } 505 continue 506 } 507 if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil { 508 log.Warn("Failed to send funding success to client", "err", err) 509 return 510 } 511 select { 512 case f.update <- struct{}{}: 513 default: 514 } 515 } 516 } 517 518 // loop keeps waiting for interesting events and pushes them out to connected 519 // websockets. 520 func (f *faucet) loop() { 521 // Wait for chain events and push them to clients 522 heads := make(chan *types.Header, 16) 523 sub, err := f.client.SubscribeNewHead(context.Background(), heads) 524 if err != nil { 525 log.Crit("Failed to subscribe to head events", "err", err) 526 } 527 defer sub.Unsubscribe() 528 529 for { 530 select { 531 case head := <-heads: 532 // New chain head arrived, query the current stats and stream to clients 533 var ( 534 balance *big.Int 535 nonce uint64 536 price *big.Int 537 err error 538 ) 539 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 540 balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number) 541 if err == nil { 542 nonce, err = f.client.NonceAt(ctx, f.account.Address, nil) 543 if err == nil { 544 price, err = f.client.SuggestGasPrice(ctx) 545 } 546 } 547 cancel() 548 549 // If querying the data failed, try for the next block 550 if err != nil { 551 log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err) 552 continue 553 } else { 554 log.Info("Updated faucet state", "block", head.Number, "hash", head.Hash(), "balance", balance, "nonce", nonce, "price", price) 555 } 556 // Faucet state retrieved, update locally and send to clients 557 balance = new(big.Int).Div(balance, ether) 558 559 f.lock.Lock() 560 f.price, f.nonce = price, nonce 561 for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce { 562 f.reqs = f.reqs[1:] 563 } 564 f.lock.Unlock() 565 566 f.lock.RLock() 567 for _, conn := range f.conns { 568 if err := send(conn, map[string]interface{}{ 569 "funds": balance, 570 "funded": f.nonce, 571 "peers": f.stack.Server().PeerCount(), 572 "requests": f.reqs, 573 }, time.Second); err != nil { 574 log.Warn("Failed to send stats to client", "err", err) 575 conn.Close() 576 continue 577 } 578 if err := send(conn, head, time.Second); err != nil { 579 log.Warn("Failed to send header to client", "err", err) 580 conn.Close() 581 } 582 } 583 f.lock.RUnlock() 584 585 case <-f.update: 586 // Pending requests updated, stream to clients 587 f.lock.RLock() 588 for _, conn := range f.conns { 589 if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil { 590 log.Warn("Failed to send requests to client", "err", err) 591 conn.Close() 592 } 593 } 594 f.lock.RUnlock() 595 } 596 } 597 } 598 599 // sends transmits a data packet to the remote end of the websocket, but also 600 // setting a write deadline to prevent waiting forever on the node. 601 func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error { 602 if timeout == 0 { 603 timeout = 60 * time.Second 604 } 605 conn.SetWriteDeadline(time.Now().Add(timeout)) 606 return websocket.JSON.Send(conn, value) 607 } 608 609 // sendError transmits an error to the remote end of the websocket, also setting 610 // the write deadline to 1 second to prevent waiting forever. 611 func sendError(conn *websocket.Conn, err error) error { 612 return send(conn, map[string]string{"error": err.Error()}, time.Second) 613 } 614 615 // sendSuccess transmits a success message to the remote end of the websocket, also 616 // setting the write deadline to 1 second to prevent waiting forever. 617 func sendSuccess(conn *websocket.Conn, msg string) error { 618 return send(conn, map[string]string{"success": msg}, time.Second) 619 } 620 621 // authGitHub tries to authenticate a faucet request using GitHub gists, returning 622 // the username, avatar URL and Ethereum address to fund on success. 623 func authGitHub(url string) (string, string, common.Address, error) { 624 // Retrieve the gist from the GitHub Gist APIs 625 parts := strings.Split(url, "/") 626 req, _ := http.NewRequest("GET", "https://api.github.com/gists/"+parts[len(parts)-1], nil) 627 if *githubUser != "" { 628 req.SetBasicAuth(*githubUser, *githubToken) 629 } 630 res, err := http.DefaultClient.Do(req) 631 if err != nil { 632 return "", "", common.Address{}, err 633 } 634 var gist struct { 635 Owner struct { 636 Login string `json:"login"` 637 } `json:"owner"` 638 Files map[string]struct { 639 Content string `json:"content"` 640 } `json:"files"` 641 } 642 err = json.NewDecoder(res.Body).Decode(&gist) 643 res.Body.Close() 644 if err != nil { 645 return "", "", common.Address{}, err 646 } 647 if gist.Owner.Login == "" { 648 return "", "", common.Address{}, errors.New("Anonymous Gists not allowed") 649 } 650 // Iterate over all the files and look for Ethereum addresses 651 var address common.Address 652 for _, file := range gist.Files { 653 content := strings.TrimSpace(file.Content) 654 if len(content) == 2+common.AddressLength*2 { 655 address = common.HexToAddress(content) 656 } 657 } 658 if address == (common.Address{}) { 659 return "", "", common.Address{}, errors.New("No Ethereum address found to fund") 660 } 661 // Validate the user's existence since the API is unhelpful here 662 if res, err = http.Head("https://github.com/" + gist.Owner.Login); err != nil { 663 return "", "", common.Address{}, err 664 } 665 res.Body.Close() 666 667 if res.StatusCode != 200 { 668 return "", "", common.Address{}, errors.New("Invalid user... boom!") 669 } 670 // Everything passed validation, return the gathered infos 671 return gist.Owner.Login + "@github", fmt.Sprintf("https://github.com/%s.png?size=64", gist.Owner.Login), address, nil 672 } 673 674 // authTwitter tries to authenticate a faucet request using Twitter posts, returning 675 // the username, avatar URL and Ethereum address to fund on success. 676 func authTwitter(url string) (string, string, common.Address, error) { 677 // Ensure the user specified a meaningful URL, no fancy nonsense 678 parts := strings.Split(url, "/") 679 if len(parts) < 4 || parts[len(parts)-2] != "status" { 680 return "", "", common.Address{}, errors.New("Invalid Twitter status URL") 681 } 682 username := parts[len(parts)-3] 683 684 // Twitter's API isn't really friendly with direct links. Still, we don't 685 // want to do ask read permissions from users, so just load the public posts and 686 // scrape it for the Ethereum address and profile URL. 687 res, err := http.Get(url) 688 if err != nil { 689 return "", "", common.Address{}, err 690 } 691 defer res.Body.Close() 692 693 reader, err := zlib.NewReader(res.Body) 694 if err != nil { 695 return "", "", common.Address{}, err 696 } 697 body, err := ioutil.ReadAll(reader) 698 if err != nil { 699 return "", "", common.Address{}, err 700 } 701 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 702 if address == (common.Address{}) { 703 return "", "", common.Address{}, errors.New("No Ethereum address found to fund") 704 } 705 var avatar string 706 if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 707 avatar = parts[1] 708 } 709 return username + "@twitter", avatar, address, nil 710 } 711 712 // authGooglePlus tries to authenticate a faucet request using GooglePlus posts, 713 // returning the username, avatar URL and Ethereum address to fund on success. 714 func authGooglePlus(url string) (string, string, common.Address, error) { 715 // Ensure the user specified a meaningful URL, no fancy nonsense 716 parts := strings.Split(url, "/") 717 if len(parts) < 4 || parts[len(parts)-2] != "posts" { 718 return "", "", common.Address{}, errors.New("Invalid Google+ post URL") 719 } 720 username := parts[len(parts)-3] 721 722 // Google's API isn't really friendly with direct links. Still, we don't 723 // want to do ask read permissions from users, so just load the public posts and 724 // scrape it for the Ethereum address and profile URL. 725 res, err := http.Get(url) 726 if err != nil { 727 return "", "", common.Address{}, err 728 } 729 defer res.Body.Close() 730 731 body, err := ioutil.ReadAll(res.Body) 732 if err != nil { 733 return "", "", common.Address{}, err 734 } 735 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 736 if address == (common.Address{}) { 737 return "", "", common.Address{}, errors.New("No Ethereum address found to fund") 738 } 739 var avatar string 740 if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 741 avatar = parts[1] 742 } 743 return username + "@google+", avatar, address, nil 744 } 745 746 // authFacebook tries to authenticate a faucet request using Facebook posts, 747 // returning the username, avatar URL and Ethereum address to fund on success. 748 func authFacebook(url string) (string, string, common.Address, error) { 749 // Ensure the user specified a meaningful URL, no fancy nonsense 750 parts := strings.Split(url, "/") 751 if len(parts) < 4 || parts[len(parts)-2] != "posts" { 752 return "", "", common.Address{}, errors.New("Invalid Facebook post URL") 753 } 754 username := parts[len(parts)-3] 755 756 // Facebook's Graph API isn't really friendly with direct links. Still, we don't 757 // want to do ask read permissions from users, so just load the public posts and 758 // scrape it for the Ethereum address and profile URL. 759 res, err := http.Get(url) 760 if err != nil { 761 return "", "", common.Address{}, err 762 } 763 defer res.Body.Close() 764 765 body, err := ioutil.ReadAll(res.Body) 766 if err != nil { 767 return "", "", common.Address{}, err 768 } 769 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 770 if address == (common.Address{}) { 771 return "", "", common.Address{}, errors.New("No Ethereum address found to fund") 772 } 773 var avatar string 774 if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 775 avatar = parts[1] 776 } 777 return username + "@facebook", avatar, address, nil 778 }