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