github.com/ethereum-optimism/optimism/l2geth@v0.0.0-20230612200230-50b04ade19e3/cmd/faucet/faucet.go (about)

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