github.com/juliankolbe/go-ethereum@v1.9.992/cmd/faucet/faucet.go (about)

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