faucet.go 30 KB

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