github.com/ethw3/go-ethereuma@v0.0.0-20221013053120-c14602a4c23c/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 an Ether faucet backed by a light client. 18 package main 19 20 import ( 21 "bytes" 22 "context" 23 _ "embed" 24 "encoding/json" 25 "errors" 26 "flag" 27 "fmt" 28 "html/template" 29 "io" 30 "math" 31 "math/big" 32 "net/http" 33 "net/url" 34 "os" 35 "path/filepath" 36 "regexp" 37 "strconv" 38 "strings" 39 "sync" 40 "time" 41 42 "github.com/ethw3/go-ethereuma/accounts" 43 "github.com/ethw3/go-ethereuma/accounts/keystore" 44 "github.com/ethw3/go-ethereuma/cmd/utils" 45 "github.com/ethw3/go-ethereuma/common" 46 "github.com/ethw3/go-ethereuma/core" 47 "github.com/ethw3/go-ethereuma/core/types" 48 "github.com/ethw3/go-ethereuma/eth/downloader" 49 "github.com/ethw3/go-ethereuma/eth/ethconfig" 50 "github.com/ethw3/go-ethereuma/ethclient" 51 "github.com/ethw3/go-ethereuma/ethstats" 52 "github.com/ethw3/go-ethereuma/les" 53 "github.com/ethw3/go-ethereuma/log" 54 "github.com/ethw3/go-ethereuma/node" 55 "github.com/ethw3/go-ethereuma/p2p" 56 "github.com/ethw3/go-ethereuma/p2p/enode" 57 "github.com/ethw3/go-ethereuma/p2p/nat" 58 "github.com/ethw3/go-ethereuma/params" 59 "github.com/gorilla/websocket" 60 ) 61 62 var ( 63 genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with") 64 apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection") 65 ethPortFlag = flag.Int("ethport", 30303, "Listener port for the devp2p connection") 66 bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with") 67 netFlag = flag.Uint64("network", 0, "Network ID to use for the Ethereum protocol") 68 statsFlag = flag.String("ethstats", "", "Ethstats network monitoring auth string") 69 70 netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet") 71 payoutFlag = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request") 72 minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds") 73 tiersFlag = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)") 74 75 accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with") 76 accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds") 77 78 captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side") 79 captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side") 80 81 noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication") 82 logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet") 83 84 twitterTokenFlag = flag.String("twitter.token", "", "Bearer token to authenticate with the v2 Twitter API") 85 twitterTokenV1Flag = flag.String("twitter.token.v1", "", "Bearer token to authenticate with the v1.1 Twitter API") 86 87 goerliFlag = flag.Bool("goerli", false, "Initializes the faucet with Görli network config") 88 rinkebyFlag = flag.Bool("rinkeby", false, "Initializes the faucet with Rinkeby network config") 89 sepoliaFlag = flag.Bool("sepolia", false, "Initializes the faucet with Sepolia network config") 90 ) 91 92 var ( 93 ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil) 94 ) 95 96 var ( 97 gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags) 98 gitDate = "" // Git commit date YYYYMMDD of the release (set via linker flags) 99 ) 100 101 //go:embed faucet.html 102 var websiteTmpl string 103 104 func main() { 105 // Parse the flags and set up the logger to print everything requested 106 flag.Parse() 107 log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true)))) 108 109 // Construct the payout tiers 110 amounts := make([]string, *tiersFlag) 111 periods := make([]string, *tiersFlag) 112 for i := 0; i < *tiersFlag; i++ { 113 // Calculate the amount for the next tier and format it 114 amount := float64(*payoutFlag) * math.Pow(2.5, float64(i)) 115 amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64)) 116 if amount == 1 { 117 amounts[i] = strings.TrimSuffix(amounts[i], "s") 118 } 119 // Calculate the period for the next tier and format it 120 period := *minutesFlag * int(math.Pow(3, float64(i))) 121 periods[i] = fmt.Sprintf("%d mins", period) 122 if period%60 == 0 { 123 period /= 60 124 periods[i] = fmt.Sprintf("%d hours", period) 125 126 if period%24 == 0 { 127 period /= 24 128 periods[i] = fmt.Sprintf("%d days", period) 129 } 130 } 131 if period == 1 { 132 periods[i] = strings.TrimSuffix(periods[i], "s") 133 } 134 } 135 website := new(bytes.Buffer) 136 err := template.Must(template.New("").Parse(websiteTmpl)).Execute(website, map[string]interface{}{ 137 "Network": *netnameFlag, 138 "Amounts": amounts, 139 "Periods": periods, 140 "Recaptcha": *captchaToken, 141 "NoAuth": *noauthFlag, 142 }) 143 if err != nil { 144 log.Crit("Failed to render the faucet template", "err", err) 145 } 146 // Load and parse the genesis block requested by the user 147 genesis, err := getGenesis(*genesisFlag, *goerliFlag, *rinkebyFlag, *sepoliaFlag) 148 if err != nil { 149 log.Crit("Failed to parse genesis config", "err", err) 150 } 151 // Convert the bootnodes to internal enode representations 152 var enodes []*enode.Node 153 for _, boot := range strings.Split(*bootFlag, ",") { 154 if url, err := enode.Parse(enode.ValidSchemes, boot); err == nil { 155 enodes = append(enodes, url) 156 } else { 157 log.Error("Failed to parse bootnode URL", "url", boot, "err", err) 158 } 159 } 160 // Load up the account key and decrypt its password 161 blob, err := os.ReadFile(*accPassFlag) 162 if 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 = os.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 []*wsConn // 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 // wsConn wraps a websocket connection with a write mutex as the underlying 221 // websocket library does not synchronize access to the stream. 222 type wsConn struct { 223 conn *websocket.Conn 224 wlock sync.Mutex 225 } 226 227 func newFaucet(genesis *core.Genesis, port int, enodes []*enode.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) { 228 // Assemble the raw devp2p protocol stack 229 stack, err := node.New(&node.Config{ 230 Name: "geth", 231 Version: params.VersionWithCommit(gitCommit, gitDate), 232 DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"), 233 P2P: p2p.Config{ 234 NAT: nat.Any(), 235 NoDiscovery: true, 236 DiscoveryV5: true, 237 ListenAddr: fmt.Sprintf(":%d", port), 238 MaxPeers: 25, 239 BootstrapNodesV5: enodes, 240 }, 241 }) 242 if err != nil { 243 return nil, err 244 } 245 246 // Assemble the Ethereum light client protocol 247 cfg := ethconfig.Defaults 248 cfg.SyncMode = downloader.LightSync 249 cfg.NetworkId = network 250 cfg.Genesis = genesis 251 utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock().Hash()) 252 253 lesBackend, err := les.New(stack, &cfg) 254 if err != nil { 255 return nil, fmt.Errorf("Failed to register the Ethereum service: %w", err) 256 } 257 258 // Assemble the ethstats monitoring and reporting service' 259 if stats != "" { 260 if err := ethstats.New(stack, lesBackend.ApiBackend, lesBackend.Engine(), stats); err != nil { 261 return nil, err 262 } 263 } 264 // Boot up the client and ensure it connects to bootnodes 265 if err := stack.Start(); err != nil { 266 return nil, err 267 } 268 for _, boot := range enodes { 269 old, err := enode.Parse(enode.ValidSchemes, boot.String()) 270 if err == nil { 271 stack.Server().AddPeer(old) 272 } 273 } 274 // Attach to the client and retrieve and interesting metadatas 275 api, err := stack.Attach() 276 if err != nil { 277 stack.Close() 278 return nil, err 279 } 280 client := ethclient.NewClient(api) 281 282 return &faucet{ 283 config: genesis.Config, 284 stack: stack, 285 client: client, 286 index: index, 287 keystore: ks, 288 account: ks.Accounts()[0], 289 timeouts: make(map[string]time.Time), 290 update: make(chan struct{}, 1), 291 }, nil 292 } 293 294 // close terminates the Ethereum connection and tears down the faucet. 295 func (f *faucet) close() error { 296 return f.stack.Close() 297 } 298 299 // listenAndServe registers the HTTP handlers for the faucet and boots it up 300 // for service user funding requests. 301 func (f *faucet) listenAndServe(port int) error { 302 go f.loop() 303 304 http.HandleFunc("/", f.webHandler) 305 http.HandleFunc("/api", f.apiHandler) 306 return http.ListenAndServe(fmt.Sprintf(":%d", port), nil) 307 } 308 309 // webHandler handles all non-api requests, simply flattening and returning the 310 // faucet website. 311 func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) { 312 w.Write(f.index) 313 } 314 315 // apiHandler handles requests for Ether grants and transaction statuses. 316 func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) { 317 upgrader := websocket.Upgrader{} 318 conn, err := upgrader.Upgrade(w, r, nil) 319 if err != nil { 320 return 321 } 322 323 // Start tracking the connection and drop at the end 324 defer conn.Close() 325 326 f.lock.Lock() 327 wsconn := &wsConn{conn: conn} 328 f.conns = append(f.conns, wsconn) 329 f.lock.Unlock() 330 331 defer func() { 332 f.lock.Lock() 333 for i, c := range f.conns { 334 if c.conn == conn { 335 f.conns = append(f.conns[:i], f.conns[i+1:]...) 336 break 337 } 338 } 339 f.lock.Unlock() 340 }() 341 // Gather the initial stats from the network to report 342 var ( 343 head *types.Header 344 balance *big.Int 345 nonce uint64 346 ) 347 for head == nil || balance == nil { 348 // Retrieve the current stats cached by the faucet 349 f.lock.RLock() 350 if f.head != nil { 351 head = types.CopyHeader(f.head) 352 } 353 if f.balance != nil { 354 balance = new(big.Int).Set(f.balance) 355 } 356 nonce = f.nonce 357 f.lock.RUnlock() 358 359 if head == nil || balance == nil { 360 // Report the faucet offline until initial stats are ready 361 //lint:ignore ST1005 This error is to be displayed in the browser 362 if err = sendError(wsconn, errors.New("Faucet offline")); err != nil { 363 log.Warn("Failed to send faucet error to client", "err", err) 364 return 365 } 366 time.Sleep(3 * time.Second) 367 } 368 } 369 // Send over the initial stats and the latest header 370 f.lock.RLock() 371 reqs := f.reqs 372 f.lock.RUnlock() 373 if err = send(wsconn, map[string]interface{}{ 374 "funds": new(big.Int).Div(balance, ether), 375 "funded": nonce, 376 "peers": f.stack.Server().PeerCount(), 377 "requests": reqs, 378 }, 3*time.Second); err != nil { 379 log.Warn("Failed to send initial stats to client", "err", err) 380 return 381 } 382 if err = send(wsconn, head, 3*time.Second); err != nil { 383 log.Warn("Failed to send initial header to client", "err", err) 384 return 385 } 386 // Keep reading requests from the websocket until the connection breaks 387 for { 388 // Fetch the next funding request and validate against github 389 var msg struct { 390 URL string `json:"url"` 391 Tier uint `json:"tier"` 392 Captcha string `json:"captcha"` 393 } 394 if err = conn.ReadJSON(&msg); err != nil { 395 return 396 } 397 if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://twitter.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") { 398 if err = sendError(wsconn, errors.New("URL doesn't link to supported services")); err != nil { 399 log.Warn("Failed to send URL error to client", "err", err) 400 return 401 } 402 continue 403 } 404 if msg.Tier >= uint(*tiersFlag) { 405 //lint:ignore ST1005 This error is to be displayed in the browser 406 if err = sendError(wsconn, errors.New("Invalid funding tier requested")); err != nil { 407 log.Warn("Failed to send tier error to client", "err", err) 408 return 409 } 410 continue 411 } 412 log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier) 413 414 // If captcha verifications are enabled, make sure we're not dealing with a robot 415 if *captchaToken != "" { 416 form := url.Values{} 417 form.Add("secret", *captchaSecret) 418 form.Add("response", msg.Captcha) 419 420 res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form) 421 if err != nil { 422 if err = sendError(wsconn, err); err != nil { 423 log.Warn("Failed to send captcha post error to client", "err", err) 424 return 425 } 426 continue 427 } 428 var result struct { 429 Success bool `json:"success"` 430 Errors json.RawMessage `json:"error-codes"` 431 } 432 err = json.NewDecoder(res.Body).Decode(&result) 433 res.Body.Close() 434 if err != nil { 435 if err = sendError(wsconn, err); err != nil { 436 log.Warn("Failed to send captcha decode error to client", "err", err) 437 return 438 } 439 continue 440 } 441 if !result.Success { 442 log.Warn("Captcha verification failed", "err", string(result.Errors)) 443 //lint:ignore ST1005 it's funny and the robot won't mind 444 if err = sendError(wsconn, errors.New("Beep-bop, you're a robot!")); err != nil { 445 log.Warn("Failed to send captcha failure to client", "err", err) 446 return 447 } 448 continue 449 } 450 } 451 // Retrieve the Ethereum address to fund, the requesting user and a profile picture 452 var ( 453 id string 454 username string 455 avatar string 456 address common.Address 457 ) 458 switch { 459 case strings.HasPrefix(msg.URL, "https://twitter.com/"): 460 id, username, avatar, address, err = authTwitter(msg.URL, *twitterTokenV1Flag, *twitterTokenFlag) 461 case strings.HasPrefix(msg.URL, "https://www.facebook.com/"): 462 username, avatar, address, err = authFacebook(msg.URL) 463 id = username 464 case *noauthFlag: 465 username, avatar, address, err = authNoAuth(msg.URL) 466 id = username 467 default: 468 //lint:ignore ST1005 This error is to be displayed in the browser 469 err = errors.New("Something funky happened, please open an issue at https://github.com/ethw3/go-ethereuma/issues") 470 } 471 if err != nil { 472 if err = sendError(wsconn, err); err != nil { 473 log.Warn("Failed to send prefix error to client", "err", err) 474 return 475 } 476 continue 477 } 478 log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address) 479 480 // Ensure the user didn't request funds too recently 481 f.lock.Lock() 482 var ( 483 fund bool 484 timeout time.Time 485 ) 486 if timeout = f.timeouts[id]; time.Now().After(timeout) { 487 // User wasn't funded recently, create the funding transaction 488 amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether) 489 amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil)) 490 amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil)) 491 492 tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil) 493 signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID) 494 if err != nil { 495 f.lock.Unlock() 496 if err = sendError(wsconn, err); err != nil { 497 log.Warn("Failed to send transaction creation error to client", "err", err) 498 return 499 } 500 continue 501 } 502 // Submit the transaction and mark as funded if successful 503 if err := f.client.SendTransaction(context.Background(), signed); err != nil { 504 f.lock.Unlock() 505 if err = sendError(wsconn, err); err != nil { 506 log.Warn("Failed to send transaction transmission error to client", "err", err) 507 return 508 } 509 continue 510 } 511 f.reqs = append(f.reqs, &request{ 512 Avatar: avatar, 513 Account: address, 514 Time: time.Now(), 515 Tx: signed, 516 }) 517 timeout := time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute 518 grace := timeout / 288 // 24h timeout => 5m grace 519 520 f.timeouts[id] = time.Now().Add(timeout - grace) 521 fund = true 522 } 523 f.lock.Unlock() 524 525 // Send an error if too frequent funding, othewise a success 526 if !fund { 527 if err = sendError(wsconn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(time.Until(timeout)))); err != nil { // nolint: gosimple 528 log.Warn("Failed to send funding error to client", "err", err) 529 return 530 } 531 continue 532 } 533 if err = sendSuccess(wsconn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil { 534 log.Warn("Failed to send funding success to client", "err", err) 535 return 536 } 537 select { 538 case f.update <- struct{}{}: 539 default: 540 } 541 } 542 } 543 544 // refresh attempts to retrieve the latest header from the chain and extract the 545 // associated faucet balance and nonce for connectivity caching. 546 func (f *faucet) refresh(head *types.Header) error { 547 // Ensure a state update does not run for too long 548 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 549 defer cancel() 550 551 // If no header was specified, use the current chain head 552 var err error 553 if head == nil { 554 if head, err = f.client.HeaderByNumber(ctx, nil); err != nil { 555 return err 556 } 557 } 558 // Retrieve the balance, nonce and gas price from the current head 559 var ( 560 balance *big.Int 561 nonce uint64 562 price *big.Int 563 ) 564 if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil { 565 return err 566 } 567 if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil { 568 return err 569 } 570 if price, err = f.client.SuggestGasPrice(ctx); err != nil { 571 return err 572 } 573 // Everything succeeded, update the cached stats and eject old requests 574 f.lock.Lock() 575 f.head, f.balance = head, balance 576 f.price, f.nonce = price, nonce 577 for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce { 578 f.reqs = f.reqs[1:] 579 } 580 f.lock.Unlock() 581 582 return nil 583 } 584 585 // loop keeps waiting for interesting events and pushes them out to connected 586 // websockets. 587 func (f *faucet) loop() { 588 // Wait for chain events and push them to clients 589 heads := make(chan *types.Header, 16) 590 sub, err := f.client.SubscribeNewHead(context.Background(), heads) 591 if err != nil { 592 log.Crit("Failed to subscribe to head events", "err", err) 593 } 594 defer sub.Unsubscribe() 595 596 // Start a goroutine to update the state from head notifications in the background 597 update := make(chan *types.Header) 598 599 go func() { 600 for head := range update { 601 // New chain head arrived, query the current stats and stream to clients 602 timestamp := time.Unix(int64(head.Time), 0) 603 if time.Since(timestamp) > time.Hour { 604 log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp)) 605 continue 606 } 607 if err := f.refresh(head); err != nil { 608 log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err) 609 continue 610 } 611 // Faucet state retrieved, update locally and send to clients 612 f.lock.RLock() 613 log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price) 614 615 balance := new(big.Int).Div(f.balance, ether) 616 peers := f.stack.Server().PeerCount() 617 618 for _, conn := range f.conns { 619 if err := send(conn, map[string]interface{}{ 620 "funds": balance, 621 "funded": f.nonce, 622 "peers": peers, 623 "requests": f.reqs, 624 }, time.Second); err != nil { 625 log.Warn("Failed to send stats to client", "err", err) 626 conn.conn.Close() 627 continue 628 } 629 if err := send(conn, head, time.Second); err != nil { 630 log.Warn("Failed to send header to client", "err", err) 631 conn.conn.Close() 632 } 633 } 634 f.lock.RUnlock() 635 } 636 }() 637 // Wait for various events and assing to the appropriate background threads 638 for { 639 select { 640 case head := <-heads: 641 // New head arrived, send if for state update if there's none running 642 select { 643 case update <- head: 644 default: 645 } 646 647 case <-f.update: 648 // Pending requests updated, stream to clients 649 f.lock.RLock() 650 for _, conn := range f.conns { 651 if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil { 652 log.Warn("Failed to send requests to client", "err", err) 653 conn.conn.Close() 654 } 655 } 656 f.lock.RUnlock() 657 } 658 } 659 } 660 661 // sends transmits a data packet to the remote end of the websocket, but also 662 // setting a write deadline to prevent waiting forever on the node. 663 func send(conn *wsConn, value interface{}, timeout time.Duration) error { 664 if timeout == 0 { 665 timeout = 60 * time.Second 666 } 667 conn.wlock.Lock() 668 defer conn.wlock.Unlock() 669 conn.conn.SetWriteDeadline(time.Now().Add(timeout)) 670 return conn.conn.WriteJSON(value) 671 } 672 673 // sendError transmits an error to the remote end of the websocket, also setting 674 // the write deadline to 1 second to prevent waiting forever. 675 func sendError(conn *wsConn, err error) error { 676 return send(conn, map[string]string{"error": err.Error()}, time.Second) 677 } 678 679 // sendSuccess transmits a success message to the remote end of the websocket, also 680 // setting the write deadline to 1 second to prevent waiting forever. 681 func sendSuccess(conn *wsConn, msg string) error { 682 return send(conn, map[string]string{"success": msg}, time.Second) 683 } 684 685 // authTwitter tries to authenticate a faucet request using Twitter posts, returning 686 // the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success. 687 func authTwitter(url string, tokenV1, tokenV2 string) (string, string, string, common.Address, error) { 688 // Ensure the user specified a meaningful URL, no fancy nonsense 689 parts := strings.Split(url, "/") 690 if len(parts) < 4 || parts[len(parts)-2] != "status" { 691 //lint:ignore ST1005 This error is to be displayed in the browser 692 return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL") 693 } 694 // Strip any query parameters from the tweet id and ensure it's numeric 695 tweetID := strings.Split(parts[len(parts)-1], "?")[0] 696 if !regexp.MustCompile("^[0-9]+$").MatchString(tweetID) { 697 return "", "", "", common.Address{}, errors.New("Invalid Tweet URL") 698 } 699 // Twitter's API isn't really friendly with direct links. 700 // It is restricted to 300 queries / 15 minute with an app api key. 701 // Anything more will require read only authorization from the users and that we want to avoid. 702 703 // If Twitter bearer token is provided, use the API, selecting the version 704 // the user would prefer (currently there's a limit of 1 v2 app / developer 705 // but unlimited v1.1 apps). 706 switch { 707 case tokenV1 != "": 708 return authTwitterWithTokenV1(tweetID, tokenV1) 709 case tokenV2 != "": 710 return authTwitterWithTokenV2(tweetID, tokenV2) 711 } 712 // Twitter API token isn't provided so we just load the public posts 713 // and scrape it for the Ethereum address and profile URL. We need to load 714 // the mobile page though since the main page loads tweet contents via JS. 715 url = strings.Replace(url, "https://twitter.com/", "https://mobile.twitter.com/", 1) 716 717 res, err := http.Get(url) 718 if err != nil { 719 return "", "", "", common.Address{}, err 720 } 721 defer res.Body.Close() 722 723 // Resolve the username from the final redirect, no intermediate junk 724 parts = strings.Split(res.Request.URL.String(), "/") 725 if len(parts) < 4 || parts[len(parts)-2] != "status" { 726 //lint:ignore ST1005 This error is to be displayed in the browser 727 return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL") 728 } 729 username := parts[len(parts)-3] 730 731 body, err := io.ReadAll(res.Body) 732 if err != nil { 733 return "", "", "", common.Address{}, err 734 } 735 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 736 if address == (common.Address{}) { 737 //lint:ignore ST1005 This error is to be displayed in the browser 738 return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund") 739 } 740 var avatar string 741 if parts = regexp.MustCompile(`src="([^"]+twimg\.com/profile_images[^"]+)"`).FindStringSubmatch(string(body)); len(parts) == 2 { 742 avatar = parts[1] 743 } 744 return username + "@twitter", username, avatar, address, nil 745 } 746 747 // authTwitterWithTokenV1 tries to authenticate a faucet request using Twitter's v1 748 // API, returning the user id, username, avatar URL and Ethereum address to fund on 749 // success. 750 func authTwitterWithTokenV1(tweetID string, token string) (string, string, string, common.Address, error) { 751 // Query the tweet details from Twitter 752 url := fmt.Sprintf("https://api.twitter.com/1.1/statuses/show.json?id=%s", tweetID) 753 req, err := http.NewRequest("GET", url, nil) 754 if err != nil { 755 return "", "", "", common.Address{}, err 756 } 757 req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) 758 res, err := http.DefaultClient.Do(req) 759 if err != nil { 760 return "", "", "", common.Address{}, err 761 } 762 defer res.Body.Close() 763 764 var result struct { 765 Text string `json:"text"` 766 User struct { 767 ID string `json:"id_str"` 768 Username string `json:"screen_name"` 769 Avatar string `json:"profile_image_url"` 770 } `json:"user"` 771 } 772 err = json.NewDecoder(res.Body).Decode(&result) 773 if err != nil { 774 return "", "", "", common.Address{}, err 775 } 776 address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Text)) 777 if address == (common.Address{}) { 778 //lint:ignore ST1005 This error is to be displayed in the browser 779 return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund") 780 } 781 return result.User.ID + "@twitter", result.User.Username, result.User.Avatar, address, nil 782 } 783 784 // authTwitterWithTokenV2 tries to authenticate a faucet request using Twitter's v2 785 // API, returning the user id, username, avatar URL and Ethereum address to fund on 786 // success. 787 func authTwitterWithTokenV2(tweetID string, token string) (string, string, string, common.Address, error) { 788 // Query the tweet details from Twitter 789 url := fmt.Sprintf("https://api.twitter.com/2/tweets/%s?expansions=author_id&user.fields=profile_image_url", tweetID) 790 req, err := http.NewRequest("GET", url, nil) 791 if err != nil { 792 return "", "", "", common.Address{}, err 793 } 794 req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) 795 res, err := http.DefaultClient.Do(req) 796 if err != nil { 797 return "", "", "", common.Address{}, err 798 } 799 defer res.Body.Close() 800 801 var result struct { 802 Data struct { 803 AuthorID string `json:"author_id"` 804 Text string `json:"text"` 805 } `json:"data"` 806 Includes struct { 807 Users []struct { 808 ID string `json:"id"` 809 Username string `json:"username"` 810 Avatar string `json:"profile_image_url"` 811 } `json:"users"` 812 } `json:"includes"` 813 } 814 815 err = json.NewDecoder(res.Body).Decode(&result) 816 if err != nil { 817 return "", "", "", common.Address{}, err 818 } 819 820 address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Data.Text)) 821 if address == (common.Address{}) { 822 //lint:ignore ST1005 This error is to be displayed in the browser 823 return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund") 824 } 825 return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].Avatar, address, nil 826 } 827 828 // authFacebook tries to authenticate a faucet request using Facebook posts, 829 // returning the username, avatar URL and Ethereum address to fund on success. 830 func authFacebook(url string) (string, string, common.Address, error) { 831 // Ensure the user specified a meaningful URL, no fancy nonsense 832 parts := strings.Split(strings.Split(url, "?")[0], "/") 833 if parts[len(parts)-1] == "" { 834 parts = parts[0 : len(parts)-1] 835 } 836 if len(parts) < 4 || parts[len(parts)-2] != "posts" { 837 //lint:ignore ST1005 This error is to be displayed in the browser 838 return "", "", common.Address{}, errors.New("Invalid Facebook post URL") 839 } 840 username := parts[len(parts)-3] 841 842 // Facebook's Graph API isn't really friendly with direct links. Still, we don't 843 // want to do ask read permissions from users, so just load the public posts and 844 // scrape it for the Ethereum address and profile URL. 845 // 846 // Facebook recently changed their desktop webpage to use AJAX for loading post 847 // content, so switch over to the mobile site for now. Will probably end up having 848 // to use the API eventually. 849 crawl := strings.Replace(url, "www.facebook.com", "m.facebook.com", 1) 850 851 res, err := http.Get(crawl) 852 if err != nil { 853 return "", "", common.Address{}, err 854 } 855 defer res.Body.Close() 856 857 body, err := io.ReadAll(res.Body) 858 if err != nil { 859 return "", "", common.Address{}, err 860 } 861 address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body))) 862 if address == (common.Address{}) { 863 //lint:ignore ST1005 This error is to be displayed in the browser 864 return "", "", common.Address{}, errors.New("No Ethereum address found to fund. Please check the post URL and verify that it can be viewed publicly.") 865 } 866 var avatar string 867 if parts = regexp.MustCompile(`src="([^"]+fbcdn\.net[^"]+)"`).FindStringSubmatch(string(body)); len(parts) == 2 { 868 avatar = parts[1] 869 } 870 return username + "@facebook", avatar, address, nil 871 } 872 873 // authNoAuth tries to interpret a faucet request as a plain Ethereum address, 874 // without actually performing any remote authentication. This mode is prone to 875 // Byzantine attack, so only ever use for truly private networks. 876 func authNoAuth(url string) (string, string, common.Address, error) { 877 address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url)) 878 if address == (common.Address{}) { 879 //lint:ignore ST1005 This error is to be displayed in the browser 880 return "", "", common.Address{}, errors.New("No Ethereum address found to fund") 881 } 882 return address.Hex() + "@noauth", "", address, nil 883 } 884 885 // getGenesis returns a genesis based on input args 886 func getGenesis(genesisFlag string, goerliFlag bool, rinkebyFlag bool, sepoliaFlag bool) (*core.Genesis, error) { 887 switch { 888 case genesisFlag != "": 889 var genesis core.Genesis 890 err := common.LoadJSON(genesisFlag, &genesis) 891 return &genesis, err 892 case goerliFlag: 893 return core.DefaultGoerliGenesisBlock(), nil 894 case rinkebyFlag: 895 return core.DefaultRinkebyGenesisBlock(), nil 896 case sepoliaFlag: 897 return core.DefaultSepoliaGenesisBlock(), nil 898 default: 899 return nil, fmt.Errorf("no genesis flag provided") 900 } 901 }