faucet.go 27 KB

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