faucet.go 32 KB

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