github.com/SmartMeshFoundation/Spectrum@v0.0.0-20220621030607-452a266fee1e/cmd/faucet/faucet.go (about)

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