faucet.go 31 KB

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