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