github.com/core-coin/go-core/v2@v2.1.9/cmd/faucet/faucet.go (about) 1 // Copyright 2017 by the Authors 2 // This file is part of go-core. 3 // 4 // go-core 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-core 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-core. If not, see <http://www.gnu.org/licenses/>. 16 17 // faucet is a Core faucet backed by a light client. 18 package main 19 20 //go:generate go-bindata -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 46 "github.com/core-coin/go-core/v2/accounts" 47 "github.com/core-coin/go-core/v2/accounts/keystore" 48 "github.com/core-coin/go-core/v2/common" 49 "github.com/core-coin/go-core/v2/core" 50 "github.com/core-coin/go-core/v2/core/types" 51 "github.com/core-coin/go-core/v2/les" 52 "github.com/core-coin/go-core/v2/log" 53 "github.com/core-coin/go-core/v2/node" 54 "github.com/core-coin/go-core/v2/p2p" 55 "github.com/core-coin/go-core/v2/p2p/discv5" 56 "github.com/core-coin/go-core/v2/p2p/enode" 57 "github.com/core-coin/go-core/v2/p2p/nat" 58 "github.com/core-coin/go-core/v2/params" 59 "github.com/core-coin/go-core/v2/xcb" 60 "github.com/core-coin/go-core/v2/xcb/downloader" 61 "github.com/core-coin/go-core/v2/xcbclient" 62 "github.com/core-coin/go-core/v2/xcbstats" 63 ) 64 65 var ( 66 genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with") 67 apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection") 68 xcbPortFlag = flag.Int("xcbport", 30300, "Listener port for the devp2p connection") 69 bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with") 70 netFlag = flag.Uint64("network", 0, "Network ID to use for the Core protocol") 71 statsFlag = flag.String("xcbstats", "", "Xcbstats network monitoring auth string") 72 73 netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet") 74 payoutFlag = flag.Int("faucet.amount", 1, "Number of Cores to pay out per user request") 75 minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds") 76 tiersFlag = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)") 77 78 accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with") 79 accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds") 80 81 captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side") 82 captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side") 83 84 noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication") 85 logFlag = flag.Int("loglevel", 3, "Log level to use for Core and the faucet") 86 ) 87 88 var ( 89 coree = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) 90 ) 91 92 var ( 93 gitTag = "" 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 Cores", 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, *xcbPortFlag, 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"` // Core 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 Core light client. 201 type faucet struct { 202 config *params.ChainConfig // Chain configurations for signing 203 stack *node.Node // Core protocol stack 204 client *xcbclient.Client // Client connection to the Core 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 energy 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: "gocore", 226 Version: params.VersionWithTag("faucet", 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 241 // Assemble the Сore light client protocol 242 cfg := xcb.DefaultConfig 243 cfg.SyncMode = downloader.LightSync 244 cfg.NetworkId = network 245 cfg.Genesis = genesis 246 lesBackend, err := les.New(stack, &cfg) 247 if err != nil { 248 return nil, fmt.Errorf("Failed to register the Core service: %w", err) 249 } 250 251 // Assemble the xcbstats monitoring and reporting service' 252 if stats != "" { 253 if err := xcbstats.New(stack, lesBackend.ApiBackend, lesBackend.Engine(), stats); err != nil { 254 return nil, err 255 } 256 } 257 // Boot up the client and ensure it connects to bootnodes 258 if err := stack.Start(); err != nil { 259 return nil, err 260 } 261 for _, boot := range enodes { 262 old, err := enode.Parse(enode.ValidSchemes, boot.String()) 263 if err == nil { 264 stack.Server().AddPeer(old) 265 } 266 } 267 // Attach to the client and retrieve and interesting metadatas 268 api, err := stack.Attach() 269 if err != nil { 270 stack.Close() 271 return nil, err 272 } 273 client := xcbclient.NewClient(api) 274 275 return &faucet{ 276 config: genesis.Config, 277 stack: stack, 278 client: client, 279 index: index, 280 keystore: ks, 281 account: ks.Accounts()[0], 282 timeouts: make(map[string]time.Time), 283 update: make(chan struct{}, 1), 284 }, nil 285 } 286 287 // close terminates the Core connection and tears down the faucet. 288 func (f *faucet) close() error { 289 return f.stack.Close() 290 } 291 292 // listenAndServe registers the HTTP handlers for the faucet and boots it up 293 // for service user funding requests. 294 func (f *faucet) listenAndServe(port int) error { 295 go f.loop() 296 297 http.HandleFunc("/", f.webHandler) 298 http.HandleFunc("/api", f.apiHandler) 299 return http.ListenAndServe(fmt.Sprintf(":%d", port), nil) 300 } 301 302 // webHandler handles all non-api requests, simply flattening and returning the 303 // faucet website. 304 func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) { 305 w.Write(f.index) 306 } 307 308 // apiHandler handles requests for Core grants and transaction statuses. 309 func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) { 310 upgrader := websocket.Upgrader{} 311 conn, err := upgrader.Upgrade(w, r, nil) 312 if err != nil { 313 return 314 } 315 316 // Start tracking the connection and drop at the end 317 defer conn.Close() 318 319 f.lock.Lock() 320 f.conns = append(f.conns, conn) 321 f.lock.Unlock() 322 323 defer func() { 324 f.lock.Lock() 325 for i, c := range f.conns { 326 if c == conn { 327 f.conns = append(f.conns[:i], f.conns[i+1:]...) 328 break 329 } 330 } 331 f.lock.Unlock() 332 }() 333 // Gather the initial stats from the network to report 334 var ( 335 head *types.Header 336 balance *big.Int 337 nonce uint64 338 ) 339 for head == nil || balance == nil { 340 // Retrieve the current stats cached by the faucet 341 f.lock.RLock() 342 if f.head != nil { 343 head = types.CopyHeader(f.head) 344 } 345 if f.balance != nil { 346 balance = new(big.Int).Set(f.balance) 347 } 348 nonce = f.nonce 349 f.lock.RUnlock() 350 351 if head == nil || balance == nil { 352 // Report the faucet offline until initial stats are ready 353 //lint:ignore ST1005 This error is to be displayed in the browser 354 if err = sendError(conn, errors.New("Faucet offline")); err != nil { 355 log.Warn("Failed to send faucet error to client", "err", err) 356 return 357 } 358 time.Sleep(3 * time.Second) 359 } 360 } 361 // Send over the initial stats and the latest header 362 f.lock.RLock() 363 reqs := f.reqs 364 f.lock.RUnlock() 365 if err = send(conn, map[string]interface{}{ 366 "funds": new(big.Int).Div(balance, coree), 367 "funded": nonce, 368 "peers": f.stack.Server().PeerCount(), 369 "requests": reqs, 370 }, 3*time.Second); err != nil { 371 log.Warn("Failed to send initial stats to client", "err", err) 372 return 373 } 374 if err = send(conn, head, 3*time.Second); err != nil { 375 log.Warn("Failed to send initial header to client", "err", err) 376 return 377 } 378 // Keep reading requests from the websocket until the connection breaks 379 for { 380 // Fetch the next funding request and validate against github 381 var msg struct { 382 URL string `json:"url"` 383 Tier uint `json:"tier"` 384 Captcha string `json:"captcha"` 385 } 386 if err = conn.ReadJSON(&msg); err != nil { 387 return 388 } 389 if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") && 390 !strings.HasPrefix(msg.URL, "https://www.facebook.com/") { 391 if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil { 392 log.Warn("Failed to send URL error to client", "err", err) 393 return 394 } 395 continue 396 } 397 if msg.Tier >= uint(*tiersFlag) { 398 //lint:ignore ST1005 This error is to be displayed in the browser 399 if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil { 400 log.Warn("Failed to send tier error to client", "err", err) 401 return 402 } 403 continue 404 } 405 log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier) 406 407 // If captcha verifications are enabled, make sure we're not dealing with a robot 408 if *captchaToken != "" { 409 form := url.Values{} 410 form.Add("secret", *captchaSecret) 411 form.Add("response", msg.Captcha) 412 413 res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form) 414 if err != nil { 415 if err = sendError(conn, err); err != nil { 416 log.Warn("Failed to send captcha post error to client", "err", err) 417 return 418 } 419 continue 420 } 421 var result struct { 422 Success bool `json:"success"` 423 Errors json.RawMessage `json:"error-codes"` 424 } 425 err = json.NewDecoder(res.Body).Decode(&result) 426 res.Body.Close() 427 if err != nil { 428 if err = sendError(conn, err); err != nil { 429 log.Warn("Failed to send captcha decode error to client", "err", err) 430 return 431 } 432 continue 433 } 434 if !result.Success { 435 log.Warn("Captcha verification failed", "err", string(result.Errors)) 436 //lint:ignore ST1005 it's funny and the robot won't mind 437 if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil { 438 log.Warn("Failed to send captcha failure to client", "err", err) 439 return 440 } 441 continue 442 } 443 } 444 // Retrieve the Core address to fund, the requesting user and a profile picture 445 var ( 446 username string 447 avatar string 448 address common.Address 449 ) 450 switch { 451 case strings.HasPrefix(msg.URL, "https://gist.github.com/"): 452 if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil { 453 log.Warn("Failed to send GitHub deprecation to client", "err", err) 454 return 455 } 456 continue 457 case strings.HasPrefix(msg.URL, "https://twitter.com/"): 458 username, avatar, address, err = authTwitter(msg.URL) 459 case strings.HasPrefix(msg.URL, "https://www.facebook.com/"): 460 username, avatar, address, err = authFacebook(msg.URL) 461 case *noauthFlag: 462 username, avatar, address, err = authNoAuth(msg.URL) 463 default: 464 //lint:ignore ST1005 This error is to be displayed in the browser 465 err = errors.New("Something funky happened, please open an issue at https://github.com/core-coin/go-core/issues") 466 } 467 if err != nil { 468 if err = sendError(conn, err); err != nil { 469 log.Warn("Failed to send prefix error to client", "err", err) 470 return 471 } 472 continue 473 } 474 log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address) 475 476 // Ensure the user didn't request funds too recently 477 f.lock.Lock() 478 var ( 479 fund bool 480 timeout time.Time 481 ) 482 if timeout = f.timeouts[username]; time.Now().After(timeout) { 483 // User wasn't funded recently, create the funding transaction 484 amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), coree) 485 amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil)) 486 amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil)) 487 488 tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil) 489 signed, err := f.keystore.SignTx(f.account, tx, f.config.NetworkID) 490 if err != nil { 491 f.lock.Unlock() 492 if err = sendError(conn, err); err != nil { 493 log.Warn("Failed to send transaction creation error to client", "err", err) 494 return 495 } 496 continue 497 } 498 // Submit the transaction and mark as funded if successful 499 if err := f.client.SendTransaction(context.Background(), signed); err != nil { 500 f.lock.Unlock() 501 if err = sendError(conn, err); err != nil { 502 log.Warn("Failed to send transaction transmission error to client", "err", err) 503 return 504 } 505 continue 506 } 507 f.reqs = append(f.reqs, &request{ 508 Avatar: avatar, 509 Account: address, 510 Time: time.Now(), 511 Tx: signed, 512 }) 513 timeout := time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute 514 grace := timeout / 288 // 24h timeout => 5m grace 515 516 f.timeouts[username] = time.Now().Add(timeout - grace) 517 fund = true 518 } 519 f.lock.Unlock() 520 521 // Send an error if too frequent funding, othewise a success 522 if !fund { 523 if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(time.Until(timeout)))); err != nil { // nolint: gosimple 524 log.Warn("Failed to send funding error to client", "err", err) 525 return 526 } 527 continue 528 } 529 if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil { 530 log.Warn("Failed to send funding success to client", "err", err) 531 return 532 } 533 select { 534 case f.update <- struct{}{}: 535 default: 536 } 537 } 538 } 539 540 // refresh attempts to retrieve the latest header from the chain and extract the 541 // associated faucet balance and nonce for connectivity caching. 542 func (f *faucet) refresh(head *types.Header) error { 543 // Ensure a state update does not run for too long 544 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 545 defer cancel() 546 547 // If no header was specified, use the current chain head 548 var err error 549 if head == nil { 550 if head, err = f.client.HeaderByNumber(ctx, nil); err != nil { 551 return err 552 } 553 } 554 // Retrieve the balance, nonce and energy price from the current head 555 var ( 556 balance *big.Int 557 nonce uint64 558 price *big.Int 559 ) 560 if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil { 561 return err 562 } 563 if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil { 564 return err 565 } 566 if price, err = f.client.SuggestEnergyPrice(ctx); err != nil { 567 return err 568 } 569 // Everything succeeded, update the cached stats and eject old requests 570 f.lock.Lock() 571 f.head, f.balance = head, balance 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 return nil 579 } 580 581 // loop keeps waiting for interesting events and pushes them out to connected 582 // websockets. 583 func (f *faucet) loop() { 584 // Wait for chain events and push them to clients 585 heads := make(chan *types.Header, 16) 586 sub, err := f.client.SubscribeNewHead(context.Background(), heads) 587 if err != nil { 588 log.Crit("Failed to subscribe to head events", "err", err) 589 } 590 defer sub.Unsubscribe() 591 592 // Start a goroutine to update the state from head notifications in the background 593 update := make(chan *types.Header) 594 595 go func() { 596 for head := range update { 597 // New chain head arrived, query the current stats and stream to clients 598 timestamp := time.Unix(int64(head.Time), 0) 599 if time.Since(timestamp) > time.Hour { 600 log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp)) 601 continue 602 } 603 if err := f.refresh(head); err != nil { 604 log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err) 605 continue 606 } 607 // Faucet state retrieved, update locally and send to clients 608 f.lock.RLock() 609 log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price) 610 611 balance := new(big.Int).Div(f.balance, coree) 612 peers := f.stack.Server().PeerCount() 613 614 for _, conn := range f.conns { 615 if err := send(conn, map[string]interface{}{ 616 "funds": balance, 617 "funded": f.nonce, 618 "peers": peers, 619 "requests": f.reqs, 620 }, time.Second); err != nil { 621 log.Warn("Failed to send stats to client", "err", err) 622 conn.Close() 623 continue 624 } 625 if err := send(conn, head, time.Second); err != nil { 626 log.Warn("Failed to send header to client", "err", err) 627 conn.Close() 628 } 629 } 630 f.lock.RUnlock() 631 } 632 }() 633 // Wait for various events and assing to the appropriate background threads 634 for { 635 select { 636 case head := <-heads: 637 // New head arrived, send if for state update if there's none running 638 select { 639 case update <- head: 640 default: 641 } 642 643 case <-f.update: 644 // Pending requests updated, stream to clients 645 f.lock.RLock() 646 for _, conn := range f.conns { 647 if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil { 648 log.Warn("Failed to send requests to client", "err", err) 649 conn.Close() 650 } 651 } 652 f.lock.RUnlock() 653 } 654 } 655 } 656 657 // sends transmits a data packet to the remote end of the websocket, but also 658 // setting a write deadline to prevent waiting forever on the node. 659 func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error { 660 if timeout == 0 { 661 timeout = 60 * time.Second 662 } 663 conn.SetWriteDeadline(time.Now().Add(timeout)) 664 return conn.WriteJSON(value) 665 } 666 667 // sendError transmits an error to the remote end of the websocket, also setting 668 // the write deadline to 1 second to prevent waiting forever. 669 func sendError(conn *websocket.Conn, err error) error { 670 return send(conn, map[string]string{"error": err.Error()}, time.Second) 671 } 672 673 // sendSuccess transmits a success message to the remote end of the websocket, also 674 // setting the write deadline to 1 second to prevent waiting forever. 675 func sendSuccess(conn *websocket.Conn, msg string) error { 676 return send(conn, map[string]string{"success": msg}, time.Second) 677 } 678 679 // authTwitter tries to authenticate a faucet request using Twitter posts, returning 680 // the username, avatar URL and Core address to fund on success. 681 func authTwitter(url string) (string, string, common.Address, error) { 682 // Ensure the user specified a meaningful URL, no fancy nonsense 683 parts := strings.Split(url, "/") 684 if len(parts) < 4 || parts[len(parts)-2] != "status" { 685 //lint:ignore ST1005 This error is to be displayed in the browser 686 return "", "", common.Address{}, errors.New("Invalid Twitter status URL") 687 } 688 // Twitter's API isn't really friendly with direct links. Still, we don't 689 // want to do ask read permissions from users, so just load the public posts and 690 // scrape it for the Core address and profile URL. 691 res, err := http.Get(url) 692 if err != nil { 693 return "", "", common.Address{}, err 694 } 695 defer res.Body.Close() 696 697 // Resolve the username from the final redirect, no intermediate junk 698 parts = strings.Split(res.Request.URL.String(), "/") 699 if len(parts) < 4 || parts[len(parts)-2] != "status" { 700 //lint:ignore ST1005 This error is to be displayed in the browser 701 return "", "", common.Address{}, errors.New("Invalid Twitter status URL") 702 } 703 username := parts[len(parts)-3] 704 705 body, err := ioutil.ReadAll(res.Body) 706 if err != nil { 707 return "", "", common.Address{}, err 708 } 709 address, err := common.HexToAddress(string(regexp.MustCompile("[0-9a-fA-F]{44}").Find(body))) 710 if err != nil { 711 return "", "", common.Address{}, err 712 } 713 if address == (common.Address{}) { 714 //lint:ignore ST1005 This error is to be displayed in the browser 715 return "", "", common.Address{}, errors.New("No Core address found to fund") 716 } 717 var avatar string 718 if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 719 avatar = parts[1] 720 } 721 return username + "@twitter", avatar, address, nil 722 } 723 724 // authFacebook tries to authenticate a faucet request using Facebook posts, 725 // returning the username, avatar URL and Core address to fund on success. 726 func authFacebook(url string) (string, string, common.Address, error) { 727 // Ensure the user specified a meaningful URL, no fancy nonsense 728 parts := strings.Split(url, "/") 729 if len(parts) < 4 || parts[len(parts)-2] != "posts" { 730 //lint:ignore ST1005 This error is to be displayed in the browser 731 return "", "", common.Address{}, errors.New("Invalid Facebook post URL") 732 } 733 username := parts[len(parts)-3] 734 735 // Facebook's Graph API isn't really friendly with direct links. Still, we don't 736 // want to do ask read permissions from users, so just load the public posts and 737 // scrape it for the Core address and profile URL. 738 res, err := http.Get(url) 739 if err != nil { 740 return "", "", common.Address{}, err 741 } 742 defer res.Body.Close() 743 744 body, err := ioutil.ReadAll(res.Body) 745 if err != nil { 746 return "", "", common.Address{}, err 747 } 748 address, err := common.HexToAddress(string(regexp.MustCompile("[0-9a-fA-F]{44}").Find(body))) 749 if err != nil { 750 return "", "", common.Address{}, err 751 } 752 if address == (common.Address{}) { 753 //lint:ignore ST1005 This error is to be displayed in the browser 754 return "", "", common.Address{}, errors.New("No Core address found to fund") 755 } 756 var avatar string 757 if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 { 758 avatar = parts[1] 759 } 760 return username + "@facebook", avatar, address, nil 761 } 762 763 // authNoAuth tries to interpret a faucet request as a plain Core address, 764 // without actually performing any remote authentication. This mode is prone to 765 // Byzantine attack, so only ever use for truly private networks. 766 func authNoAuth(url string) (string, string, common.Address, error) { 767 address, err := common.HexToAddress(regexp.MustCompile("[0-9a-fA-F]{44}").FindString(url)) 768 if err != nil { 769 return "", "", common.Address{}, err 770 } 771 if address == (common.Address{}) { 772 //lint:ignore ST1005 This error is to be displayed in the browser 773 return "", "", common.Address{}, errors.New("No Core address found to fund") 774 } 775 return address.Hex() + "@noauth", "", address, nil 776 }