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