github.com/CommerciumBlockchain/go-commercium@v0.0.0-20220709212705-b46438a77516/cmd/faucet/faucet.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-ethereum.
     3  //
     4  // go-ethereum is free software: you can redistribute it and/or modify
     5  // it under the terms of the GNU General Public License as published by
     6  // the Free Software Foundation, either version 3 of the License, or
     7  // (at your option) any later version.
     8  //
     9  // go-ethereum is distributed in the hope that it will be useful,
    10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    12  // GNU General Public License for more details.
    13  //
    14  // You should have received a copy of the GNU General Public License
    15  // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
    16  
    17  // faucet is a Ether faucet backed by a light client.
    18  package main
    19  
    20  //go:generate go-bindata -nometadata -o website.go faucet.html
    21  //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/CommerciumBlockchain/go-commercium/accounts"
    45  	"github.com/CommerciumBlockchain/go-commercium/accounts/keystore"
    46  	"github.com/CommerciumBlockchain/go-commercium/cmd/utils"
    47  	"github.com/CommerciumBlockchain/go-commercium/common"
    48  	"github.com/CommerciumBlockchain/go-commercium/core"
    49  	"github.com/CommerciumBlockchain/go-commercium/core/types"
    50  	"github.com/CommerciumBlockchain/go-commercium/eth"
    51  	"github.com/CommerciumBlockchain/go-commercium/eth/downloader"
    52  	"github.com/CommerciumBlockchain/go-commercium/ethclient"
    53  	"github.com/CommerciumBlockchain/go-commercium/ethstats"
    54  	"github.com/CommerciumBlockchain/go-commercium/les"
    55  	"github.com/CommerciumBlockchain/go-commercium/log"
    56  	"github.com/CommerciumBlockchain/go-commercium/node"
    57  	"github.com/CommerciumBlockchain/go-commercium/p2p"
    58  	"github.com/CommerciumBlockchain/go-commercium/p2p/discv5"
    59  	"github.com/CommerciumBlockchain/go-commercium/p2p/enode"
    60  	"github.com/CommerciumBlockchain/go-commercium/p2p/nat"
    61  	"github.com/CommerciumBlockchain/go-commercium/params"
    62  	"github.com/gorilla/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", 30303, "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 Ethereum 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 Ethereum and the faucet")
    86  
    87  	twitterBearerToken = flag.String("twitter.token", "", "Twitter bearer token to authenticate with the twitter API")
    88  )
    89  
    90  var (
    91  	ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
    92  )
    93  
    94  var (
    95  	gitCommit = "" // Git SHA1 commit hash of the release (set via linker flags)
    96  	gitDate   = "" // Git commit date YYYYMMDD of the release (set via linker flags)
    97  )
    98  
    99  func main() {
   100  	// Parse the flags and set up the logger to print everything requested
   101  	flag.Parse()
   102  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
   103  
   104  	// Construct the payout tiers
   105  	amounts := make([]string, *tiersFlag)
   106  	periods := make([]string, *tiersFlag)
   107  	for i := 0; i < *tiersFlag; i++ {
   108  		// Calculate the amount for the next tier and format it
   109  		amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
   110  		amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
   111  		if amount == 1 {
   112  			amounts[i] = strings.TrimSuffix(amounts[i], "s")
   113  		}
   114  		// Calculate the period for the next tier and format it
   115  		period := *minutesFlag * int(math.Pow(3, float64(i)))
   116  		periods[i] = fmt.Sprintf("%d mins", period)
   117  		if period%60 == 0 {
   118  			period /= 60
   119  			periods[i] = fmt.Sprintf("%d hours", period)
   120  
   121  			if period%24 == 0 {
   122  				period /= 24
   123  				periods[i] = fmt.Sprintf("%d days", period)
   124  			}
   125  		}
   126  		if period == 1 {
   127  			periods[i] = strings.TrimSuffix(periods[i], "s")
   128  		}
   129  	}
   130  	// Load up and render the faucet website
   131  	tmpl, err := Asset("faucet.html")
   132  	if err != nil {
   133  		log.Crit("Failed to load the faucet template", "err", err)
   134  	}
   135  	website := new(bytes.Buffer)
   136  	err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
   137  		"Network":   *netnameFlag,
   138  		"Amounts":   amounts,
   139  		"Periods":   periods,
   140  		"Recaptcha": *captchaToken,
   141  		"NoAuth":    *noauthFlag,
   142  	})
   143  	if err != nil {
   144  		log.Crit("Failed to render the faucet template", "err", err)
   145  	}
   146  	// Load and parse the genesis block requested by the user
   147  	blob, err := ioutil.ReadFile(*genesisFlag)
   148  	if err != nil {
   149  		log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
   150  	}
   151  	genesis := new(core.Genesis)
   152  	if err = json.Unmarshal(blob, genesis); err != nil {
   153  		log.Crit("Failed to parse genesis block json", "err", err)
   154  	}
   155  	// Convert the bootnodes to internal enode representations
   156  	var enodes []*discv5.Node
   157  	for _, boot := range strings.Split(*bootFlag, ",") {
   158  		if url, err := discv5.ParseNode(boot); err == nil {
   159  			enodes = append(enodes, url)
   160  		} else {
   161  			log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
   162  		}
   163  	}
   164  	// Load up the account key and decrypt its password
   165  	if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
   166  		log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
   167  	}
   168  	pass := strings.TrimSuffix(string(blob), "\n")
   169  
   170  	ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
   171  	if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
   172  		log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
   173  	}
   174  	acc, err := ks.Import(blob, pass, pass)
   175  	if err != nil && err != keystore.ErrAccountAlreadyExists {
   176  		log.Crit("Failed to import faucet signer account", "err", err)
   177  	}
   178  	if err := ks.Unlock(acc, pass); err != nil {
   179  		log.Crit("Failed to unlock faucet signer account", "err", err)
   180  	}
   181  	// Assemble and start the faucet light service
   182  	faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
   183  	if err != nil {
   184  		log.Crit("Failed to start faucet", "err", err)
   185  	}
   186  	defer faucet.close()
   187  
   188  	if err := faucet.listenAndServe(*apiPortFlag); err != nil {
   189  		log.Crit("Failed to launch faucet API", "err", err)
   190  	}
   191  }
   192  
   193  // request represents an accepted funding request.
   194  type request struct {
   195  	Avatar  string             `json:"avatar"`  // Avatar URL to make the UI nicer
   196  	Account common.Address     `json:"account"` // Ethereum address being funded
   197  	Time    time.Time          `json:"time"`    // Timestamp when the request was accepted
   198  	Tx      *types.Transaction `json:"tx"`      // Transaction funding the account
   199  }
   200  
   201  // faucet represents a crypto faucet backed by an Ethereum light client.
   202  type faucet struct {
   203  	config *params.ChainConfig // Chain configurations for signing
   204  	stack  *node.Node          // Ethereum protocol stack
   205  	client *ethclient.Client   // Client connection to the Ethereum chain
   206  	index  []byte              // Index page to serve up on the web
   207  
   208  	keystore *keystore.KeyStore // Keystore containing the single signer
   209  	account  accounts.Account   // Account funding user faucet requests
   210  	head     *types.Header      // Current head header of the faucet
   211  	balance  *big.Int           // Current balance of the faucet
   212  	nonce    uint64             // Current pending nonce of the faucet
   213  	price    *big.Int           // Current gas price to issue funds with
   214  
   215  	conns    []*websocket.Conn    // Currently live websocket connections
   216  	timeouts map[string]time.Time // History of users and their funding timeouts
   217  	reqs     []*request           // Currently pending funding requests
   218  	update   chan struct{}        // Channel to signal request updates
   219  
   220  	lock sync.RWMutex // Lock protecting the faucet's internals
   221  }
   222  
   223  func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
   224  	// Assemble the raw devp2p protocol stack
   225  	stack, err := node.New(&node.Config{
   226  		Name:    "geth",
   227  		Version: params.VersionWithCommit(gitCommit, gitDate),
   228  		DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
   229  		P2P: p2p.Config{
   230  			NAT:              nat.Any(),
   231  			NoDiscovery:      true,
   232  			DiscoveryV5:      true,
   233  			ListenAddr:       fmt.Sprintf(":%d", port),
   234  			MaxPeers:         25,
   235  			BootstrapNodesV5: enodes,
   236  		},
   237  	})
   238  	if err != nil {
   239  		return nil, err
   240  	}
   241  
   242  	// Assemble the Ethereum light client protocol
   243  	cfg := eth.DefaultConfig
   244  	cfg.SyncMode = downloader.LightSync
   245  	cfg.NetworkId = network
   246  	cfg.Genesis = genesis
   247  	utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock(nil).Hash())
   248  	lesBackend, err := les.New(stack, &cfg)
   249  	if err != nil {
   250  		return nil, fmt.Errorf("Failed to register the Ethereum service: %w", err)
   251  	}
   252  
   253  	// Assemble the ethstats monitoring and reporting service'
   254  	if stats != "" {
   255  		if err := ethstats.New(stack, lesBackend.ApiBackend, lesBackend.Engine(), stats); err != nil {
   256  			return nil, err
   257  		}
   258  	}
   259  	// Boot up the client and ensure it connects to bootnodes
   260  	if err := stack.Start(); err != nil {
   261  		return nil, err
   262  	}
   263  	for _, boot := range enodes {
   264  		old, err := enode.Parse(enode.ValidSchemes, boot.String())
   265  		if err == nil {
   266  			stack.Server().AddPeer(old)
   267  		}
   268  	}
   269  	// Attach to the client and retrieve and interesting metadatas
   270  	api, err := stack.Attach()
   271  	if err != nil {
   272  		stack.Close()
   273  		return nil, err
   274  	}
   275  	client := ethclient.NewClient(api)
   276  
   277  	return &faucet{
   278  		config:   genesis.Config,
   279  		stack:    stack,
   280  		client:   client,
   281  		index:    index,
   282  		keystore: ks,
   283  		account:  ks.Accounts()[0],
   284  		timeouts: make(map[string]time.Time),
   285  		update:   make(chan struct{}, 1),
   286  	}, nil
   287  }
   288  
   289  // close terminates the Ethereum connection and tears down the faucet.
   290  func (f *faucet) close() error {
   291  	return f.stack.Close()
   292  }
   293  
   294  // listenAndServe registers the HTTP handlers for the faucet and boots it up
   295  // for service user funding requests.
   296  func (f *faucet) listenAndServe(port int) error {
   297  	go f.loop()
   298  
   299  	http.HandleFunc("/", f.webHandler)
   300  	http.HandleFunc("/api", f.apiHandler)
   301  	return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
   302  }
   303  
   304  // webHandler handles all non-api requests, simply flattening and returning the
   305  // faucet website.
   306  func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
   307  	w.Write(f.index)
   308  }
   309  
   310  // apiHandler handles requests for Ether grants and transaction statuses.
   311  func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
   312  	upgrader := websocket.Upgrader{}
   313  	conn, err := upgrader.Upgrade(w, r, nil)
   314  	if err != nil {
   315  		return
   316  	}
   317  
   318  	// Start tracking the connection and drop at the end
   319  	defer conn.Close()
   320  
   321  	f.lock.Lock()
   322  	f.conns = append(f.conns, conn)
   323  	f.lock.Unlock()
   324  
   325  	defer func() {
   326  		f.lock.Lock()
   327  		for i, c := range f.conns {
   328  			if c == conn {
   329  				f.conns = append(f.conns[:i], f.conns[i+1:]...)
   330  				break
   331  			}
   332  		}
   333  		f.lock.Unlock()
   334  	}()
   335  	// Gather the initial stats from the network to report
   336  	var (
   337  		head    *types.Header
   338  		balance *big.Int
   339  		nonce   uint64
   340  	)
   341  	for head == nil || balance == nil {
   342  		// Retrieve the current stats cached by the faucet
   343  		f.lock.RLock()
   344  		if f.head != nil {
   345  			head = types.CopyHeader(f.head)
   346  		}
   347  		if f.balance != nil {
   348  			balance = new(big.Int).Set(f.balance)
   349  		}
   350  		nonce = f.nonce
   351  		f.lock.RUnlock()
   352  
   353  		if head == nil || balance == nil {
   354  			// Report the faucet offline until initial stats are ready
   355  			//lint:ignore ST1005 This error is to be displayed in the browser
   356  			if err = sendError(conn, errors.New("Faucet offline")); err != nil {
   357  				log.Warn("Failed to send faucet error to client", "err", err)
   358  				return
   359  			}
   360  			time.Sleep(3 * time.Second)
   361  		}
   362  	}
   363  	// Send over the initial stats and the latest header
   364  	f.lock.RLock()
   365  	reqs := f.reqs
   366  	f.lock.RUnlock()
   367  	if err = send(conn, map[string]interface{}{
   368  		"funds":    new(big.Int).Div(balance, ether),
   369  		"funded":   nonce,
   370  		"peers":    f.stack.Server().PeerCount(),
   371  		"requests": reqs,
   372  	}, 3*time.Second); err != nil {
   373  		log.Warn("Failed to send initial stats to client", "err", err)
   374  		return
   375  	}
   376  	if err = send(conn, head, 3*time.Second); err != nil {
   377  		log.Warn("Failed to send initial header to client", "err", err)
   378  		return
   379  	}
   380  	// Keep reading requests from the websocket until the connection breaks
   381  	for {
   382  		// Fetch the next funding request and validate against github
   383  		var msg struct {
   384  			URL     string `json:"url"`
   385  			Tier    uint   `json:"tier"`
   386  			Captcha string `json:"captcha"`
   387  		}
   388  		if err = conn.ReadJSON(&msg); err != nil {
   389  			return
   390  		}
   391  		if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
   392  			!strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
   393  			if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil {
   394  				log.Warn("Failed to send URL error to client", "err", err)
   395  				return
   396  			}
   397  			continue
   398  		}
   399  		if msg.Tier >= uint(*tiersFlag) {
   400  			//lint:ignore ST1005 This error is to be displayed in the browser
   401  			if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil {
   402  				log.Warn("Failed to send tier error to client", "err", err)
   403  				return
   404  			}
   405  			continue
   406  		}
   407  		log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier)
   408  
   409  		// If captcha verifications are enabled, make sure we're not dealing with a robot
   410  		if *captchaToken != "" {
   411  			form := url.Values{}
   412  			form.Add("secret", *captchaSecret)
   413  			form.Add("response", msg.Captcha)
   414  
   415  			res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
   416  			if err != nil {
   417  				if err = sendError(conn, err); err != nil {
   418  					log.Warn("Failed to send captcha post error to client", "err", err)
   419  					return
   420  				}
   421  				continue
   422  			}
   423  			var result struct {
   424  				Success bool            `json:"success"`
   425  				Errors  json.RawMessage `json:"error-codes"`
   426  			}
   427  			err = json.NewDecoder(res.Body).Decode(&result)
   428  			res.Body.Close()
   429  			if err != nil {
   430  				if err = sendError(conn, err); err != nil {
   431  					log.Warn("Failed to send captcha decode error to client", "err", err)
   432  					return
   433  				}
   434  				continue
   435  			}
   436  			if !result.Success {
   437  				log.Warn("Captcha verification failed", "err", string(result.Errors))
   438  				//lint:ignore ST1005 it's funny and the robot won't mind
   439  				if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil {
   440  					log.Warn("Failed to send captcha failure to client", "err", err)
   441  					return
   442  				}
   443  				continue
   444  			}
   445  		}
   446  		// Retrieve the Ethereum address to fund, the requesting user and a profile picture
   447  		var (
   448  			id       string
   449  			username string
   450  			avatar   string
   451  			address  common.Address
   452  		)
   453  		switch {
   454  		case strings.HasPrefix(msg.URL, "https://gist.github.com/"):
   455  			if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil {
   456  				log.Warn("Failed to send GitHub deprecation to client", "err", err)
   457  				return
   458  			}
   459  			continue
   460  		case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
   461  			//lint:ignore ST1005 Google is a company name and should be capitalized.
   462  			if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil {
   463  				log.Warn("Failed to send Google+ deprecation to client", "err", err)
   464  				return
   465  			}
   466  			continue
   467  		case strings.HasPrefix(msg.URL, "https://twitter.com/"):
   468  			id, username, avatar, address, err = authTwitter(msg.URL, *twitterBearerToken)
   469  		case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
   470  			username, avatar, address, err = authFacebook(msg.URL)
   471  			id = username
   472  		case *noauthFlag:
   473  			username, avatar, address, err = authNoAuth(msg.URL)
   474  			id = username
   475  		default:
   476  			//lint:ignore ST1005 This error is to be displayed in the browser
   477  			err = errors.New("Something funky happened, please open an issue at https://github.com/CommerciumBlockchain/go-commercium/issues")
   478  		}
   479  		if err != nil {
   480  			if err = sendError(conn, err); err != nil {
   481  				log.Warn("Failed to send prefix error to client", "err", err)
   482  				return
   483  			}
   484  			continue
   485  		}
   486  		log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address)
   487  
   488  		// Ensure the user didn't request funds too recently
   489  		f.lock.Lock()
   490  		var (
   491  			fund    bool
   492  			timeout time.Time
   493  		)
   494  		if timeout = f.timeouts[id]; time.Now().After(timeout) {
   495  			// User wasn't funded recently, create the funding transaction
   496  			amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
   497  			amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
   498  			amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil))
   499  
   500  			tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil)
   501  			signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID)
   502  			if err != nil {
   503  				f.lock.Unlock()
   504  				if err = sendError(conn, err); err != nil {
   505  					log.Warn("Failed to send transaction creation error to client", "err", err)
   506  					return
   507  				}
   508  				continue
   509  			}
   510  			// Submit the transaction and mark as funded if successful
   511  			if err := f.client.SendTransaction(context.Background(), signed); err != nil {
   512  				f.lock.Unlock()
   513  				if err = sendError(conn, err); err != nil {
   514  					log.Warn("Failed to send transaction transmission error to client", "err", err)
   515  					return
   516  				}
   517  				continue
   518  			}
   519  			f.reqs = append(f.reqs, &request{
   520  				Avatar:  avatar,
   521  				Account: address,
   522  				Time:    time.Now(),
   523  				Tx:      signed,
   524  			})
   525  			timeout := time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute
   526  			grace := timeout / 288 // 24h timeout => 5m grace
   527  
   528  			f.timeouts[id] = time.Now().Add(timeout - grace)
   529  			fund = true
   530  		}
   531  		f.lock.Unlock()
   532  
   533  		// Send an error if too frequent funding, othewise a success
   534  		if !fund {
   535  			if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(time.Until(timeout)))); err != nil { // nolint: gosimple
   536  				log.Warn("Failed to send funding error to client", "err", err)
   537  				return
   538  			}
   539  			continue
   540  		}
   541  		if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil {
   542  			log.Warn("Failed to send funding success to client", "err", err)
   543  			return
   544  		}
   545  		select {
   546  		case f.update <- struct{}{}:
   547  		default:
   548  		}
   549  	}
   550  }
   551  
   552  // refresh attempts to retrieve the latest header from the chain and extract the
   553  // associated faucet balance and nonce for connectivity caching.
   554  func (f *faucet) refresh(head *types.Header) error {
   555  	// Ensure a state update does not run for too long
   556  	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
   557  	defer cancel()
   558  
   559  	// If no header was specified, use the current chain head
   560  	var err error
   561  	if head == nil {
   562  		if head, err = f.client.HeaderByNumber(ctx, nil); err != nil {
   563  			return err
   564  		}
   565  	}
   566  	// Retrieve the balance, nonce and gas price from the current head
   567  	var (
   568  		balance *big.Int
   569  		nonce   uint64
   570  		price   *big.Int
   571  	)
   572  	if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil {
   573  		return err
   574  	}
   575  	if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil {
   576  		return err
   577  	}
   578  	if price, err = f.client.SuggestGasPrice(ctx); err != nil {
   579  		return err
   580  	}
   581  	// Everything succeeded, update the cached stats and eject old requests
   582  	f.lock.Lock()
   583  	f.head, f.balance = head, balance
   584  	f.price, f.nonce = price, nonce
   585  	for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
   586  		f.reqs = f.reqs[1:]
   587  	}
   588  	f.lock.Unlock()
   589  
   590  	return nil
   591  }
   592  
   593  // loop keeps waiting for interesting events and pushes them out to connected
   594  // websockets.
   595  func (f *faucet) loop() {
   596  	// Wait for chain events and push them to clients
   597  	heads := make(chan *types.Header, 16)
   598  	sub, err := f.client.SubscribeNewHead(context.Background(), heads)
   599  	if err != nil {
   600  		log.Crit("Failed to subscribe to head events", "err", err)
   601  	}
   602  	defer sub.Unsubscribe()
   603  
   604  	// Start a goroutine to update the state from head notifications in the background
   605  	update := make(chan *types.Header)
   606  
   607  	go func() {
   608  		for head := range update {
   609  			// New chain head arrived, query the current stats and stream to clients
   610  			timestamp := time.Unix(int64(head.Time), 0)
   611  			if time.Since(timestamp) > time.Hour {
   612  				log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp))
   613  				continue
   614  			}
   615  			if err := f.refresh(head); err != nil {
   616  				log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err)
   617  				continue
   618  			}
   619  			// Faucet state retrieved, update locally and send to clients
   620  			f.lock.RLock()
   621  			log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price)
   622  
   623  			balance := new(big.Int).Div(f.balance, ether)
   624  			peers := f.stack.Server().PeerCount()
   625  
   626  			for _, conn := range f.conns {
   627  				if err := send(conn, map[string]interface{}{
   628  					"funds":    balance,
   629  					"funded":   f.nonce,
   630  					"peers":    peers,
   631  					"requests": f.reqs,
   632  				}, time.Second); err != nil {
   633  					log.Warn("Failed to send stats to client", "err", err)
   634  					conn.Close()
   635  					continue
   636  				}
   637  				if err := send(conn, head, time.Second); err != nil {
   638  					log.Warn("Failed to send header to client", "err", err)
   639  					conn.Close()
   640  				}
   641  			}
   642  			f.lock.RUnlock()
   643  		}
   644  	}()
   645  	// Wait for various events and assing to the appropriate background threads
   646  	for {
   647  		select {
   648  		case head := <-heads:
   649  			// New head arrived, send if for state update if there's none running
   650  			select {
   651  			case update <- head:
   652  			default:
   653  			}
   654  
   655  		case <-f.update:
   656  			// Pending requests updated, stream to clients
   657  			f.lock.RLock()
   658  			for _, conn := range f.conns {
   659  				if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
   660  					log.Warn("Failed to send requests to client", "err", err)
   661  					conn.Close()
   662  				}
   663  			}
   664  			f.lock.RUnlock()
   665  		}
   666  	}
   667  }
   668  
   669  // sends transmits a data packet to the remote end of the websocket, but also
   670  // setting a write deadline to prevent waiting forever on the node.
   671  func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
   672  	if timeout == 0 {
   673  		timeout = 60 * time.Second
   674  	}
   675  	conn.SetWriteDeadline(time.Now().Add(timeout))
   676  	return conn.WriteJSON(value)
   677  }
   678  
   679  // sendError transmits an error to the remote end of the websocket, also setting
   680  // the write deadline to 1 second to prevent waiting forever.
   681  func sendError(conn *websocket.Conn, err error) error {
   682  	return send(conn, map[string]string{"error": err.Error()}, time.Second)
   683  }
   684  
   685  // sendSuccess transmits a success message to the remote end of the websocket, also
   686  // setting the write deadline to 1 second to prevent waiting forever.
   687  func sendSuccess(conn *websocket.Conn, msg string) error {
   688  	return send(conn, map[string]string{"success": msg}, time.Second)
   689  }
   690  
   691  // authTwitter tries to authenticate a faucet request using Twitter posts, returning
   692  // the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success.
   693  func authTwitter(url string, token string) (string, string, string, common.Address, error) {
   694  	// Ensure the user specified a meaningful URL, no fancy nonsense
   695  	parts := strings.Split(url, "/")
   696  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   697  		//lint:ignore ST1005 This error is to be displayed in the browser
   698  		return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   699  	}
   700  
   701  	// Twitter's API isn't really friendly with direct links.
   702  	// It is restricted to 300 queries / 15 minute with an app api key.
   703  	// Anything more will require read only authorization from the users and that we want to avoid.
   704  
   705  	// If twitter bearer token is provided, use the twitter api
   706  	if token != "" {
   707  		return authTwitterWithToken(parts[len(parts)-1], token)
   708  	}
   709  
   710  	// Twiter API token isn't provided so we just load the public posts
   711  	// and scrape it for the Ethereum address and profile URL. We need to load
   712  	// the mobile page though since the main page loads tweet contents via JS.
   713  	url = strings.Replace(url, "https://twitter.com/", "https://mobile.twitter.com/", 1)
   714  
   715  	res, err := http.Get(url)
   716  	if err != nil {
   717  		return "", "", "", common.Address{}, err
   718  	}
   719  	defer res.Body.Close()
   720  
   721  	// Resolve the username from the final redirect, no intermediate junk
   722  	parts = strings.Split(res.Request.URL.String(), "/")
   723  	if len(parts) < 4 || parts[len(parts)-2] != "status" {
   724  		//lint:ignore ST1005 This error is to be displayed in the browser
   725  		return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
   726  	}
   727  	username := parts[len(parts)-3]
   728  
   729  	body, err := ioutil.ReadAll(res.Body)
   730  	if err != nil {
   731  		return "", "", "", common.Address{}, err
   732  	}
   733  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   734  	if address == (common.Address{}) {
   735  		//lint:ignore ST1005 This error is to be displayed in the browser
   736  		return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   737  	}
   738  	var avatar string
   739  	if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   740  		avatar = parts[1]
   741  	}
   742  	return username + "@twitter", username, avatar, address, nil
   743  }
   744  
   745  // authTwitterWithToken tries to authenticate a faucet request using Twitter's API, returning
   746  // the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success.
   747  func authTwitterWithToken(tweetID string, token string) (string, string, string, common.Address, error) {
   748  	// Strip any query parameters from the tweet id
   749  	sanitizedTweetID := strings.Split(tweetID, "?")[0]
   750  
   751  	// Ensure numeric tweetID
   752  	if !regexp.MustCompile("^[0-9]+$").MatchString(sanitizedTweetID) {
   753  		return "", "", "", common.Address{}, errors.New("Invalid Tweet URL")
   754  	}
   755  
   756  	// Query the tweet details from Twitter
   757  	url := fmt.Sprintf("https://api.twitter.com/2/tweets/%s?expansions=author_id&user.fields=profile_image_url", sanitizedTweetID)
   758  	req, err := http.NewRequest("GET", url, nil)
   759  	if err != nil {
   760  		return "", "", "", common.Address{}, err
   761  	}
   762  	req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
   763  	res, err := http.DefaultClient.Do(req)
   764  	if err != nil {
   765  		return "", "", "", common.Address{}, err
   766  	}
   767  	defer res.Body.Close()
   768  
   769  	var result struct {
   770  		Data struct {
   771  			AuthorID string `json:"author_id"`
   772  			ID       string `json:"id"`
   773  			Text     string `json:"text"`
   774  		} `json:"data"`
   775  		Includes struct {
   776  			Users []struct {
   777  				ProfileImageURL string `json:"profile_image_url"`
   778  				Username        string `json:"username"`
   779  				ID              string `json:"id"`
   780  				Name            string `json:"name"`
   781  			} `json:"users"`
   782  		} `json:"includes"`
   783  	}
   784  
   785  	err = json.NewDecoder(res.Body).Decode(&result)
   786  	if err != nil {
   787  		return "", "", "", common.Address{}, err
   788  	}
   789  
   790  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Data.Text))
   791  	if address == (common.Address{}) {
   792  		//lint:ignore ST1005 This error is to be displayed in the browser
   793  		return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   794  	}
   795  	return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].ProfileImageURL, address, nil
   796  }
   797  
   798  // authFacebook tries to authenticate a faucet request using Facebook posts,
   799  // returning the username, avatar URL and Ethereum address to fund on success.
   800  func authFacebook(url string) (string, string, common.Address, error) {
   801  	// Ensure the user specified a meaningful URL, no fancy nonsense
   802  	parts := strings.Split(strings.Split(url, "?")[0], "/")
   803  	if parts[len(parts)-1] == "" {
   804  		parts = parts[0 : len(parts)-1]
   805  	}
   806  	if len(parts) < 4 || parts[len(parts)-2] != "posts" {
   807  		//lint:ignore ST1005 This error is to be displayed in the browser
   808  		return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
   809  	}
   810  	username := parts[len(parts)-3]
   811  
   812  	// Facebook's Graph API isn't really friendly with direct links. Still, we don't
   813  	// want to do ask read permissions from users, so just load the public posts and
   814  	// scrape it for the Ethereum address and profile URL.
   815  	res, err := http.Get(url)
   816  	if err != nil {
   817  		return "", "", common.Address{}, err
   818  	}
   819  	defer res.Body.Close()
   820  
   821  	body, err := ioutil.ReadAll(res.Body)
   822  	if err != nil {
   823  		return "", "", common.Address{}, err
   824  	}
   825  	address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
   826  	if address == (common.Address{}) {
   827  		//lint:ignore ST1005 This error is to be displayed in the browser
   828  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   829  	}
   830  	var avatar string
   831  	if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
   832  		avatar = parts[1]
   833  	}
   834  	return username + "@facebook", avatar, address, nil
   835  }
   836  
   837  // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
   838  // without actually performing any remote authentication. This mode is prone to
   839  // Byzantine attack, so only ever use for truly private networks.
   840  func authNoAuth(url string) (string, string, common.Address, error) {
   841  	address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
   842  	if address == (common.Address{}) {
   843  		//lint:ignore ST1005 This error is to be displayed in the browser
   844  		return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
   845  	}
   846  	return address.Hex() + "@noauth", "", address, nil
   847  }