github.com/alexdevranger/node-1.8.27@v0.0.0-20221128213301-aa5841e41d2d/cmd/faucet/faucet.go (about)

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