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