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