faucet.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  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. 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. // Delete trailing newline in password
  152. pass := strings.TrimSuffix(string(blob), "\n")
  153. ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
  154. if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
  155. log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
  156. }
  157. acc, err := ks.Import(blob, pass, pass)
  158. if err != nil {
  159. log.Crit("Failed to import faucet signer account", "err", err)
  160. }
  161. ks.Unlock(acc, pass)
  162. // Assemble and start the faucet light service
  163. faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
  164. if err != nil {
  165. log.Crit("Failed to start faucet", "err", err)
  166. }
  167. defer faucet.close()
  168. if err := faucet.listenAndServe(*apiPortFlag); err != nil {
  169. log.Crit("Failed to launch faucet API", "err", err)
  170. }
  171. }
  172. // request represents an accepted funding request.
  173. type request struct {
  174. Avatar string `json:"avatar"` // Avatar URL to make the UI nicer
  175. Account common.Address `json:"account"` // Ethereum address being funded
  176. Time time.Time `json:"time"` // Timestamp when the request was accepted
  177. Tx *types.Transaction `json:"tx"` // Transaction funding the account
  178. }
  179. // faucet represents a crypto faucet backed by an Ethereum light client.
  180. type faucet struct {
  181. config *params.ChainConfig // Chain configurations for signing
  182. stack *node.Node // Ethereum protocol stack
  183. client *ethclient.Client // Client connection to the Ethereum chain
  184. index []byte // Index page to serve up on the web
  185. keystore *keystore.KeyStore // Keystore containing the single signer
  186. account accounts.Account // Account funding user faucet requests
  187. head *types.Header // Current head header of the faucet
  188. balance *big.Int // Current balance of the faucet
  189. nonce uint64 // Current pending nonce of the faucet
  190. price *big.Int // Current gas price to issue funds with
  191. conns []*websocket.Conn // Currently live websocket connections
  192. timeouts map[string]time.Time // History of users and their funding timeouts
  193. reqs []*request // Currently pending funding requests
  194. update chan struct{} // Channel to signal request updates
  195. lock sync.RWMutex // Lock protecting the faucet's internals
  196. }
  197. func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
  198. // Assemble the raw devp2p protocol stack
  199. stack, err := node.New(&node.Config{
  200. Name: "geth",
  201. Version: params.VersionWithCommit(gitCommit, gitDate),
  202. DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
  203. P2P: p2p.Config{
  204. NAT: nat.Any(),
  205. NoDiscovery: true,
  206. DiscoveryV5: true,
  207. ListenAddr: fmt.Sprintf(":%d", port),
  208. MaxPeers: 25,
  209. BootstrapNodesV5: enodes,
  210. },
  211. })
  212. if err != nil {
  213. return nil, err
  214. }
  215. // Assemble the Ethereum light client protocol
  216. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  217. cfg := eth.DefaultConfig
  218. cfg.SyncMode = downloader.LightSync
  219. cfg.NetworkId = network
  220. cfg.Genesis = genesis
  221. return les.New(ctx, &cfg)
  222. }); err != nil {
  223. return nil, err
  224. }
  225. // Assemble the ethstats monitoring and reporting service'
  226. if stats != "" {
  227. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  228. var serv *les.LightEthereum
  229. ctx.Service(&serv)
  230. return ethstats.New(stats, nil, serv)
  231. }); err != nil {
  232. return nil, err
  233. }
  234. }
  235. // Boot up the client and ensure it connects to bootnodes
  236. if err := stack.Start(); err != nil {
  237. return nil, err
  238. }
  239. for _, boot := range enodes {
  240. old, err := enode.ParseV4(boot.String())
  241. if err == nil {
  242. stack.Server().AddPeer(old)
  243. }
  244. }
  245. // Attach to the client and retrieve and interesting metadatas
  246. api, err := stack.Attach()
  247. if err != nil {
  248. stack.Stop()
  249. return nil, err
  250. }
  251. client := ethclient.NewClient(api)
  252. return &faucet{
  253. config: genesis.Config,
  254. stack: stack,
  255. client: client,
  256. index: index,
  257. keystore: ks,
  258. account: ks.Accounts()[0],
  259. timeouts: make(map[string]time.Time),
  260. update: make(chan struct{}, 1),
  261. }, nil
  262. }
  263. // close terminates the Ethereum connection and tears down the faucet.
  264. func (f *faucet) close() error {
  265. return f.stack.Close()
  266. }
  267. // listenAndServe registers the HTTP handlers for the faucet and boots it up
  268. // for service user funding requests.
  269. func (f *faucet) listenAndServe(port int) error {
  270. go f.loop()
  271. http.HandleFunc("/", f.webHandler)
  272. http.Handle("/api", websocket.Handler(f.apiHandler))
  273. return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
  274. }
  275. // webHandler handles all non-api requests, simply flattening and returning the
  276. // faucet website.
  277. func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
  278. w.Write(f.index)
  279. }
  280. // apiHandler handles requests for Ether grants and transaction statuses.
  281. func (f *faucet) apiHandler(conn *websocket.Conn) {
  282. // Start tracking the connection and drop at the end
  283. defer conn.Close()
  284. f.lock.Lock()
  285. f.conns = append(f.conns, conn)
  286. f.lock.Unlock()
  287. defer func() {
  288. f.lock.Lock()
  289. for i, c := range f.conns {
  290. if c == conn {
  291. f.conns = append(f.conns[:i], f.conns[i+1:]...)
  292. break
  293. }
  294. }
  295. f.lock.Unlock()
  296. }()
  297. // Gather the initial stats from the network to report
  298. var (
  299. head *types.Header
  300. balance *big.Int
  301. nonce uint64
  302. err error
  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. if err = sendError(conn, errors.New("Faucet offline")); err != nil {
  318. log.Warn("Failed to send faucet error to client", "err", err)
  319. return
  320. }
  321. time.Sleep(3 * time.Second)
  322. }
  323. }
  324. // Send over the initial stats and the latest header
  325. if err = send(conn, map[string]interface{}{
  326. "funds": new(big.Int).Div(balance, ether),
  327. "funded": nonce,
  328. "peers": f.stack.Server().PeerCount(),
  329. "requests": f.reqs,
  330. }, 3*time.Second); err != nil {
  331. log.Warn("Failed to send initial stats to client", "err", err)
  332. return
  333. }
  334. if err = send(conn, head, 3*time.Second); err != nil {
  335. log.Warn("Failed to send initial header to client", "err", err)
  336. return
  337. }
  338. // Keep reading requests from the websocket until the connection breaks
  339. for {
  340. // Fetch the next funding request and validate against github
  341. var msg struct {
  342. URL string `json:"url"`
  343. Tier uint `json:"tier"`
  344. Captcha string `json:"captcha"`
  345. }
  346. if err = websocket.JSON.Receive(conn, &msg); err != nil {
  347. return
  348. }
  349. if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
  350. !strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
  351. if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil {
  352. log.Warn("Failed to send URL error to client", "err", err)
  353. return
  354. }
  355. continue
  356. }
  357. if msg.Tier >= uint(*tiersFlag) {
  358. if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil {
  359. log.Warn("Failed to send tier error to client", "err", err)
  360. return
  361. }
  362. continue
  363. }
  364. log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier)
  365. // If captcha verifications are enabled, make sure we're not dealing with a robot
  366. if *captchaToken != "" {
  367. form := url.Values{}
  368. form.Add("secret", *captchaSecret)
  369. form.Add("response", msg.Captcha)
  370. res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
  371. if err != nil {
  372. if err = sendError(conn, err); err != nil {
  373. log.Warn("Failed to send captcha post error to client", "err", err)
  374. return
  375. }
  376. continue
  377. }
  378. var result struct {
  379. Success bool `json:"success"`
  380. Errors json.RawMessage `json:"error-codes"`
  381. }
  382. err = json.NewDecoder(res.Body).Decode(&result)
  383. res.Body.Close()
  384. if err != nil {
  385. if err = sendError(conn, err); err != nil {
  386. log.Warn("Failed to send captcha decode error to client", "err", err)
  387. return
  388. }
  389. continue
  390. }
  391. if !result.Success {
  392. log.Warn("Captcha verification failed", "err", string(result.Errors))
  393. if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil {
  394. log.Warn("Failed to send captcha failure to client", "err", err)
  395. return
  396. }
  397. continue
  398. }
  399. }
  400. // Retrieve the Ethereum address to fund, the requesting user and a profile picture
  401. var (
  402. username string
  403. avatar string
  404. address common.Address
  405. )
  406. switch {
  407. case strings.HasPrefix(msg.URL, "https://gist.github.com/"):
  408. if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil {
  409. log.Warn("Failed to send GitHub deprecation to client", "err", err)
  410. return
  411. }
  412. continue
  413. case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
  414. if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil {
  415. log.Warn("Failed to send Google+ deprecation to client", "err", err)
  416. return
  417. }
  418. continue
  419. case strings.HasPrefix(msg.URL, "https://twitter.com/"):
  420. username, avatar, address, err = authTwitter(msg.URL)
  421. case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
  422. username, avatar, address, err = authFacebook(msg.URL)
  423. case *noauthFlag:
  424. username, avatar, address, err = authNoAuth(msg.URL)
  425. default:
  426. err = errors.New("Something funky happened, please open an issue at https://github.com/ethereum/go-ethereum/issues")
  427. }
  428. if err != nil {
  429. if err = sendError(conn, err); err != nil {
  430. log.Warn("Failed to send prefix error to client", "err", err)
  431. return
  432. }
  433. continue
  434. }
  435. log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address)
  436. // Ensure the user didn't request funds too recently
  437. f.lock.Lock()
  438. var (
  439. fund bool
  440. timeout time.Time
  441. )
  442. if timeout = f.timeouts[username]; time.Now().After(timeout) {
  443. // User wasn't funded recently, create the funding transaction
  444. amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
  445. amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
  446. amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil))
  447. tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil)
  448. signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID)
  449. if err != nil {
  450. f.lock.Unlock()
  451. if err = sendError(conn, err); err != nil {
  452. log.Warn("Failed to send transaction creation error to client", "err", err)
  453. return
  454. }
  455. continue
  456. }
  457. // Submit the transaction and mark as funded if successful
  458. if err := f.client.SendTransaction(context.Background(), signed); err != nil {
  459. f.lock.Unlock()
  460. if err = sendError(conn, err); err != nil {
  461. log.Warn("Failed to send transaction transmission error to client", "err", err)
  462. return
  463. }
  464. continue
  465. }
  466. f.reqs = append(f.reqs, &request{
  467. Avatar: avatar,
  468. Account: address,
  469. Time: time.Now(),
  470. Tx: signed,
  471. })
  472. f.timeouts[username] = time.Now().Add(time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute)
  473. fund = true
  474. }
  475. f.lock.Unlock()
  476. // Send an error if too frequent funding, othewise a success
  477. if !fund {
  478. if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))); err != nil { // nolint: gosimple
  479. log.Warn("Failed to send funding error to client", "err", err)
  480. return
  481. }
  482. continue
  483. }
  484. if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil {
  485. log.Warn("Failed to send funding success to client", "err", err)
  486. return
  487. }
  488. select {
  489. case f.update <- struct{}{}:
  490. default:
  491. }
  492. }
  493. }
  494. // refresh attempts to retrieve the latest header from the chain and extract the
  495. // associated faucet balance and nonce for connectivity caching.
  496. func (f *faucet) refresh(head *types.Header) error {
  497. // Ensure a state update does not run for too long
  498. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  499. defer cancel()
  500. // If no header was specified, use the current chain head
  501. var err error
  502. if head == nil {
  503. if head, err = f.client.HeaderByNumber(ctx, nil); err != nil {
  504. return err
  505. }
  506. }
  507. // Retrieve the balance, nonce and gas price from the current head
  508. var (
  509. balance *big.Int
  510. nonce uint64
  511. price *big.Int
  512. )
  513. if balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number); err != nil {
  514. return err
  515. }
  516. if nonce, err = f.client.NonceAt(ctx, f.account.Address, head.Number); err != nil {
  517. return err
  518. }
  519. if price, err = f.client.SuggestGasPrice(ctx); err != nil {
  520. return err
  521. }
  522. // Everything succeeded, update the cached stats and eject old requests
  523. f.lock.Lock()
  524. f.head, f.balance = head, balance
  525. f.price, f.nonce = price, nonce
  526. for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
  527. f.reqs = f.reqs[1:]
  528. }
  529. f.lock.Unlock()
  530. return nil
  531. }
  532. // loop keeps waiting for interesting events and pushes them out to connected
  533. // websockets.
  534. func (f *faucet) loop() {
  535. // Wait for chain events and push them to clients
  536. heads := make(chan *types.Header, 16)
  537. sub, err := f.client.SubscribeNewHead(context.Background(), heads)
  538. if err != nil {
  539. log.Crit("Failed to subscribe to head events", "err", err)
  540. }
  541. defer sub.Unsubscribe()
  542. // Start a goroutine to update the state from head notifications in the background
  543. update := make(chan *types.Header)
  544. go func() {
  545. for head := range update {
  546. // New chain head arrived, query the current stats and stream to clients
  547. timestamp := time.Unix(int64(head.Time), 0)
  548. if time.Since(timestamp) > time.Hour {
  549. log.Warn("Skipping faucet refresh, head too old", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp))
  550. continue
  551. }
  552. if err := f.refresh(head); err != nil {
  553. log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err)
  554. continue
  555. }
  556. // Faucet state retrieved, update locally and send to clients
  557. f.lock.RLock()
  558. log.Info("Updated faucet state", "number", head.Number, "hash", head.Hash(), "age", common.PrettyAge(timestamp), "balance", f.balance, "nonce", f.nonce, "price", f.price)
  559. balance := new(big.Int).Div(f.balance, ether)
  560. peers := f.stack.Server().PeerCount()
  561. for _, conn := range f.conns {
  562. if err := send(conn, map[string]interface{}{
  563. "funds": balance,
  564. "funded": f.nonce,
  565. "peers": peers,
  566. "requests": f.reqs,
  567. }, time.Second); err != nil {
  568. log.Warn("Failed to send stats to client", "err", err)
  569. conn.Close()
  570. continue
  571. }
  572. if err := send(conn, head, time.Second); err != nil {
  573. log.Warn("Failed to send header to client", "err", err)
  574. conn.Close()
  575. }
  576. }
  577. f.lock.RUnlock()
  578. }
  579. }()
  580. // Wait for various events and assing to the appropriate background threads
  581. for {
  582. select {
  583. case head := <-heads:
  584. // New head arrived, send if for state update if there's none running
  585. select {
  586. case update <- head:
  587. default:
  588. }
  589. case <-f.update:
  590. // Pending requests updated, stream to clients
  591. f.lock.RLock()
  592. for _, conn := range f.conns {
  593. if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
  594. log.Warn("Failed to send requests to client", "err", err)
  595. conn.Close()
  596. }
  597. }
  598. f.lock.RUnlock()
  599. }
  600. }
  601. }
  602. // sends transmits a data packet to the remote end of the websocket, but also
  603. // setting a write deadline to prevent waiting forever on the node.
  604. func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
  605. if timeout == 0 {
  606. timeout = 60 * time.Second
  607. }
  608. conn.SetWriteDeadline(time.Now().Add(timeout))
  609. return websocket.JSON.Send(conn, value)
  610. }
  611. // sendError transmits an error to the remote end of the websocket, also setting
  612. // the write deadline to 1 second to prevent waiting forever.
  613. func sendError(conn *websocket.Conn, err error) error {
  614. return send(conn, map[string]string{"error": err.Error()}, time.Second)
  615. }
  616. // sendSuccess transmits a success message to the remote end of the websocket, also
  617. // setting the write deadline to 1 second to prevent waiting forever.
  618. func sendSuccess(conn *websocket.Conn, msg string) error {
  619. return send(conn, map[string]string{"success": msg}, time.Second)
  620. }
  621. // authTwitter tries to authenticate a faucet request using Twitter posts, returning
  622. // the username, avatar URL and Ethereum address to fund on success.
  623. func authTwitter(url string) (string, string, common.Address, error) {
  624. // Ensure the user specified a meaningful URL, no fancy nonsense
  625. parts := strings.Split(url, "/")
  626. if len(parts) < 4 || parts[len(parts)-2] != "status" {
  627. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  628. }
  629. // Twitter's API isn't really friendly with direct links. Still, we don't
  630. // want to do ask read permissions from users, so just load the public posts and
  631. // scrape it for the Ethereum address and profile URL.
  632. res, err := http.Get(url)
  633. if err != nil {
  634. return "", "", common.Address{}, err
  635. }
  636. defer res.Body.Close()
  637. // Resolve the username from the final redirect, no intermediate junk
  638. parts = strings.Split(res.Request.URL.String(), "/")
  639. if len(parts) < 4 || parts[len(parts)-2] != "status" {
  640. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  641. }
  642. username := parts[len(parts)-3]
  643. body, err := ioutil.ReadAll(res.Body)
  644. if err != nil {
  645. return "", "", common.Address{}, err
  646. }
  647. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  648. if address == (common.Address{}) {
  649. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  650. }
  651. var avatar string
  652. if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  653. avatar = parts[1]
  654. }
  655. return username + "@twitter", avatar, address, nil
  656. }
  657. // authFacebook tries to authenticate a faucet request using Facebook posts,
  658. // returning the username, avatar URL and Ethereum address to fund on success.
  659. func authFacebook(url string) (string, string, common.Address, error) {
  660. // Ensure the user specified a meaningful URL, no fancy nonsense
  661. parts := strings.Split(url, "/")
  662. if len(parts) < 4 || parts[len(parts)-2] != "posts" {
  663. return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
  664. }
  665. username := parts[len(parts)-3]
  666. // Facebook's Graph API isn't really friendly with direct links. Still, we don't
  667. // want to do ask read permissions from users, so just load the public posts and
  668. // scrape it for the Ethereum address and profile URL.
  669. res, err := http.Get(url)
  670. if err != nil {
  671. return "", "", common.Address{}, err
  672. }
  673. defer res.Body.Close()
  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. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  681. }
  682. var avatar string
  683. if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  684. avatar = parts[1]
  685. }
  686. return username + "@facebook", avatar, address, nil
  687. }
  688. // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
  689. // without actually performing any remote authentication. This mode is prone to
  690. // Byzantine attack, so only ever use for truly private networks.
  691. func authNoAuth(url string) (string, string, common.Address, error) {
  692. address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
  693. if address == (common.Address{}) {
  694. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  695. }
  696. return address.Hex() + "@noauth", "", address, nil
  697. }