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