github.com/codingfuture/orig-energi3@v0.8.4/cmd/faucet/faucet.go (about)

     1  // Copyright 2018 The Energi Core Authors
     2  // Copyright 2017 The go-ethereum Authors
     3  // This file is part of Energi Core.
     4  //
     5  // Energi Core is free software: you can redistribute it and/or modify
     6  // it under the terms of the GNU General Public License as published by
     7  // the Free Software Foundation, either version 3 of the License, or
     8  // (at your option) any later version.
     9  //
    10  // Energi Core is distributed in the hope that it will be useful,
    11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    13  // GNU General Public License for more details.
    14  //
    15  // You should have received a copy of the GNU General Public License
    16  // along with Energi Core. If not, see <http://www.gnu.org/licenses/>.
    17  
    18  // faucet is a Ether faucet backed by a light client.
    19  package main
    20  
    21  //go:generate go-bindata -nometadata -o website.go faucet.html
    22  //go:generate gofmt -w -s website.go
    23  
    24  import (
    25  	"bytes"
    26  	"context"
    27  	"encoding/json"
    28  	"errors"
    29  	"flag"
    30  	"fmt"
    31  	"html/template"
    32  	"io/ioutil"
    33  	"math"
    34  	"math/big"
    35  	"net/http"
    36  	"net/url"
    37  	"os"
    38  	"path/filepath"
    39  	"regexp"
    40  	"strconv"
    41  	"strings"
    42  	"sync"
    43  	"time"
    44  
    45  	"github.com/ethereum/go-ethereum/accounts"
    46  	"github.com/ethereum/go-ethereum/accounts/keystore"
    47  	"github.com/ethereum/go-ethereum/common"
    48  	"github.com/ethereum/go-ethereum/core"
    49  	"github.com/ethereum/go-ethereum/core/types"
    50  	"github.com/ethereum/go-ethereum/eth"
    51  	"github.com/ethereum/go-ethereum/eth/downloader"
    52  	"github.com/ethereum/go-ethereum/ethclient"
    53  	"github.com/ethereum/go-ethereum/ethstats"
    54  	"github.com/ethereum/go-ethereum/les"
    55  	"github.com/ethereum/go-ethereum/log"
    56  	"github.com/ethereum/go-ethereum/node"
    57  	"github.com/ethereum/go-ethereum/p2p"
    58  	"github.com/ethereum/go-ethereum/p2p/discv5"
    59  	"github.com/ethereum/go-ethereum/p2p/enode"
    60  	"github.com/ethereum/go-ethereum/p2p/nat"
    61  	"github.com/ethereum/go-ethereum/params"
    62  	"golang.org/x/net/websocket"
    63  )
    64  
    65  var (
    66  	genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with")
    67  	apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection")
    68  	ethPortFlag = flag.Int("ethport", 39797, "Listener port for the devp2p connection")
    69  	bootFlag    = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with")
    70  	netFlag     = flag.Uint64("network", 0, "Network ID to use for the Energi protocol")
    71  	statsFlag   = flag.String("ethstats", "", "Ethstats network monitoring auth string")
    72  
    73  	netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet")
    74  	payoutFlag  = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request")
    75  	minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds")
    76  	tiersFlag   = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)")
    77  
    78  	accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with")
    79  	accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds")
    80  
    81  	captchaToken  = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side")
    82  	captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side")
    83  
    84  	noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication")
    85  	logFlag    = flag.Int("loglevel", 3, "Log level to use for Energi and the faucet")
    86  )
    87  
    88  var (
    89  	ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
    90  )
    91  
    92  func main() {
    93  	// Parse the flags and set up the logger to print everything requested
    94  	flag.Parse()
    95  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
    96  
    97  	// Construct the payout tiers
    98  	amounts := make([]string, *tiersFlag)
    99  	periods := make([]string, *tiersFlag)
   100  	for i := 0; i < *tiersFlag; i++ {
   101  		// Calculate the amount for the next tier and format it
   102  		amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
   103  		amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
   104  		if amount == 1 {
   105  			amounts[i] = strings.TrimSuffix(amounts[i], "s")
   106  		}
   107  		// Calculate the period for the next tier and format it
   108  		period := *minutesFlag * int(math.Pow(3, float64(i)))
   109  		periods[i] = fmt.Sprintf("%d mins", period)
   110  		if period%60 == 0 {
   111  			period /= 60
   112  			periods[i] = fmt.Sprintf("%d hours", period)
   113  
   114  			if period%24 == 0 {
   115  				period /= 24
   116  				periods[i] = fmt.Sprintf("%d days", period)
   117  			}
   118  		}
   119  		if period == 1 {
   120  			periods[i] = strings.TrimSuffix(periods[i], "s")
   121  		}
   122  	}
   123  	// Load up and render the faucet website
   124  	tmpl, err := Asset("faucet.html")
   125  	if err != nil {
   126  		log.Crit("Failed to load the faucet template", "err", err)
   127  	}
   128  	website := new(bytes.Buffer)
   129  	err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
   130  		"Network":   *netnameFlag,
   131  		"Amounts":   amounts,
   132  		"Periods":   periods,
   133  		"Recaptcha": *captchaToken,
   134  		"NoAuth":    *noauthFlag,
   135  	})
   136  	if err != nil {
   137  		log.Crit("Failed to render the faucet template", "err", err)
   138  	}
   139  	// Load and parse the genesis block requested by the user
   140  	blob, err := ioutil.ReadFile(*genesisFlag)
   141  	if err != nil {
   142  		log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
   143  	}
   144  	genesis := new(core.Genesis)
   145  	if err = json.Unmarshal(blob, genesis); err != nil {
   146  		log.Crit("Failed to parse genesis block json", "err", err)
   147  	}
   148  	// Convert the bootnodes to internal enode representations
   149  	var enodes []*discv5.Node
   150  	for _, boot := range strings.Split(*bootFlag, ",") {
   151  		if url, err := discv5.ParseNode(boot); err == nil {
   152  			enodes = append(enodes, url)
   153  		} else {
   154  			log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
   155  		}
   156  	}
   157  	// Load up the account key and decrypt its password
   158  	if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
   159  		log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
   160  	}
   161  	// Delete trailing newline in password
   162  	pass := strings.TrimSuffix(string(blob), "\n")
   163  
   164  	ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".energifaucet", "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, false)
   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  	head     *types.Header      // Current head header of the faucet
   204  	balance  *big.Int           // Current balance of the faucet
   205  	nonce    uint64             // Current pending nonce of the faucet
   206  	price    *big.Int           // Current gas price to issue funds with
   207  
   208  	conns    []*websocket.Conn    // Currently live websocket connections
   209  	timeouts map[string]time.Time // History of users and their funding timeouts
   210  	reqs     []*request           // Currently pending funding requests
   211  	update   chan struct{}        // Channel to signal request updates
   212  
   213  	lock sync.RWMutex // Lock protecting the faucet's internals
   214  }
   215  
   216  func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
   217  	// Assemble the raw devp2p protocol stack
   218  	stack, err := node.New(&node.Config{
   219  		Name:    "energi3",
   220  		Version: params.VersionWithMeta,
   221  		DataDir: filepath.Join(os.Getenv("HOME"), ".energifaucet"),
   222  		P2P: p2p.Config{
   223  			NAT:              nat.Any(),
   224  			NoDiscovery:      true,
   225  			DiscoveryV5:      true,
   226  			ListenAddr:       fmt.Sprintf(":%d", port),
   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, err := enode.ParseV4(boot.String())
   260  		if err == nil {
   261  			stack.Server().AddPeer(old)
   262  		}
   263  	}
   264  	// Attach to the client and retrieve and interesting metadatas
   265  	api, err := stack.Attach()
   266  	if err != nil {
   267  		stack.Stop()
   268  		return nil, err
   269  	}
   270  	client := ethclient.NewClient(api)
   271  
   272  	return &faucet{
   273  		config:   genesis.Config,
   274  		stack:    stack,
   275  		client:   client,
   276  		index:    index,
   277  		keystore: ks,
   278  		account:  ks.Accounts()[0],
   279  		timeouts: make(map[string]time.Time),
   280  		update:   make(chan struct{}, 1),
   281  	}, nil
   282  }
   283  
   284  // close terminates the Ethereum connection and tears down the faucet.
   285  func (f *faucet) close() error {
   286  	return f.stack.Stop()
   287  }
   288  
   289  // listenAndServe registers the HTTP handlers for the faucet and boots it up
   290  // for service user funding requests.
   291  func (f *faucet) listenAndServe(port int) error {
   292  	go f.loop()
   293  
   294  	http.HandleFunc("/", f.webHandler)
   295  	http.Handle("/api", websocket.Handler(f.apiHandler))
   296  
   297  	return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
   298  }
   299  
   300  // webHandler handles all non-api requests, simply flattening and returning the
   301  // faucet website.
   302  func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
   303  	w.Write(f.index)
   304  }
   305  
   306  // apiHandler handles requests for Ether grants and transaction statuses.
   307  func (f *faucet) apiHandler(conn *websocket.Conn) {
   308  	// Start tracking the connection and drop at the end
   309  	defer conn.Close()
   310  
   311  	f.lock.Lock()
   312  	f.conns = append(f.conns, conn)
   313  	f.lock.Unlock()
   314  
   315  	defer func() {
   316  		f.lock.Lock()
   317  		for i, c := range f.conns {
   318  			if c == conn {
   319  				f.conns = append(f.conns[:i], f.conns[i+1:]...)
   320  				break
   321  			}
   322  		}
   323  		f.lock.Unlock()
   324  	}()
   325  	// Gather the initial stats from the network to report
   326  	var (
   327  		head    *types.Header
   328  		balance *big.Int
   329  		nonce   uint64
   330  		err     error
   331  	)
   332  	for head == nil || balance == nil {
   333  		// Retrieve the current stats cached by the faucet
   334  		f.lock.RLock()
   335  		if f.head != nil {
   336  			head = types.CopyHeader(f.head)
   337  		}
   338  		if f.balance != nil {
   339  			balance = new(big.Int).Set(f.balance)
   340  		}
   341  		nonce = f.nonce
   342  		f.lock.RUnlock()
   343  
   344  		if head == nil || balance == nil {
   345  			// Report the faucet offline until initial stats are ready
   346  			if err = sendError(conn, errors.New("Faucet offline")); err != nil {
   347  				log.Warn("Failed to send faucet error to client", "err", err)
   348  				return
   349  			}
   350  			time.Sleep(3 * time.Second)
   351  		}
   352  	}
   353  	// Send over the initial stats and the latest header
   354  	if err = send(conn, map[string]interface{}{
   355  		"funds":    new(big.Int).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/ethereum/go-ethereum/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, 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  // refresh attempts to retrieve the latest header from the chain and extract the
   526  // associated faucet balance and nonce for connectivity caching.
   527  func (f *faucet) refresh(head *types.Header) error {
   528  	// Ensure a state update does not run for too long
   529  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   530  	defer cancel()
   531  
   532  	// If no header was specified, use the current chain head
   533  	var err error
   534  	if head == nil {
   535  		if head, err = f.client.HeaderByNumber(ctx, nil); err != nil {
   536  			return err
   537  		}
   538  	}
   539  	// Retrieve the balance, nonce and gas price from the current head
   540  	var (
   541  		balance *big.Int
   542  		nonce   uint64
   543  		price   *big.Int
   544  	)
   545  	if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil {
   546  		return err
   547  	}
   548  	if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil {
   549  		return err
   550  	}
   551  	if price, err = f.client.SuggestGasPrice(ctx); err != nil {
   552  		return err
   553  	}
   554  	// Everything succeeded, update the cached stats and eject old requests
   555  	f.lock.Lock()
   556  	f.head, f.balance = head, balance
   557  	f.price, f.nonce = price, nonce
   558  	for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
   559  		f.reqs = f.reqs[1:]
   560  	}
   561  	f.lock.Unlock()
   562  
   563  	return nil
   564  }
   565  
   566  // loop keeps waiting for interesting events and pushes them out to connected
   567  // websockets.
   568  func (f *faucet) loop() {
   569  	// Wait for chain events and push them to clients
   570  	heads := make(chan *types.Header, 16)
   571  	sub, err := f.client.SubscribeNewHead(context.Background(), heads)
   572  	if err != nil {
   573  		log.Crit("Failed to subscribe to head events", "err", err)
   574  	}
   575  	defer sub.Unsubscribe()
   576  
   577  	// Start a goroutine to update the state from head notifications in the background
   578  	update := make(chan *types.Header)
   579  
   580  	go func() {
   581  		for head := range update {
   582  			// New chain head arrived, query the current stats and stream to clients
   583  			timestamp := time.Unix(int64(head.Time), 0)
   584  			if time.Since(timestamp) > time.Hour {
   585  				log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp))
   586  				continue
   587  			}
   588  			if err := f.refresh(head); err != nil {
   589  				log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err)
   590  				continue
   591  			}
   592  			// Faucet state retrieved, update locally and send to clients
   593  			f.lock.RLock()
   594  			log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price)
   595  
   596  			balance := new(big.Int).Div(f.balance, ether)
   597  			peers := f.stack.Server().PeerCount()
   598  
   599  			for _, conn := range f.conns {
   600  				if err := send(conn, map[string]interface{}{
   601  					"funds":    balance,
   602  					"funded":   f.nonce,
   603  					"peers":    peers,
   604  					"requests": f.reqs,
   605  				}, time.Second); err != nil {
   606  					log.Warn("Failed to send stats to client", "err", err)
   607  					conn.Close()
   608  					continue
   609  				}
   610  				if err := send(conn, head, time.Second); err != nil {
   611  					log.Warn("Failed to send header to client", "err", err)
   612  					conn.Close()
   613  				}
   614  			}
   615  			f.lock.RUnlock()
   616  		}
   617  	}()
   618  	// Wait for various events and assing to the appropriate background threads
   619  	for {
   620  		select {
   621  		case head := <-heads:
   622  			// New head arrived, send if for state update if there's none running
   623  			select {
   624  			case update <- head:
   625  			default:
   626  			}
   627  
   628  		case <-f.update:
   629  			// Pending requests updated, stream to clients
   630  			f.lock.RLock()
   631  			for _, conn := range f.conns {
   632  				if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
   633  					log.Warn("Failed to send requests to client", "err", err)
   634  					conn.Close()
   635  				}
   636  			}
   637  			f.lock.RUnlock()
   638  		}
   639  	}
   640  }
   641  
   642  // sends transmits a data packet to the remote end of the websocket, but also
   643  // setting a write deadline to prevent waiting forever on the node.
   644  func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
   645  	if timeout == 0 {
   646  		timeout = 60 * time.Second
   647  	}
   648  	conn.SetWriteDeadline(time.Now().Add(timeout))
   649  	return websocket.JSON.Send(conn, value)
   650  }
   651  
   652  // sendError transmits an error to the remote end of the websocket, also setting
   653  // the write deadline to 1 second to prevent waiting forever.
   654  func sendError(conn *websocket.Conn, err error) error {
   655  	return send(conn, map[string]string{"error": err.Error()}, time.Second)
   656  }
   657  
   658  // sendSuccess transmits a success message to the remote end of the websocket, also
   659  // setting the write deadline to 1 second to prevent waiting forever.
   660  func sendSuccess(conn *websocket.Conn, msg string) error {
   661  	return send(conn, map[string]string{"success": msg}, time.Second)
   662  }
   663  
   664  // authTwitter tries to authenticate a faucet request using Twitter posts, returning
   665  // the username, avatar URL and Ethereum address to fund on success.
   666  func authTwitter(url string) (string, string, common.Address, error) {
   667  	// Ensure the user specified a meaningful URL, no fancy nonsense
   668  	parts := strings.Split(url, "/")
   669  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   670  		return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   671  	}
   672  	// Twitter's API isn't really friendly with direct links. Still, we don't
   673  	// want to do ask read permissions from users, so just load the public posts and
   674  	// scrape it for the Ethereum address and profile URL.
   675  	res, err := http.Get(url)
   676  	if err != nil {
   677  		return "", "", common.Address{}, err
   678  	}
   679  	defer res.Body.Close()
   680  
   681  	// Resolve the username from the final redirect, no intermediate junk
   682  	parts = strings.Split(res.Request.URL.String(), "/")
   683  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   684  		return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   685  	}
   686  	username := parts[len(parts)-3]
   687  
   688  	body, err := ioutil.ReadAll(res.Body)
   689  	if err != nil {
   690  		return "", "", common.Address{}, err
   691  	}
   692  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   693  	if address == (common.Address{}) {
   694  		return "", "", common.Address{}, errors.New("No Energi address found to fund")
   695  	}
   696  	var avatar string
   697  	if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   698  		avatar = parts[1]
   699  	}
   700  	return username + "@twitter", avatar, address, nil
   701  }
   702  
   703  // authGooglePlus tries to authenticate a faucet request using GooglePlus posts,
   704  // returning the username, avatar URL and Ethereum address to fund on success.
   705  func authGooglePlus(url string) (string, string, common.Address, error) {
   706  	// Ensure the user specified a meaningful URL, no fancy nonsense
   707  	parts := strings.Split(url, "/")
   708  	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
   709  		return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
   710  	}
   711  	username := parts[len(parts)-3]
   712  
   713  	// Google's API isn't really friendly with direct links. Still, we don't
   714  	// want to do ask read permissions from users, so just load the public posts and
   715  	// scrape it for the Ethereum address and profile URL.
   716  	res, err := http.Get(url)
   717  	if err != nil {
   718  		return "", "", common.Address{}, err
   719  	}
   720  	defer res.Body.Close()
   721  
   722  	body, err := ioutil.ReadAll(res.Body)
   723  	if err != nil {
   724  		return "", "", common.Address{}, err
   725  	}
   726  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   727  	if address == (common.Address{}) {
   728  		return "", "", common.Address{}, errors.New("No Energi address found to fund")
   729  	}
   730  	var avatar string
   731  	if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   732  		avatar = parts[1]
   733  	}
   734  	return username + "@google+", avatar, address, nil
   735  }
   736  
   737  // authFacebook tries to authenticate a faucet request using Facebook posts,
   738  // returning the username, avatar URL and Ethereum address to fund on success.
   739  func authFacebook(url string) (string, string, common.Address, error) {
   740  	// Ensure the user specified a meaningful URL, no fancy nonsense
   741  	parts := strings.Split(url, "/")
   742  	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
   743  		return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
   744  	}
   745  	username := parts[len(parts)-3]
   746  
   747  	// Facebook's Graph API isn't really friendly with direct links. Still, we don't
   748  	// want to do ask read permissions from users, so just load the public posts and
   749  	// scrape it for the Ethereum address and profile URL.
   750  	res, err := http.Get(url)
   751  	if err != nil {
   752  		return "", "", common.Address{}, err
   753  	}
   754  	defer res.Body.Close()
   755  
   756  	body, err := ioutil.ReadAll(res.Body)
   757  	if err != nil {
   758  		return "", "", common.Address{}, err
   759  	}
   760  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   761  	if address == (common.Address{}) {
   762  		return "", "", common.Address{}, errors.New("No Energi address found to fund")
   763  	}
   764  	var avatar string
   765  	if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   766  		avatar = parts[1]
   767  	}
   768  	return username + "@facebook", avatar, address, nil
   769  }
   770  
   771  // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
   772  // without actually performing any remote authentication. This mode is prone to
   773  // Byzantine attack, so only ever use for truly private networks.
   774  func authNoAuth(url string) (string, string, common.Address, error) {
   775  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
   776  	if address == (common.Address{}) {
   777  		return "", "", common.Address{}, errors.New("No Energi address found to fund")
   778  	}
   779  	return address.Hex() + "@noauth", "", address, nil
   780  }