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