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