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