github.com/shrimpyuk/bor@v0.2.15-0.20220224151350-fb4ec6020bae/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  //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"
    45  	"github.com/ethereum/go-ethereum/accounts/keystore"
    46  	"github.com/ethereum/go-ethereum/cmd/utils"
    47  	"github.com/ethereum/go-ethereum/common"
    48  	"github.com/ethereum/go-ethereum/core"
    49  	"github.com/ethereum/go-ethereum/core/types"
    50  	"github.com/ethereum/go-ethereum/eth/downloader"
    51  	"github.com/ethereum/go-ethereum/eth/ethconfig"
    52  	"github.com/ethereum/go-ethereum/ethclient"
    53  	"github.com/ethereum/go-ethereum/ethstats"
    54  	"github.com/ethereum/go-ethereum/les"
    55  	"github.com/ethereum/go-ethereum/log"
    56  	"github.com/ethereum/go-ethereum/node"
    57  	"github.com/ethereum/go-ethereum/p2p"
    58  	"github.com/ethereum/go-ethereum/p2p/enode"
    59  	"github.com/ethereum/go-ethereum/p2p/nat"
    60  	"github.com/ethereum/go-ethereum/params"
    61  	"github.com/gorilla/websocket"
    62  )
    63  
    64  var (
    65  	genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with")
    66  	apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection")
    67  	ethPortFlag = flag.Int("ethport", 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  	twitterTokenFlag   = flag.String("twitter.token", "", "Bearer token to authenticate with the v2 Twitter API")
    87  	twitterTokenV1Flag = flag.String("twitter.token.v1", "", "Bearer token to authenticate with the v1.1 Twitter API")
    88  
    89  	goerliFlag  = flag.Bool("goerli", false, "Initializes the faucet with Görli network config")
    90  	rinkebyFlag = flag.Bool("rinkeby", false, "Initializes the faucet with Rinkeby network config")
    91  	mumbaiFlag  = flag.Bool("bor-mumbai", false, "Initializes the faucet with Bor-Mumbai network config")
    92  )
    93  
    94  var (
    95  	ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
    96  )
    97  
    98  var (
    99  	gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
   100  	gitDate   = "" // Git commit date YYYYMMDD of the release (set via linker flags)
   101  )
   102  
   103  func main() {
   104  	// Parse the flags and set up the logger to print everything requested
   105  	flag.Parse()
   106  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
   107  
   108  	// Construct the payout tiers
   109  	amounts := make([]string, *tiersFlag)
   110  	periods := make([]string, *tiersFlag)
   111  	for i := 0; i < *tiersFlag; i++ {
   112  		// Calculate the amount for the next tier and format it
   113  		amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
   114  		amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
   115  		if amount == 1 {
   116  			amounts[i] = strings.TrimSuffix(amounts[i], "s")
   117  		}
   118  		// Calculate the period for the next tier and format it
   119  		period := *minutesFlag * int(math.Pow(3, float64(i)))
   120  		periods[i] = fmt.Sprintf("%d mins", period)
   121  		if period%60 == 0 {
   122  			period /= 60
   123  			periods[i] = fmt.Sprintf("%d hours", period)
   124  
   125  			if period%24 == 0 {
   126  				period /= 24
   127  				periods[i] = fmt.Sprintf("%d days", period)
   128  			}
   129  		}
   130  		if period == 1 {
   131  			periods[i] = strings.TrimSuffix(periods[i], "s")
   132  		}
   133  	}
   134  	// Load up and render the faucet website
   135  	tmpl, err := Asset("faucet.html")
   136  	if err != nil {
   137  		log.Crit("Failed to load the faucet template", "err", err)
   138  	}
   139  	website := new(bytes.Buffer)
   140  	err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
   141  		"Network":   *netnameFlag,
   142  		"Amounts":   amounts,
   143  		"Periods":   periods,
   144  		"Recaptcha": *captchaToken,
   145  		"NoAuth":    *noauthFlag,
   146  	})
   147  	if err != nil {
   148  		log.Crit("Failed to render the faucet template", "err", err)
   149  	}
   150  	// Load and parse the genesis block requested by the user
   151  	genesis, err := getGenesis(genesisFlag, *goerliFlag, *rinkebyFlag, *mumbaiFlag)
   152  	if err != nil {
   153  		log.Crit("Failed to parse genesis config", "err", err)
   154  	}
   155  	// Convert the bootnodes to internal enode representations
   156  	var enodes []*enode.Node
   157  	for _, boot := range strings.Split(*bootFlag, ",") {
   158  		if url, err := enode.Parse(enode.ValidSchemes, boot); err == nil {
   159  			enodes = append(enodes, url)
   160  		} else {
   161  			log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
   162  		}
   163  	}
   164  	// Load up the account key and decrypt its password
   165  	blob, err := ioutil.ReadFile(*accPassFlag)
   166  	if err != nil {
   167  		log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
   168  	}
   169  	pass := strings.TrimSuffix(string(blob), "\n")
   170  
   171  	ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
   172  	if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
   173  		log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
   174  	}
   175  	acc, err := ks.Import(blob, pass, pass)
   176  	if err != nil && err != keystore.ErrAccountAlreadyExists {
   177  		log.Crit("Failed to import faucet signer account", "err", err)
   178  	}
   179  	if err := ks.Unlock(acc, pass); err != nil {
   180  		log.Crit("Failed to unlock faucet signer account", "err", err)
   181  	}
   182  	// Assemble and start the faucet light service
   183  	faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
   184  	if err != nil {
   185  		log.Crit("Failed to start faucet", "err", err)
   186  	}
   187  	defer faucet.close()
   188  
   189  	if err := faucet.listenAndServe(*apiPortFlag); err != nil {
   190  		log.Crit("Failed to launch faucet API", "err", err)
   191  	}
   192  }
   193  
   194  // request represents an accepted funding request.
   195  type request struct {
   196  	Avatar  string             `json:"avatar"`  // Avatar URL to make the UI nicer
   197  	Account common.Address     `json:"account"` // Ethereum address being funded
   198  	Time    time.Time          `json:"time"`    // Timestamp when the request was accepted
   199  	Tx      *types.Transaction `json:"tx"`      // Transaction funding the account
   200  }
   201  
   202  // faucet represents a crypto faucet backed by an Ethereum light client.
   203  type faucet struct {
   204  	config *params.ChainConfig // Chain configurations for signing
   205  	stack  *node.Node          // Ethereum protocol stack
   206  	client *ethclient.Client   // Client connection to the Ethereum chain
   207  	index  []byte              // Index page to serve up on the web
   208  
   209  	keystore *keystore.KeyStore // Keystore containing the single signer
   210  	account  accounts.Account   // Account funding user faucet requests
   211  	head     *types.Header      // Current head header of the faucet
   212  	balance  *big.Int           // Current balance of the faucet
   213  	nonce    uint64             // Current pending nonce of the faucet
   214  	price    *big.Int           // Current gas price to issue funds with
   215  
   216  	conns    []*wsConn            // Currently live websocket connections
   217  	timeouts map[string]time.Time // History of users and their funding timeouts
   218  	reqs     []*request           // Currently pending funding requests
   219  	update   chan struct{}        // Channel to signal request updates
   220  
   221  	lock sync.RWMutex // Lock protecting the faucet's internals
   222  }
   223  
   224  // wsConn wraps a websocket connection with a write mutex as the underlying
   225  // websocket library does not synchronize access to the stream.
   226  type wsConn struct {
   227  	conn  *websocket.Conn
   228  	wlock sync.Mutex
   229  }
   230  
   231  func newFaucet(genesis *core.Genesis, port int, enodes []*enode.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
   232  	// Assemble the raw devp2p protocol stack
   233  	stack, err := node.New(&node.Config{
   234  		Name:    "geth",
   235  		Version: params.VersionWithCommit(gitCommit, gitDate),
   236  		DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
   237  		P2P: p2p.Config{
   238  			NAT:              nat.Any(),
   239  			NoDiscovery:      true,
   240  			DiscoveryV5:      true,
   241  			ListenAddr:       fmt.Sprintf(":%d", port),
   242  			MaxPeers:         25,
   243  			BootstrapNodesV5: enodes,
   244  		},
   245  	})
   246  	if err != nil {
   247  		return nil, err
   248  	}
   249  
   250  	// Assemble the Ethereum light client protocol
   251  	cfg := ethconfig.Defaults
   252  	cfg.SyncMode = downloader.LightSync
   253  	cfg.NetworkId = network
   254  	cfg.Genesis = genesis
   255  	utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock(nil).Hash())
   256  
   257  	lesBackend, err := les.New(stack, &cfg)
   258  	if err != nil {
   259  		return nil, fmt.Errorf("Failed to register the Ethereum service: %w", err)
   260  	}
   261  
   262  	// Assemble the ethstats monitoring and reporting service'
   263  	if stats != "" {
   264  		if err := ethstats.New(stack, lesBackend.ApiBackend, lesBackend.Engine(), stats); err != nil {
   265  			return nil, err
   266  		}
   267  	}
   268  	// Boot up the client and ensure it connects to bootnodes
   269  	if err := stack.Start(); err != nil {
   270  		return nil, err
   271  	}
   272  	for _, boot := range enodes {
   273  		old, err := enode.Parse(enode.ValidSchemes, boot.String())
   274  		if err == nil {
   275  			stack.Server().AddPeer(old)
   276  		}
   277  	}
   278  	// Attach to the client and retrieve and interesting metadatas
   279  	api, err := stack.Attach()
   280  	if err != nil {
   281  		stack.Close()
   282  		return nil, err
   283  	}
   284  	client := ethclient.NewClient(api)
   285  
   286  	return &faucet{
   287  		config:   genesis.Config,
   288  		stack:    stack,
   289  		client:   client,
   290  		index:    index,
   291  		keystore: ks,
   292  		account:  ks.Accounts()[0],
   293  		timeouts: make(map[string]time.Time),
   294  		update:   make(chan struct{}, 1),
   295  	}, nil
   296  }
   297  
   298  // close terminates the Ethereum connection and tears down the faucet.
   299  func (f *faucet) close() error {
   300  	return f.stack.Close()
   301  }
   302  
   303  // listenAndServe registers the HTTP handlers for the faucet and boots it up
   304  // for service user funding requests.
   305  func (f *faucet) listenAndServe(port int) error {
   306  	go f.loop()
   307  
   308  	http.HandleFunc("/", f.webHandler)
   309  	http.HandleFunc("/api", f.apiHandler)
   310  	return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
   311  }
   312  
   313  // webHandler handles all non-api requests, simply flattening and returning the
   314  // faucet website.
   315  func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
   316  	w.Write(f.index)
   317  }
   318  
   319  // apiHandler handles requests for Ether grants and transaction statuses.
   320  func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
   321  	upgrader := websocket.Upgrader{}
   322  	conn, err := upgrader.Upgrade(w, r, nil)
   323  	if err != nil {
   324  		return
   325  	}
   326  
   327  	// Start tracking the connection and drop at the end
   328  	defer conn.Close()
   329  
   330  	f.lock.Lock()
   331  	wsconn := &wsConn{conn: conn}
   332  	f.conns = append(f.conns, wsconn)
   333  	f.lock.Unlock()
   334  
   335  	defer func() {
   336  		f.lock.Lock()
   337  		for i, c := range f.conns {
   338  			if c.conn == conn {
   339  				f.conns = append(f.conns[:i], f.conns[i+1:]...)
   340  				break
   341  			}
   342  		}
   343  		f.lock.Unlock()
   344  	}()
   345  	// Gather the initial stats from the network to report
   346  	var (
   347  		head    *types.Header
   348  		balance *big.Int
   349  		nonce   uint64
   350  	)
   351  	for head == nil || balance == nil {
   352  		// Retrieve the current stats cached by the faucet
   353  		f.lock.RLock()
   354  		if f.head != nil {
   355  			head = types.CopyHeader(f.head)
   356  		}
   357  		if f.balance != nil {
   358  			balance = new(big.Int).Set(f.balance)
   359  		}
   360  		nonce = f.nonce
   361  		f.lock.RUnlock()
   362  
   363  		if head == nil || balance == nil {
   364  			// Report the faucet offline until initial stats are ready
   365  			//lint:ignore ST1005 This error is to be displayed in the browser
   366  			if err = sendError(wsconn, errors.New("Faucet offline")); err != nil {
   367  				log.Warn("Failed to send faucet error to client", "err", err)
   368  				return
   369  			}
   370  			time.Sleep(3 * time.Second)
   371  		}
   372  	}
   373  	// Send over the initial stats and the latest header
   374  	f.lock.RLock()
   375  	reqs := f.reqs
   376  	f.lock.RUnlock()
   377  	if err = send(wsconn, map[string]interface{}{
   378  		"funds":    new(big.Int).Div(balance, ether),
   379  		"funded":   nonce,
   380  		"peers":    f.stack.Server().PeerCount(),
   381  		"requests": reqs,
   382  	}, 3*time.Second); err != nil {
   383  		log.Warn("Failed to send initial stats to client", "err", err)
   384  		return
   385  	}
   386  	if err = send(wsconn, head, 3*time.Second); err != nil {
   387  		log.Warn("Failed to send initial header to client", "err", err)
   388  		return
   389  	}
   390  	// Keep reading requests from the websocket until the connection breaks
   391  	for {
   392  		// Fetch the next funding request and validate against github
   393  		var msg struct {
   394  			URL     string `json:"url"`
   395  			Tier    uint   `json:"tier"`
   396  			Captcha string `json:"captcha"`
   397  		}
   398  		if err = conn.ReadJSON(&msg); err != nil {
   399  			return
   400  		}
   401  		if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://twitter.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
   402  			if err = sendError(wsconn, errors.New("URL doesn't link to supported services")); err != nil {
   403  				log.Warn("Failed to send URL error to client", "err", err)
   404  				return
   405  			}
   406  			continue
   407  		}
   408  		if msg.Tier >= uint(*tiersFlag) {
   409  			//lint:ignore ST1005 This error is to be displayed in the browser
   410  			if err = sendError(wsconn, errors.New("Invalid funding tier requested")); err != nil {
   411  				log.Warn("Failed to send tier error to client", "err", err)
   412  				return
   413  			}
   414  			continue
   415  		}
   416  		log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier)
   417  
   418  		// If captcha verifications are enabled, make sure we're not dealing with a robot
   419  		if *captchaToken != "" {
   420  			form := url.Values{}
   421  			form.Add("secret", *captchaSecret)
   422  			form.Add("response", msg.Captcha)
   423  
   424  			res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
   425  			if err != nil {
   426  				if err = sendError(wsconn, err); err != nil {
   427  					log.Warn("Failed to send captcha post error to client", "err", err)
   428  					return
   429  				}
   430  				continue
   431  			}
   432  			var result struct {
   433  				Success bool            `json:"success"`
   434  				Errors  json.RawMessage `json:"error-codes"`
   435  			}
   436  			err = json.NewDecoder(res.Body).Decode(&result)
   437  			res.Body.Close()
   438  			if err != nil {
   439  				if err = sendError(wsconn, err); err != nil {
   440  					log.Warn("Failed to send captcha decode error to client", "err", err)
   441  					return
   442  				}
   443  				continue
   444  			}
   445  			if !result.Success {
   446  				log.Warn("Captcha verification failed", "err", string(result.Errors))
   447  				//lint:ignore ST1005 it's funny and the robot won't mind
   448  				if err = sendError(wsconn, errors.New("Beep-bop, you're a robot!")); err != nil {
   449  					log.Warn("Failed to send captcha failure to client", "err", err)
   450  					return
   451  				}
   452  				continue
   453  			}
   454  		}
   455  		// Retrieve the Ethereum address to fund, the requesting user and a profile picture
   456  		var (
   457  			id       string
   458  			username string
   459  			avatar   string
   460  			address  common.Address
   461  		)
   462  		switch {
   463  		case strings.HasPrefix(msg.URL, "https://twitter.com/"):
   464  			id, username, avatar, address, err = authTwitter(msg.URL, *twitterTokenV1Flag, *twitterTokenFlag)
   465  		case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
   466  			username, avatar, address, err = authFacebook(msg.URL)
   467  			id = username
   468  		case *noauthFlag:
   469  			username, avatar, address, err = authNoAuth(msg.URL)
   470  			id = username
   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/ethereum/go-ethereum/issues")
   474  		}
   475  		if err != nil {
   476  			if err = sendError(wsconn, 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[id]; 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(wsconn, 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(wsconn, 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[id] = 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(wsconn, 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(wsconn, 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.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.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.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 *wsConn, value interface{}, timeout time.Duration) error {
   668  	if timeout == 0 {
   669  		timeout = 60 * time.Second
   670  	}
   671  	conn.wlock.Lock()
   672  	defer conn.wlock.Unlock()
   673  	conn.conn.SetWriteDeadline(time.Now().Add(timeout))
   674  	return conn.conn.WriteJSON(value)
   675  }
   676  
   677  // sendError transmits an error to the remote end of the websocket, also setting
   678  // the write deadline to 1 second to prevent waiting forever.
   679  func sendError(conn *wsConn, err error) error {
   680  	return send(conn, map[string]string{"error": err.Error()}, time.Second)
   681  }
   682  
   683  // sendSuccess transmits a success message to the remote end of the websocket, also
   684  // setting the write deadline to 1 second to prevent waiting forever.
   685  func sendSuccess(conn *wsConn, msg string) error {
   686  	return send(conn, map[string]string{"success": msg}, time.Second)
   687  }
   688  
   689  // authTwitter tries to authenticate a faucet request using Twitter posts, returning
   690  // the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success.
   691  func authTwitter(url string, tokenV1, tokenV2 string) (string, string, string, common.Address, error) {
   692  	// Ensure the user specified a meaningful URL, no fancy nonsense
   693  	parts := strings.Split(url, "/")
   694  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   695  		//lint:ignore ST1005 This error is to be displayed in the browser
   696  		return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   697  	}
   698  	// Strip any query parameters from the tweet id and ensure it's numeric
   699  	tweetID := strings.Split(parts[len(parts)-1], "?")[0]
   700  	if !regexp.MustCompile("^[0-9]+$").MatchString(tweetID) {
   701  		return "", "", "", common.Address{}, errors.New("Invalid Tweet URL")
   702  	}
   703  	// Twitter's API isn't really friendly with direct links.
   704  	// It is restricted to 300 queries / 15 minute with an app api key.
   705  	// Anything more will require read only authorization from the users and that we want to avoid.
   706  
   707  	// If Twitter bearer token is provided, use the API, selecting the version
   708  	// the user would prefer (currently there's a limit of 1 v2 app / developer
   709  	// but unlimited v1.1 apps).
   710  	switch {
   711  	case tokenV1 != "":
   712  		return authTwitterWithTokenV1(tweetID, tokenV1)
   713  	case tokenV2 != "":
   714  		return authTwitterWithTokenV2(tweetID, tokenV2)
   715  	}
   716  	// Twiter API token isn't provided so we just load the public posts
   717  	// and scrape it for the Ethereum address and profile URL. We need to load
   718  	// the mobile page though since the main page loads tweet contents via JS.
   719  	url = strings.Replace(url, "https://twitter.com/", "https://mobile.twitter.com/", 1)
   720  
   721  	res, err := http.Get(url)
   722  	if err != nil {
   723  		return "", "", "", common.Address{}, err
   724  	}
   725  	defer res.Body.Close()
   726  
   727  	// Resolve the username from the final redirect, no intermediate junk
   728  	parts = strings.Split(res.Request.URL.String(), "/")
   729  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   730  		//lint:ignore ST1005 This error is to be displayed in the browser
   731  		return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   732  	}
   733  	username := parts[len(parts)-3]
   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  		//lint:ignore ST1005 This error is to be displayed in the browser
   742  		return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   743  	}
   744  	var avatar string
   745  	if parts = regexp.MustCompile(`src="([^"]+twimg\.com/profile_images[^"]+)"`).FindStringSubmatch(string(body)); len(parts) == 2 {
   746  		avatar = parts[1]
   747  	}
   748  	return username + "@twitter", username, avatar, address, nil
   749  }
   750  
   751  // authTwitterWithTokenV1 tries to authenticate a faucet request using Twitter's v1
   752  // API, returning the user id, username, avatar URL and Ethereum address to fund on
   753  // success.
   754  func authTwitterWithTokenV1(tweetID string, token string) (string, string, string, common.Address, error) {
   755  	// Query the tweet details from Twitter
   756  	url := fmt.Sprintf("https://api.twitter.com/1.1/statuses/show.json?id=%s", tweetID)
   757  	req, err := http.NewRequest("GET", url, nil)
   758  	if err != nil {
   759  		return "", "", "", common.Address{}, err
   760  	}
   761  	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
   762  	res, err := http.DefaultClient.Do(req)
   763  	if err != nil {
   764  		return "", "", "", common.Address{}, err
   765  	}
   766  	defer res.Body.Close()
   767  
   768  	var result struct {
   769  		Text string `json:"text"`
   770  		User struct {
   771  			ID       string `json:"id_str"`
   772  			Username string `json:"screen_name"`
   773  			Avatar   string `json:"profile_image_url"`
   774  		} `json:"user"`
   775  	}
   776  	err = json.NewDecoder(res.Body).Decode(&result)
   777  	if err != nil {
   778  		return "", "", "", common.Address{}, err
   779  	}
   780  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Text))
   781  	if address == (common.Address{}) {
   782  		//lint:ignore ST1005 This error is to be displayed in the browser
   783  		return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   784  	}
   785  	return result.User.ID + "@twitter", result.User.Username, result.User.Avatar, address, nil
   786  }
   787  
   788  // authTwitterWithTokenV2 tries to authenticate a faucet request using Twitter's v2
   789  // API, returning the user id, username, avatar URL and Ethereum address to fund on
   790  // success.
   791  func authTwitterWithTokenV2(tweetID string, token string) (string, string, string, common.Address, error) {
   792  	// Query the tweet details from Twitter
   793  	url := fmt.Sprintf("https://api.twitter.com/2/tweets/%s?expansions=author_id&user.fields=profile_image_url", tweetID)
   794  	req, err := http.NewRequest("GET", url, nil)
   795  	if err != nil {
   796  		return "", "", "", common.Address{}, err
   797  	}
   798  	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
   799  	res, err := http.DefaultClient.Do(req)
   800  	if err != nil {
   801  		return "", "", "", common.Address{}, err
   802  	}
   803  	defer res.Body.Close()
   804  
   805  	var result struct {
   806  		Data struct {
   807  			AuthorID string `json:"author_id"`
   808  			Text     string `json:"text"`
   809  		} `json:"data"`
   810  		Includes struct {
   811  			Users []struct {
   812  				ID       string `json:"id"`
   813  				Username string `json:"username"`
   814  				Avatar   string `json:"profile_image_url"`
   815  			} `json:"users"`
   816  		} `json:"includes"`
   817  	}
   818  
   819  	err = json.NewDecoder(res.Body).Decode(&result)
   820  	if err != nil {
   821  		return "", "", "", common.Address{}, err
   822  	}
   823  
   824  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Data.Text))
   825  	if address == (common.Address{}) {
   826  		//lint:ignore ST1005 This error is to be displayed in the browser
   827  		return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   828  	}
   829  	return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].Avatar, address, nil
   830  }
   831  
   832  // authFacebook tries to authenticate a faucet request using Facebook posts,
   833  // returning the username, avatar URL and Ethereum address to fund on success.
   834  func authFacebook(url string) (string, string, common.Address, error) {
   835  	// Ensure the user specified a meaningful URL, no fancy nonsense
   836  	parts := strings.Split(strings.Split(url, "?")[0], "/")
   837  	if parts[len(parts)-1] == "" {
   838  		parts = parts[0 : len(parts)-1]
   839  	}
   840  	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
   841  		//lint:ignore ST1005 This error is to be displayed in the browser
   842  		return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
   843  	}
   844  	username := parts[len(parts)-3]
   845  
   846  	// Facebook's Graph API isn't really friendly with direct links. Still, we don't
   847  	// want to do ask read permissions from users, so just load the public posts and
   848  	// scrape it for the Ethereum address and profile URL.
   849  	//
   850  	// Facebook recently changed their desktop webpage to use AJAX for loading post
   851  	// content, so switch over to the mobile site for now. Will probably end up having
   852  	// to use the API eventually.
   853  	crawl := strings.Replace(url, "www.facebook.com", "m.facebook.com", 1)
   854  
   855  	res, err := http.Get(crawl)
   856  	if err != nil {
   857  		return "", "", common.Address{}, err
   858  	}
   859  	defer res.Body.Close()
   860  
   861  	body, err := ioutil.ReadAll(res.Body)
   862  	if err != nil {
   863  		return "", "", common.Address{}, err
   864  	}
   865  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   866  	if address == (common.Address{}) {
   867  		//lint:ignore ST1005 This error is to be displayed in the browser
   868  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   869  	}
   870  	var avatar string
   871  	if parts = regexp.MustCompile(`src="([^"]+fbcdn\.net[^"]+)"`).FindStringSubmatch(string(body)); len(parts) == 2 {
   872  		avatar = parts[1]
   873  	}
   874  	return username + "@facebook", avatar, address, nil
   875  }
   876  
   877  // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
   878  // without actually performing any remote authentication. This mode is prone to
   879  // Byzantine attack, so only ever use for truly private networks.
   880  func authNoAuth(url string) (string, string, common.Address, error) {
   881  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
   882  	if address == (common.Address{}) {
   883  		//lint:ignore ST1005 This error is to be displayed in the browser
   884  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   885  	}
   886  	return address.Hex() + "@noauth", "", address, nil
   887  }
   888  
   889  // getGenesis returns a genesis based on input args
   890  func getGenesis(genesisFlag *string, goerliFlag bool, rinkebyFlag bool, mumbaiFlag bool) (*core.Genesis, error) {
   891  	switch {
   892  	case genesisFlag != nil:
   893  		var genesis core.Genesis
   894  		err := common.LoadJSON(*genesisFlag, &genesis)
   895  		return &genesis, err
   896  	case goerliFlag:
   897  		return core.DefaultGoerliGenesisBlock(), nil
   898  	case rinkebyFlag:
   899  		return core.DefaultRinkebyGenesisBlock(), nil
   900  	case mumbaiFlag:
   901  		return core.DefaultMumbaiGenesisBlock(), nil
   902  	default:
   903  		return nil, fmt.Errorf("no genesis flag provided")
   904  	}
   905  }