github.com/waltonchain/waltonchain_gwtc_src@v1.1.4-0.20201225072101-8a298c95a819/cmd/faucet/faucet.go (about)

     1  // Copyright 2017 The go-ethereum Authors
     2  // This file is part of go-wtc.
     3  //
     4  // go-wtc 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-wtc 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-wtc. 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  
    22  import (
    23  	"bytes"
    24  	"context"
    25  	"encoding/json"
    26  	"flag"
    27  	"fmt"
    28  	"html/template"
    29  	"io/ioutil"
    30  	"math"
    31  	"math/big"
    32  	"net/http"
    33  	"net/url"
    34  	"os"
    35  	"path/filepath"
    36  	"strconv"
    37  	"strings"
    38  	"sync"
    39  	"time"
    40  
    41  	"github.com/wtc/go-wtc/accounts"
    42  	"github.com/wtc/go-wtc/accounts/keystore"
    43  	"github.com/wtc/go-wtc/common"
    44  	"github.com/wtc/go-wtc/core"
    45  	"github.com/wtc/go-wtc/core/types"
    46  	"github.com/wtc/go-wtc/wtc"
    47  	"github.com/wtc/go-wtc/wtc/downloader"
    48  	"github.com/wtc/go-wtc/wtcclient"
    49  	"github.com/wtc/go-wtc/wtcstats"
    50  	"github.com/wtc/go-wtc/les"
    51  	"github.com/wtc/go-wtc/log"
    52  	"github.com/wtc/go-wtc/node"
    53  	"github.com/wtc/go-wtc/p2p"
    54  	"github.com/wtc/go-wtc/p2p/discover"
    55  	"github.com/wtc/go-wtc/p2p/discv5"
    56  	"github.com/wtc/go-wtc/p2p/nat"
    57  	"github.com/wtc/go-wtc/params"
    58  	"golang.org/x/net/websocket"
    59  )
    60  
    61  var (
    62  	genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with")
    63  	apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection")
    64  	ethPortFlag = flag.Int("ethport", 10101, "Listener port for the devp2p connection")
    65  	bootFlag    = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with")
    66  	netFlag     = flag.Uint64("network", 0, "Network ID to use for the Wtc protocol")
    67  	statsFlag   = flag.String("ethstats", "", "Ethstats network monitoring auth string")
    68  
    69  	netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet")
    70  	payoutFlag  = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request")
    71  	minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds")
    72  	tiersFlag   = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)")
    73  
    74  	accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with")
    75  	accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds")
    76  
    77  	githubUser  = flag.String("github.user", "", "GitHub user to authenticate with for Gist access")
    78  	githubToken = flag.String("github.token", "", "GitHub personal token to access Gists with")
    79  
    80  	captchaToken  = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side")
    81  	captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side")
    82  
    83  	logFlag = flag.Int("loglevel", 3, "Log level to use for Wtc and the faucet")
    84  )
    85  
    86  var (
    87  	ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
    88  )
    89  
    90  func main() {
    91  	// Parse the flags and set up the logger to print everything requested
    92  	flag.Parse()
    93  	log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
    94  
    95  	// Construct the payout tiers
    96  	amounts := make([]string, *tiersFlag)
    97  	periods := make([]string, *tiersFlag)
    98  	for i := 0; i < *tiersFlag; i++ {
    99  		// Calculate the amount for the next tier and format it
   100  		amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
   101  		amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
   102  		if amount == 1 {
   103  			amounts[i] = strings.TrimSuffix(amounts[i], "s")
   104  		}
   105  		// Calculate the period for the next tier and format it
   106  		period := *minutesFlag * int(math.Pow(3, float64(i)))
   107  		periods[i] = fmt.Sprintf("%d mins", period)
   108  		if period%60 == 0 {
   109  			period /= 60
   110  			periods[i] = fmt.Sprintf("%d hours", period)
   111  
   112  			if period%24 == 0 {
   113  				period /= 24
   114  				periods[i] = fmt.Sprintf("%d days", period)
   115  			}
   116  		}
   117  		if period == 1 {
   118  			periods[i] = strings.TrimSuffix(periods[i], "s")
   119  		}
   120  	}
   121  	// Load up and render the faucet website
   122  	tmpl, err := Asset("faucet.html")
   123  	if err != nil {
   124  		log.Crit("Failed to load the faucet template", "err", err)
   125  	}
   126  	website := new(bytes.Buffer)
   127  	err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
   128  		"Network":   *netnameFlag,
   129  		"Amounts":   amounts,
   130  		"Periods":   periods,
   131  		"Recaptcha": *captchaToken,
   132  	})
   133  	if err != nil {
   134  		log.Crit("Failed to render the faucet template", "err", err)
   135  	}
   136  	// Load and parse the genesis block requested by the user
   137  	blob, err := ioutil.ReadFile(*genesisFlag)
   138  	if err != nil {
   139  		log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
   140  	}
   141  	genesis := new(core.Genesis)
   142  	if err = json.Unmarshal(blob, genesis); err != nil {
   143  		log.Crit("Failed to parse genesis block json", "err", err)
   144  	}
   145  	// Convert the bootnodes to internal enode representations
   146  	var enodes []*discv5.Node
   147  	for _, boot := range strings.Split(*bootFlag, ",") {
   148  		if url, err := discv5.ParseNode(boot); err == nil {
   149  			enodes = append(enodes, url)
   150  		} else {
   151  			log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
   152  		}
   153  	}
   154  	// Load up the account key and decrypt its password
   155  	if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
   156  		log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
   157  	}
   158  	pass := string(blob)
   159  
   160  	ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
   161  	if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
   162  		log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
   163  	}
   164  	acc, err := ks.Import(blob, pass, pass)
   165  	if err != nil {
   166  		log.Crit("Failed to import faucet signer account", "err", err)
   167  	}
   168  	ks.Unlock(acc, pass)
   169  
   170  	// Assemble and start the faucet light service
   171  	faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
   172  	if err != nil {
   173  		log.Crit("Failed to start faucet", "err", err)
   174  	}
   175  	defer faucet.close()
   176  
   177  	if err := faucet.listenAndServe(*apiPortFlag); err != nil {
   178  		log.Crit("Failed to launch faucet API", "err", err)
   179  	}
   180  }
   181  
   182  // request represents an accepted funding request.
   183  type request struct {
   184  	Username string             `json:"username"` // GitHub user for displaying an avatar
   185  	Account  common.Address     `json:"account"`  // Wtc address being funded
   186  	Time     time.Time          `json:"time"`     // Timestamp when te request was accepted
   187  	Tx       *types.Transaction `json:"tx"`       // Transaction funding the account
   188  }
   189  
   190  // faucet represents a crypto faucet backed by an Wtc light client.
   191  type faucet struct {
   192  	config *params.ChainConfig // Chain configurations for signing
   193  	stack  *node.Node          // Wtc protocol stack
   194  	client *wtcclient.Client   // Client connection to the Wtc chain
   195  	index  []byte              // Index page to serve up on the web
   196  
   197  	keystore *keystore.KeyStore // Keystore containing the single signer
   198  	account  accounts.Account   // Account funding user faucet requests
   199  	nonce    uint64             // Current pending nonce of the faucet
   200  	price    *big.Int           // Current gas price to issue funds with
   201  
   202  	conns    []*websocket.Conn    // Currently live websocket connections
   203  	timeouts map[string]time.Time // History of users and their funding timeouts
   204  	reqs     []*request           // Currently pending funding requests
   205  	update   chan struct{}        // Channel to signal request updates
   206  
   207  	lock sync.RWMutex // Lock protecting the faucet's internals
   208  }
   209  
   210  func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
   211  	// Assemble the raw devp2p protocol stack
   212  	stack, err := node.New(&node.Config{
   213  		Name:    "gwtc",
   214  		Version: params.Version,
   215  		DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
   216  		P2P: p2p.Config{
   217  			NAT:              nat.Any(),
   218  			NoDiscovery:      true,
   219  			DiscoveryV5:      true,
   220  			ListenAddr:       fmt.Sprintf(":%d", port),
   221  			DiscoveryV5Addr:  fmt.Sprintf(":%d", port+1),
   222  			MaxPeers:         25,
   223  			BootstrapNodesV5: enodes,
   224  		},
   225  	})
   226  	if err != nil {
   227  		return nil, err
   228  	}
   229  	// Assemble the Wtc light client protocol
   230  	if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   231  		cfg := eth.DefaultConfig
   232  		cfg.SyncMode = downloader.LightSync
   233  		cfg.NetworkId = network
   234  		cfg.Genesis = genesis
   235  		return les.New(ctx, &cfg)
   236  	}); err != nil {
   237  		return nil, err
   238  	}
   239  	// Assemble the ethstats monitoring and reporting service'
   240  	if stats != "" {
   241  		if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
   242  			var serv *les.LightWtc
   243  			ctx.Service(&serv)
   244  			return ethstats.New(stats, nil, serv)
   245  		}); err != nil {
   246  			return nil, err
   247  		}
   248  	}
   249  	// Boot up the client and ensure it connects to bootnodes
   250  	if err := stack.Start(); err != nil {
   251  		return nil, err
   252  	}
   253  	for _, boot := range enodes {
   254  		old, _ := discover.ParseNode(boot.String())
   255  		stack.Server().AddPeer(old)
   256  	}
   257  	// Attach to the client and retrieve and interesting metadatas
   258  	api, err := stack.Attach()
   259  	if err != nil {
   260  		stack.Stop()
   261  		return nil, err
   262  	}
   263  	client := wtcclient.NewClient(api)
   264  
   265  	return &faucet{
   266  		config:   genesis.Config,
   267  		stack:    stack,
   268  		client:   client,
   269  		index:    index,
   270  		keystore: ks,
   271  		account:  ks.Accounts()[0],
   272  		timeouts: make(map[string]time.Time),
   273  		update:   make(chan struct{}, 1),
   274  	}, nil
   275  }
   276  
   277  // close terminates the Wtc connection and tears down the faucet.
   278  func (f *faucet) close() error {
   279  	return f.stack.Stop()
   280  }
   281  
   282  // listenAndServe registers the HTTP handlers for the faucet and boots it up
   283  // for service user funding requests.
   284  func (f *faucet) listenAndServe(port int) error {
   285  	go f.loop()
   286  
   287  	http.HandleFunc("/", f.webHandler)
   288  	http.Handle("/api", websocket.Handler(f.apiHandler))
   289  
   290  	return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
   291  }
   292  
   293  // webHandler handles all non-api requests, simply flattening and returning the
   294  // faucet website.
   295  func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
   296  	w.Write(f.index)
   297  }
   298  
   299  // apiHandler handles requests for Ether grants and transaction statuses.
   300  func (f *faucet) apiHandler(conn *websocket.Conn) {
   301  	// Start tracking the connection and drop at the end
   302  	f.lock.Lock()
   303  	f.conns = append(f.conns, conn)
   304  	f.lock.Unlock()
   305  
   306  	defer func() {
   307  		f.lock.Lock()
   308  		for i, c := range f.conns {
   309  			if c == conn {
   310  				f.conns = append(f.conns[:i], f.conns[i+1:]...)
   311  				break
   312  			}
   313  		}
   314  		f.lock.Unlock()
   315  	}()
   316  	// Send a few initial stats to the client
   317  	balance, _ := f.client.BalanceAt(context.Background(), f.account.Address, nil)
   318  	nonce, _ := f.client.NonceAt(context.Background(), f.account.Address, nil)
   319  
   320  	websocket.JSON.Send(conn, map[string]interface{}{
   321  		"funds":    balance.Div(balance, ether),
   322  		"funded":   nonce,
   323  		"peers":    f.stack.Server().PeerCount(),
   324  		"requests": f.reqs,
   325  	})
   326  	// Send the initial block to the client
   327  	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
   328  	header, err := f.client.HeaderByNumber(ctx, nil)
   329  	cancel()
   330  
   331  	if err != nil {
   332  		log.Error("Failed to retrieve latest header", "err", err)
   333  	} else {
   334  		websocket.JSON.Send(conn, header)
   335  	}
   336  	// Keep reading requests from the websocket until the connection breaks
   337  	for {
   338  		// Fetch the next funding request and validate against github
   339  		var msg struct {
   340  			URL     string `json:"url"`
   341  			Tier    uint   `json:"tier"`
   342  			Captcha string `json:"captcha"`
   343  		}
   344  		if err := websocket.JSON.Receive(conn, &msg); err != nil {
   345  			return
   346  		}
   347  		if !strings.HasPrefix(msg.URL, "https://gist.github.com/") {
   348  			websocket.JSON.Send(conn, map[string]string{"error": "URL doesn't link to GitHub Gists"})
   349  			continue
   350  		}
   351  		if msg.Tier >= uint(*tiersFlag) {
   352  			websocket.JSON.Send(conn, map[string]string{"error": "Invalid funding tier requested"})
   353  			continue
   354  		}
   355  		log.Info("Faucet funds requested", "gist", msg.URL, "tier", msg.Tier)
   356  
   357  		// If captcha verifications are enabled, make sure we're not dealing with a robot
   358  		if *captchaToken != "" {
   359  			form := url.Values{}
   360  			form.Add("secret", *captchaSecret)
   361  			form.Add("response", msg.Captcha)
   362  
   363  			res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
   364  			if err != nil {
   365  				websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   366  				continue
   367  			}
   368  			var result struct {
   369  				Success bool            `json:"success"`
   370  				Errors  json.RawMessage `json:"error-codes"`
   371  			}
   372  			err = json.NewDecoder(res.Body).Decode(&result)
   373  			res.Body.Close()
   374  			if err != nil {
   375  				websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   376  				continue
   377  			}
   378  			if !result.Success {
   379  				log.Warn("Captcha verification failed", "err", string(result.Errors))
   380  				websocket.JSON.Send(conn, map[string]string{"error": "Beep-bop, you're a robot!"})
   381  				continue
   382  			}
   383  		}
   384  		// Retrieve the gist from the GitHub Gist APIs
   385  		parts := strings.Split(msg.URL, "/")
   386  		req, _ := http.NewRequest("GET", "https://api.github.com/gists/"+parts[len(parts)-1], nil)
   387  		if *githubUser != "" {
   388  			req.SetBasicAuth(*githubUser, *githubToken)
   389  		}
   390  		res, err := http.DefaultClient.Do(req)
   391  		if err != nil {
   392  			websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   393  			continue
   394  		}
   395  		var gist struct {
   396  			Owner struct {
   397  				Login string `json:"login"`
   398  			} `json:"owner"`
   399  			Files map[string]struct {
   400  				Content string `json:"content"`
   401  			} `json:"files"`
   402  		}
   403  		err = json.NewDecoder(res.Body).Decode(&gist)
   404  		res.Body.Close()
   405  		if err != nil {
   406  			websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   407  			continue
   408  		}
   409  		if gist.Owner.Login == "" {
   410  			websocket.JSON.Send(conn, map[string]string{"error": "Anonymous Gists not allowed"})
   411  			continue
   412  		}
   413  		// Iterate over all the files and look for Wtc addresses
   414  		var address common.Address
   415  		for _, file := range gist.Files {
   416  			content := strings.TrimSpace(file.Content)
   417  			if len(content) == 2+common.AddressLength*2 {
   418  				address = common.HexToAddress(content)
   419  			}
   420  		}
   421  		if address == (common.Address{}) {
   422  			websocket.JSON.Send(conn, map[string]string{"error": "No Wtc address found to fund"})
   423  			continue
   424  		}
   425  		// Validate the user's existence since the API is unhelpful here
   426  		if res, err = http.Head("https://github.com/" + gist.Owner.Login); err != nil {
   427  			websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   428  			continue
   429  		}
   430  		res.Body.Close()
   431  
   432  		if res.StatusCode != 200 {
   433  			websocket.JSON.Send(conn, map[string]string{"error": "Invalid user... boom!"})
   434  			continue
   435  		}
   436  		// Ensure the user didn't request funds too recently
   437  		f.lock.Lock()
   438  		var (
   439  			fund    bool
   440  			timeout time.Time
   441  		)
   442  		if timeout = f.timeouts[gist.Owner.Login]; time.Now().After(timeout) {
   443  			// User wasn't funded recently, create the funding transaction
   444  			amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
   445  			amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
   446  			amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil))
   447  
   448  			tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, big.NewInt(21000), f.price, nil)
   449  			signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainId)
   450  			if err != nil {
   451  				websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   452  				f.lock.Unlock()
   453  				continue
   454  			}
   455  			// Submit the transaction and mark as funded if successful
   456  			if err := f.client.SendTransaction(context.Background(), signed); err != nil {
   457  				websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
   458  				f.lock.Unlock()
   459  				continue
   460  			}
   461  			f.reqs = append(f.reqs, &request{
   462  				Username: gist.Owner.Login,
   463  				Account:  address,
   464  				Time:     time.Now(),
   465  				Tx:       signed,
   466  			})
   467  			f.timeouts[gist.Owner.Login] = time.Now().Add(time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute)
   468  			fund = true
   469  		}
   470  		f.lock.Unlock()
   471  
   472  		// Send an error if too frequent funding, othewise a success
   473  		if !fund {
   474  			websocket.JSON.Send(conn, map[string]string{"error": fmt.Sprintf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))})
   475  			continue
   476  		}
   477  		websocket.JSON.Send(conn, map[string]string{"success": fmt.Sprintf("Funding request accepted for %s into %s", gist.Owner.Login, address.Hex())})
   478  		select {
   479  		case f.update <- struct{}{}:
   480  		default:
   481  		}
   482  	}
   483  }
   484  
   485  // loop keeps waiting for interesting events and pushes them out to connected
   486  // websockets.
   487  func (f *faucet) loop() {
   488  	// Wait for chain events and push them to clients
   489  	heads := make(chan *types.Header, 16)
   490  	sub, err := f.client.SubscribeNewHead(context.Background(), heads)
   491  	if err != nil {
   492  		log.Crit("Failed to subscribe to head events", "err", err)
   493  	}
   494  	defer sub.Unsubscribe()
   495  
   496  	for {
   497  		select {
   498  		case head := <-heads:
   499  			// New chain head arrived, query the current stats and stream to clients
   500  			balance, _ := f.client.BalanceAt(context.Background(), f.account.Address, nil)
   501  			balance = new(big.Int).Div(balance, ether)
   502  
   503  			price, _ := f.client.SuggestGasPrice(context.Background())
   504  			nonce, _ := f.client.NonceAt(context.Background(), f.account.Address, nil)
   505  
   506  			f.lock.Lock()
   507  			f.price, f.nonce = price, nonce
   508  			for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
   509  				f.reqs = f.reqs[1:]
   510  			}
   511  			f.lock.Unlock()
   512  
   513  			f.lock.RLock()
   514  			for _, conn := range f.conns {
   515  				if err := websocket.JSON.Send(conn, map[string]interface{}{
   516  					"funds":    balance,
   517  					"funded":   f.nonce,
   518  					"peers":    f.stack.Server().PeerCount(),
   519  					"requests": f.reqs,
   520  				}); err != nil {
   521  					log.Warn("Failed to send stats to client", "err", err)
   522  					conn.Close()
   523  					continue
   524  				}
   525  				if err := websocket.JSON.Send(conn, head); err != nil {
   526  					log.Warn("Failed to send header to client", "err", err)
   527  					conn.Close()
   528  				}
   529  			}
   530  			f.lock.RUnlock()
   531  
   532  		case <-f.update:
   533  			// Pending requests updated, stream to clients
   534  			f.lock.RLock()
   535  			for _, conn := range f.conns {
   536  				if err := websocket.JSON.Send(conn, map[string]interface{}{"requests": f.reqs}); err != nil {
   537  					log.Warn("Failed to send requests to client", "err", err)
   538  					conn.Close()
   539  				}
   540  			}
   541  			f.lock.RUnlock()
   542  		}
   543  	}
   544  }