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