faucet.go 27 KB

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