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