github.com/cerc-io/go-ethereum@v1.9.7/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/go-ethereum/accounts"
    45  	"github.com/ethereum/go-ethereum/accounts/keystore"
    46  	"github.com/ethereum/go-ethereum/common"
    47  	"github.com/ethereum/go-ethereum/core"
    48  	"github.com/ethereum/go-ethereum/core/types"
    49  	"github.com/ethereum/go-ethereum/eth"
    50  	"github.com/ethereum/go-ethereum/eth/downloader"
    51  	"github.com/ethereum/go-ethereum/ethclient"
    52  	"github.com/ethereum/go-ethereum/ethstats"
    53  	"github.com/ethereum/go-ethereum/les"
    54  	"github.com/ethereum/go-ethereum/log"
    55  	"github.com/ethereum/go-ethereum/node"
    56  	"github.com/ethereum/go-ethereum/p2p"
    57  	"github.com/ethereum/go-ethereum/p2p/discv5"
    58  	"github.com/ethereum/go-ethereum/p2p/enode"
    59  	"github.com/ethereum/go-ethereum/p2p/nat"
    60  	"github.com/ethereum/go-ethereum/params"
    61  	"golang.org/x/net/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.Handle("/api", websocket.Handler(f.apiHandler))
   300  
   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(conn *websocket.Conn) {
   312  	// Start tracking the connection and drop at the end
   313  	defer conn.Close()
   314  
   315  	f.lock.Lock()
   316  	f.conns = append(f.conns, conn)
   317  	f.lock.Unlock()
   318  
   319  	defer func() {
   320  		f.lock.Lock()
   321  		for i, c := range f.conns {
   322  			if c == conn {
   323  				f.conns = append(f.conns[:i], f.conns[i+1:]...)
   324  				break
   325  			}
   326  		}
   327  		f.lock.Unlock()
   328  	}()
   329  	// Gather the initial stats from the network to report
   330  	var (
   331  		head    *types.Header
   332  		balance *big.Int
   333  		nonce   uint64
   334  		err     error
   335  	)
   336  	for head == nil || balance == nil {
   337  		// Retrieve the current stats cached by the faucet
   338  		f.lock.RLock()
   339  		if f.head != nil {
   340  			head = types.CopyHeader(f.head)
   341  		}
   342  		if f.balance != nil {
   343  			balance = new(big.Int).Set(f.balance)
   344  		}
   345  		nonce = f.nonce
   346  		f.lock.RUnlock()
   347  
   348  		if head == nil || balance == nil {
   349  			// Report the faucet offline until initial stats are ready
   350  			if err = sendError(conn, errors.New("Faucet offline")); err != nil {
   351  				log.Warn("Failed to send faucet error to client", "err", err)
   352  				return
   353  			}
   354  			time.Sleep(3 * time.Second)
   355  		}
   356  	}
   357  	// Send over the initial stats and the latest header
   358  	if err = send(conn, map[string]interface{}{
   359  		"funds":    new(big.Int).Div(balance, ether),
   360  		"funded":   nonce,
   361  		"peers":    f.stack.Server().PeerCount(),
   362  		"requests": f.reqs,
   363  	}, 3*time.Second); err != nil {
   364  		log.Warn("Failed to send initial stats to client", "err", err)
   365  		return
   366  	}
   367  	if err = send(conn, head, 3*time.Second); err != nil {
   368  		log.Warn("Failed to send initial header to client", "err", err)
   369  		return
   370  	}
   371  	// Keep reading requests from the websocket until the connection breaks
   372  	for {
   373  		// Fetch the next funding request and validate against github
   374  		var msg struct {
   375  			URL     string `json:"url"`
   376  			Tier    uint   `json:"tier"`
   377  			Captcha string `json:"captcha"`
   378  		}
   379  		if err = websocket.JSON.Receive(conn, &msg); err != nil {
   380  			return
   381  		}
   382  		if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
   383  			!strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
   384  			if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil {
   385  				log.Warn("Failed to send URL error to client", "err", err)
   386  				return
   387  			}
   388  			continue
   389  		}
   390  		if msg.Tier >= uint(*tiersFlag) {
   391  			if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil {
   392  				log.Warn("Failed to send tier error to client", "err", err)
   393  				return
   394  			}
   395  			continue
   396  		}
   397  		log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier)
   398  
   399  		// If captcha verifications are enabled, make sure we're not dealing with a robot
   400  		if *captchaToken != "" {
   401  			form := url.Values{}
   402  			form.Add("secret", *captchaSecret)
   403  			form.Add("response", msg.Captcha)
   404  
   405  			res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
   406  			if err != nil {
   407  				if err = sendError(conn, err); err != nil {
   408  					log.Warn("Failed to send captcha post error to client", "err", err)
   409  					return
   410  				}
   411  				continue
   412  			}
   413  			var result struct {
   414  				Success bool            `json:"success"`
   415  				Errors  json.RawMessage `json:"error-codes"`
   416  			}
   417  			err = json.NewDecoder(res.Body).Decode(&result)
   418  			res.Body.Close()
   419  			if err != nil {
   420  				if err = sendError(conn, err); err != nil {
   421  					log.Warn("Failed to send captcha decode error to client", "err", err)
   422  					return
   423  				}
   424  				continue
   425  			}
   426  			if !result.Success {
   427  				log.Warn("Captcha verification failed", "err", string(result.Errors))
   428  				if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil {
   429  					log.Warn("Failed to send captcha failure to client", "err", err)
   430  					return
   431  				}
   432  				continue
   433  			}
   434  		}
   435  		// Retrieve the Ethereum address to fund, the requesting user and a profile picture
   436  		var (
   437  			username string
   438  			avatar   string
   439  			address  common.Address
   440  		)
   441  		switch {
   442  		case strings.HasPrefix(msg.URL, "https://gist.github.com/"):
   443  			if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil {
   444  				log.Warn("Failed to send GitHub deprecation to client", "err", err)
   445  				return
   446  			}
   447  			continue
   448  		case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
   449  			if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil {
   450  				log.Warn("Failed to send Google+ deprecation to client", "err", err)
   451  				return
   452  			}
   453  			continue
   454  		case strings.HasPrefix(msg.URL, "https://twitter.com/"):
   455  			username, avatar, address, err = authTwitter(msg.URL)
   456  		case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
   457  			username, avatar, address, err = authFacebook(msg.URL)
   458  		case *noauthFlag:
   459  			username, avatar, address, err = authNoAuth(msg.URL)
   460  		default:
   461  			err = errors.New("Something funky happened, please open an issue at https://github.com/ethereum/go-ethereum/issues")
   462  		}
   463  		if err != nil {
   464  			if err = sendError(conn, err); err != nil {
   465  				log.Warn("Failed to send prefix error to client", "err", err)
   466  				return
   467  			}
   468  			continue
   469  		}
   470  		log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address)
   471  
   472  		// Ensure the user didn't request funds too recently
   473  		f.lock.Lock()
   474  		var (
   475  			fund    bool
   476  			timeout time.Time
   477  		)
   478  		if timeout = f.timeouts[username]; time.Now().After(timeout) {
   479  			// User wasn't funded recently, create the funding transaction
   480  			amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
   481  			amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
   482  			amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil))
   483  
   484  			tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil)
   485  			signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID)
   486  			if err != nil {
   487  				f.lock.Unlock()
   488  				if err = sendError(conn, err); err != nil {
   489  					log.Warn("Failed to send transaction creation error to client", "err", err)
   490  					return
   491  				}
   492  				continue
   493  			}
   494  			// Submit the transaction and mark as funded if successful
   495  			if err := f.client.SendTransaction(context.Background(), signed); err != nil {
   496  				f.lock.Unlock()
   497  				if err = sendError(conn, err); err != nil {
   498  					log.Warn("Failed to send transaction transmission error to client", "err", err)
   499  					return
   500  				}
   501  				continue
   502  			}
   503  			f.reqs = append(f.reqs, &request{
   504  				Avatar:  avatar,
   505  				Account: address,
   506  				Time:    time.Now(),
   507  				Tx:      signed,
   508  			})
   509  			timeout := time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute
   510  			grace := timeout / 288 // 24h timeout => 5m grace
   511  
   512  			f.timeouts[username] = time.Now().Add(timeout - grace)
   513  			fund = true
   514  		}
   515  		f.lock.Unlock()
   516  
   517  		// Send an error if too frequent funding, othewise a success
   518  		if !fund {
   519  			if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))); err != nil { // nolint: gosimple
   520  				log.Warn("Failed to send funding error to client", "err", err)
   521  				return
   522  			}
   523  			continue
   524  		}
   525  		if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil {
   526  			log.Warn("Failed to send funding success to client", "err", err)
   527  			return
   528  		}
   529  		select {
   530  		case f.update <- struct{}{}:
   531  		default:
   532  		}
   533  	}
   534  }
   535  
   536  // refresh attempts to retrieve the latest header from the chain and extract the
   537  // associated faucet balance and nonce for connectivity caching.
   538  func (f *faucet) refresh(head *types.Header) error {
   539  	// Ensure a state update does not run for too long
   540  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   541  	defer cancel()
   542  
   543  	// If no header was specified, use the current chain head
   544  	var err error
   545  	if head == nil {
   546  		if head, err = f.client.HeaderByNumber(ctx, nil); err != nil {
   547  			return err
   548  		}
   549  	}
   550  	// Retrieve the balance, nonce and gas price from the current head
   551  	var (
   552  		balance *big.Int
   553  		nonce   uint64
   554  		price   *big.Int
   555  	)
   556  	if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil {
   557  		return err
   558  	}
   559  	if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil {
   560  		return err
   561  	}
   562  	if price, err = f.client.SuggestGasPrice(ctx); err != nil {
   563  		return err
   564  	}
   565  	// Everything succeeded, update the cached stats and eject old requests
   566  	f.lock.Lock()
   567  	f.head, f.balance = head, balance
   568  	f.price, f.nonce = price, nonce
   569  	for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
   570  		f.reqs = f.reqs[1:]
   571  	}
   572  	f.lock.Unlock()
   573  
   574  	return nil
   575  }
   576  
   577  // loop keeps waiting for interesting events and pushes them out to connected
   578  // websockets.
   579  func (f *faucet) loop() {
   580  	// Wait for chain events and push them to clients
   581  	heads := make(chan *types.Header, 16)
   582  	sub, err := f.client.SubscribeNewHead(context.Background(), heads)
   583  	if err != nil {
   584  		log.Crit("Failed to subscribe to head events", "err", err)
   585  	}
   586  	defer sub.Unsubscribe()
   587  
   588  	// Start a goroutine to update the state from head notifications in the background
   589  	update := make(chan *types.Header)
   590  
   591  	go func() {
   592  		for head := range update {
   593  			// New chain head arrived, query the current stats and stream to clients
   594  			timestamp := time.Unix(int64(head.Time), 0)
   595  			if time.Since(timestamp) > time.Hour {
   596  				log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp))
   597  				continue
   598  			}
   599  			if err := f.refresh(head); err != nil {
   600  				log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err)
   601  				continue
   602  			}
   603  			// Faucet state retrieved, update locally and send to clients
   604  			f.lock.RLock()
   605  			log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price)
   606  
   607  			balance := new(big.Int).Div(f.balance, ether)
   608  			peers := f.stack.Server().PeerCount()
   609  
   610  			for _, conn := range f.conns {
   611  				if err := send(conn, map[string]interface{}{
   612  					"funds":    balance,
   613  					"funded":   f.nonce,
   614  					"peers":    peers,
   615  					"requests": f.reqs,
   616  				}, time.Second); err != nil {
   617  					log.Warn("Failed to send stats to client", "err", err)
   618  					conn.Close()
   619  					continue
   620  				}
   621  				if err := send(conn, head, time.Second); err != nil {
   622  					log.Warn("Failed to send header to client", "err", err)
   623  					conn.Close()
   624  				}
   625  			}
   626  			f.lock.RUnlock()
   627  		}
   628  	}()
   629  	// Wait for various events and assing to the appropriate background threads
   630  	for {
   631  		select {
   632  		case head := <-heads:
   633  			// New head arrived, send if for state update if there's none running
   634  			select {
   635  			case update <- head:
   636  			default:
   637  			}
   638  
   639  		case <-f.update:
   640  			// Pending requests updated, stream to clients
   641  			f.lock.RLock()
   642  			for _, conn := range f.conns {
   643  				if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
   644  					log.Warn("Failed to send requests to client", "err", err)
   645  					conn.Close()
   646  				}
   647  			}
   648  			f.lock.RUnlock()
   649  		}
   650  	}
   651  }
   652  
   653  // sends transmits a data packet to the remote end of the websocket, but also
   654  // setting a write deadline to prevent waiting forever on the node.
   655  func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
   656  	if timeout == 0 {
   657  		timeout = 60 * time.Second
   658  	}
   659  	conn.SetWriteDeadline(time.Now().Add(timeout))
   660  	return websocket.JSON.Send(conn, value)
   661  }
   662  
   663  // sendError transmits an error to the remote end of the websocket, also setting
   664  // the write deadline to 1 second to prevent waiting forever.
   665  func sendError(conn *websocket.Conn, err error) error {
   666  	return send(conn, map[string]string{"error": err.Error()}, time.Second)
   667  }
   668  
   669  // sendSuccess transmits a success message to the remote end of the websocket, also
   670  // setting the write deadline to 1 second to prevent waiting forever.
   671  func sendSuccess(conn *websocket.Conn, msg string) error {
   672  	return send(conn, map[string]string{"success": msg}, time.Second)
   673  }
   674  
   675  // authTwitter tries to authenticate a faucet request using Twitter posts, returning
   676  // the username, avatar URL and Ethereum address to fund on success.
   677  func authTwitter(url string) (string, string, common.Address, error) {
   678  	// Ensure the user specified a meaningful URL, no fancy nonsense
   679  	parts := strings.Split(url, "/")
   680  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   681  		return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   682  	}
   683  	// Twitter's API isn't really friendly with direct links. Still, we don't
   684  	// want to do ask read permissions from users, so just load the public posts and
   685  	// scrape it for the Ethereum address and profile URL.
   686  	res, err := http.Get(url)
   687  	if err != nil {
   688  		return "", "", common.Address{}, err
   689  	}
   690  	defer res.Body.Close()
   691  
   692  	// Resolve the username from the final redirect, no intermediate junk
   693  	parts = strings.Split(res.Request.URL.String(), "/")
   694  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   695  		return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   696  	}
   697  	username := parts[len(parts)-3]
   698  
   699  	body, err := ioutil.ReadAll(res.Body)
   700  	if err != nil {
   701  		return "", "", common.Address{}, err
   702  	}
   703  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   704  	if address == (common.Address{}) {
   705  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   706  	}
   707  	var avatar string
   708  	if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   709  		avatar = parts[1]
   710  	}
   711  	return username + "@twitter", avatar, address, nil
   712  }
   713  
   714  // authFacebook tries to authenticate a faucet request using Facebook posts,
   715  // returning the username, avatar URL and Ethereum address to fund on success.
   716  func authFacebook(url string) (string, string, common.Address, error) {
   717  	// Ensure the user specified a meaningful URL, no fancy nonsense
   718  	parts := strings.Split(url, "/")
   719  	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
   720  		return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
   721  	}
   722  	username := parts[len(parts)-3]
   723  
   724  	// Facebook's Graph API isn't really friendly with direct links. Still, we don't
   725  	// want to do ask read permissions from users, so just load the public posts and
   726  	// scrape it for the Ethereum address and profile URL.
   727  	res, err := http.Get(url)
   728  	if err != nil {
   729  		return "", "", common.Address{}, err
   730  	}
   731  	defer res.Body.Close()
   732  
   733  	body, err := ioutil.ReadAll(res.Body)
   734  	if err != nil {
   735  		return "", "", common.Address{}, err
   736  	}
   737  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   738  	if address == (common.Address{}) {
   739  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   740  	}
   741  	var avatar string
   742  	if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   743  		avatar = parts[1]
   744  	}
   745  	return username + "@facebook", avatar, address, nil
   746  }
   747  
   748  // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
   749  // without actually performing any remote authentication. This mode is prone to
   750  // Byzantine attack, so only ever use for truly private networks.
   751  func authNoAuth(url string) (string, string, common.Address, error) {
   752  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
   753  	if address == (common.Address{}) {
   754  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   755  	}
   756  	return address.Hex() + "@noauth", "", address, nil
   757  }