faucet.go 27 KB

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