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