faucet.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // faucet is a Ether faucet backed by a light client.
  17. package main
  18. //go:generate go-bindata -nometadata -o website.go faucet.html
  19. //go:generate gofmt -w -s website.go
  20. import (
  21. "bytes"
  22. "context"
  23. "encoding/json"
  24. "errors"
  25. "flag"
  26. "fmt"
  27. "html/template"
  28. "io/ioutil"
  29. "math"
  30. "math/big"
  31. "net/http"
  32. "net/url"
  33. "os"
  34. "path/filepath"
  35. "regexp"
  36. "strconv"
  37. "strings"
  38. "sync"
  39. "time"
  40. "github.com/ethereum/go-ethereum/accounts"
  41. "github.com/ethereum/go-ethereum/accounts/keystore"
  42. "github.com/ethereum/go-ethereum/common"
  43. "github.com/ethereum/go-ethereum/core"
  44. "github.com/ethereum/go-ethereum/core/types"
  45. "github.com/ethereum/go-ethereum/eth"
  46. "github.com/ethereum/go-ethereum/eth/downloader"
  47. "github.com/ethereum/go-ethereum/ethclient"
  48. "github.com/ethereum/go-ethereum/ethstats"
  49. "github.com/ethereum/go-ethereum/les"
  50. "github.com/ethereum/go-ethereum/log"
  51. "github.com/ethereum/go-ethereum/node"
  52. "github.com/ethereum/go-ethereum/p2p"
  53. "github.com/ethereum/go-ethereum/p2p/discover"
  54. "github.com/ethereum/go-ethereum/p2p/discv5"
  55. "github.com/ethereum/go-ethereum/p2p/nat"
  56. "github.com/ethereum/go-ethereum/params"
  57. "golang.org/x/net/websocket"
  58. )
  59. var (
  60. genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with")
  61. apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection")
  62. ethPortFlag = flag.Int("ethport", 30303, "Listener port for the devp2p connection")
  63. bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with")
  64. netFlag = flag.Uint64("network", 0, "Network ID to use for the Ethereum protocol")
  65. statsFlag = flag.String("ethstats", "", "Ethstats network monitoring auth string")
  66. netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet")
  67. payoutFlag = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request")
  68. minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds")
  69. tiersFlag = flag.Int("faucet.tiers", 3, "Number of funding tiers to enable (x3 time, x2.5 funds)")
  70. accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with")
  71. accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds")
  72. githubUser = flag.String("github.user", "", "GitHub user to authenticate with for Gist access")
  73. githubToken = flag.String("github.token", "", "GitHub personal token to access Gists with")
  74. captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side")
  75. captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side")
  76. noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication")
  77. logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet")
  78. )
  79. var (
  80. ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
  81. )
  82. func main() {
  83. // Parse the flags and set up the logger to print everything requested
  84. flag.Parse()
  85. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
  86. // Construct the payout tiers
  87. amounts := make([]string, *tiersFlag)
  88. periods := make([]string, *tiersFlag)
  89. for i := 0; i < *tiersFlag; i++ {
  90. // Calculate the amount for the next tier and format it
  91. amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
  92. amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
  93. if amount == 1 {
  94. amounts[i] = strings.TrimSuffix(amounts[i], "s")
  95. }
  96. // Calculate the period for the next tier and format it
  97. period := *minutesFlag * int(math.Pow(3, float64(i)))
  98. periods[i] = fmt.Sprintf("%d mins", period)
  99. if period%60 == 0 {
  100. period /= 60
  101. periods[i] = fmt.Sprintf("%d hours", period)
  102. if period%24 == 0 {
  103. period /= 24
  104. periods[i] = fmt.Sprintf("%d days", period)
  105. }
  106. }
  107. if period == 1 {
  108. periods[i] = strings.TrimSuffix(periods[i], "s")
  109. }
  110. }
  111. // Load up and render the faucet website
  112. tmpl, err := Asset("faucet.html")
  113. if err != nil {
  114. log.Crit("Failed to load the faucet template", "err", err)
  115. }
  116. website := new(bytes.Buffer)
  117. err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
  118. "Network": *netnameFlag,
  119. "Amounts": amounts,
  120. "Periods": periods,
  121. "Recaptcha": *captchaToken,
  122. "NoAuth": *noauthFlag,
  123. })
  124. if err != nil {
  125. log.Crit("Failed to render the faucet template", "err", err)
  126. }
  127. // Load and parse the genesis block requested by the user
  128. blob, err := ioutil.ReadFile(*genesisFlag)
  129. if err != nil {
  130. log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
  131. }
  132. genesis := new(core.Genesis)
  133. if err = json.Unmarshal(blob, genesis); err != nil {
  134. log.Crit("Failed to parse genesis block json", "err", err)
  135. }
  136. // Convert the bootnodes to internal enode representations
  137. var enodes []*discv5.Node
  138. for _, boot := range strings.Split(*bootFlag, ",") {
  139. if url, err := discv5.ParseNode(boot); err == nil {
  140. enodes = append(enodes, url)
  141. } else {
  142. log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
  143. }
  144. }
  145. // Load up the account key and decrypt its password
  146. if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
  147. log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
  148. }
  149. pass := string(blob)
  150. ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
  151. if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
  152. log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
  153. }
  154. acc, err := ks.Import(blob, pass, pass)
  155. if err != nil {
  156. log.Crit("Failed to import faucet signer account", "err", err)
  157. }
  158. ks.Unlock(acc, pass)
  159. // Assemble and start the faucet light service
  160. faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
  161. if err != nil {
  162. log.Crit("Failed to start faucet", "err", err)
  163. }
  164. defer faucet.close()
  165. if err := faucet.listenAndServe(*apiPortFlag); err != nil {
  166. log.Crit("Failed to launch faucet API", "err", err)
  167. }
  168. }
  169. // request represents an accepted funding request.
  170. type request struct {
  171. Avatar string `json:"avatar"` // Avatar URL to make the UI nicer
  172. Account common.Address `json:"account"` // Ethereum address being funded
  173. Time time.Time `json:"time"` // Timestamp when the request was accepted
  174. Tx *types.Transaction `json:"tx"` // Transaction funding the account
  175. }
  176. // faucet represents a crypto faucet backed by an Ethereum light client.
  177. type faucet struct {
  178. config *params.ChainConfig // Chain configurations for signing
  179. stack *node.Node // Ethereum protocol stack
  180. client *ethclient.Client // Client connection to the Ethereum chain
  181. index []byte // Index page to serve up on the web
  182. keystore *keystore.KeyStore // Keystore containing the single signer
  183. account accounts.Account // Account funding user faucet requests
  184. nonce uint64 // Current pending nonce of the faucet
  185. price *big.Int // Current gas price to issue funds with
  186. conns []*websocket.Conn // Currently live websocket connections
  187. timeouts map[string]time.Time // History of users and their funding timeouts
  188. reqs []*request // Currently pending funding requests
  189. update chan struct{} // Channel to signal request updates
  190. lock sync.RWMutex // Lock protecting the faucet's internals
  191. }
  192. func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network uint64, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
  193. // Assemble the raw devp2p protocol stack
  194. stack, err := node.New(&node.Config{
  195. Name: "geth",
  196. Version: params.Version,
  197. DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
  198. P2P: p2p.Config{
  199. NAT: nat.Any(),
  200. NoDiscovery: true,
  201. DiscoveryV5: true,
  202. ListenAddr: fmt.Sprintf(":%d", port),
  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. // Start a goroutine to update the state from head notifications in the background
  497. update := make(chan *types.Header)
  498. go func() {
  499. for head := range update {
  500. // New chain head arrived, query the current stats and stream to clients
  501. var (
  502. balance *big.Int
  503. nonce uint64
  504. price *big.Int
  505. err error
  506. )
  507. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  508. balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number)
  509. if err == nil {
  510. nonce, err = f.client.NonceAt(ctx, f.account.Address, nil)
  511. if err == nil {
  512. price, err = f.client.SuggestGasPrice(ctx)
  513. }
  514. }
  515. cancel()
  516. // If querying the data failed, try for the next block
  517. if err != nil {
  518. log.Warn("Failed to update faucet state", "block", head.Number, "hash", head.Hash(), "err", err)
  519. continue
  520. } else {
  521. log.Info("Updated faucet state", "block", head.Number, "hash", head.Hash(), "balance", balance, "nonce", nonce, "price", price)
  522. }
  523. // Faucet state retrieved, update locally and send to clients
  524. balance = new(big.Int).Div(balance, ether)
  525. f.lock.Lock()
  526. f.price, f.nonce = price, nonce
  527. for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
  528. f.reqs = f.reqs[1:]
  529. }
  530. f.lock.Unlock()
  531. f.lock.RLock()
  532. for _, conn := range f.conns {
  533. if err := send(conn, map[string]interface{}{
  534. "funds": balance,
  535. "funded": f.nonce,
  536. "peers": f.stack.Server().PeerCount(),
  537. "requests": f.reqs,
  538. }, time.Second); err != nil {
  539. log.Warn("Failed to send stats to client", "err", err)
  540. conn.Close()
  541. continue
  542. }
  543. if err := send(conn, head, time.Second); err != nil {
  544. log.Warn("Failed to send header to client", "err", err)
  545. conn.Close()
  546. }
  547. }
  548. f.lock.RUnlock()
  549. }
  550. }()
  551. // Wait for various events and assing to the appropriate background threads
  552. for {
  553. select {
  554. case head := <-heads:
  555. // New head arrived, send if for state update if there's none running
  556. select {
  557. case update <- head:
  558. default:
  559. }
  560. case <-f.update:
  561. // Pending requests updated, stream to clients
  562. f.lock.RLock()
  563. for _, conn := range f.conns {
  564. if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
  565. log.Warn("Failed to send requests to client", "err", err)
  566. conn.Close()
  567. }
  568. }
  569. f.lock.RUnlock()
  570. }
  571. }
  572. }
  573. // sends transmits a data packet to the remote end of the websocket, but also
  574. // setting a write deadline to prevent waiting forever on the node.
  575. func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
  576. if timeout == 0 {
  577. timeout = 60 * time.Second
  578. }
  579. conn.SetWriteDeadline(time.Now().Add(timeout))
  580. return websocket.JSON.Send(conn, value)
  581. }
  582. // sendError transmits an error to the remote end of the websocket, also setting
  583. // the write deadline to 1 second to prevent waiting forever.
  584. func sendError(conn *websocket.Conn, err error) error {
  585. return send(conn, map[string]string{"error": err.Error()}, time.Second)
  586. }
  587. // sendSuccess transmits a success message to the remote end of the websocket, also
  588. // setting the write deadline to 1 second to prevent waiting forever.
  589. func sendSuccess(conn *websocket.Conn, msg string) error {
  590. return send(conn, map[string]string{"success": msg}, time.Second)
  591. }
  592. // authGitHub tries to authenticate a faucet request using GitHub gists, returning
  593. // the username, avatar URL and Ethereum address to fund on success.
  594. func authGitHub(url string) (string, string, common.Address, error) {
  595. // Retrieve the gist from the GitHub Gist APIs
  596. parts := strings.Split(url, "/")
  597. req, _ := http.NewRequest("GET", "https://api.github.com/gists/"+parts[len(parts)-1], nil)
  598. if *githubUser != "" {
  599. req.SetBasicAuth(*githubUser, *githubToken)
  600. }
  601. res, err := http.DefaultClient.Do(req)
  602. if err != nil {
  603. return "", "", common.Address{}, err
  604. }
  605. var gist struct {
  606. Owner struct {
  607. Login string `json:"login"`
  608. } `json:"owner"`
  609. Files map[string]struct {
  610. Content string `json:"content"`
  611. } `json:"files"`
  612. }
  613. err = json.NewDecoder(res.Body).Decode(&gist)
  614. res.Body.Close()
  615. if err != nil {
  616. return "", "", common.Address{}, err
  617. }
  618. if gist.Owner.Login == "" {
  619. return "", "", common.Address{}, errors.New("Anonymous Gists not allowed")
  620. }
  621. // Iterate over all the files and look for Ethereum addresses
  622. var address common.Address
  623. for _, file := range gist.Files {
  624. content := strings.TrimSpace(file.Content)
  625. if len(content) == 2+common.AddressLength*2 {
  626. address = common.HexToAddress(content)
  627. }
  628. }
  629. if address == (common.Address{}) {
  630. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  631. }
  632. // Validate the user's existence since the API is unhelpful here
  633. if res, err = http.Head("https://github.com/" + gist.Owner.Login); err != nil {
  634. return "", "", common.Address{}, err
  635. }
  636. res.Body.Close()
  637. if res.StatusCode != 200 {
  638. return "", "", common.Address{}, errors.New("Invalid user... boom!")
  639. }
  640. // Everything passed validation, return the gathered infos
  641. return gist.Owner.Login + "@github", fmt.Sprintf("https://github.com/%s.png?size=64", gist.Owner.Login), address, nil
  642. }
  643. // authTwitter tries to authenticate a faucet request using Twitter posts, returning
  644. // the username, avatar URL and Ethereum address to fund on success.
  645. func authTwitter(url string) (string, string, common.Address, error) {
  646. // Ensure the user specified a meaningful URL, no fancy nonsense
  647. parts := strings.Split(url, "/")
  648. if len(parts) < 4 || parts[len(parts)-2] != "status" {
  649. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  650. }
  651. // Twitter's API isn't really friendly with direct links. Still, we don't
  652. // want to do ask read permissions from users, so just load the public posts and
  653. // scrape it for the Ethereum address and profile URL.
  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. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  663. }
  664. username := parts[len(parts)-3]
  665. body, err := ioutil.ReadAll(res.Body)
  666. if err != nil {
  667. return "", "", common.Address{}, err
  668. }
  669. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  670. if address == (common.Address{}) {
  671. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  672. }
  673. var avatar string
  674. if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  675. avatar = parts[1]
  676. }
  677. return username + "@twitter", avatar, address, nil
  678. }
  679. // authGooglePlus tries to authenticate a faucet request using GooglePlus posts,
  680. // returning the username, avatar URL and Ethereum address to fund on success.
  681. func authGooglePlus(url string) (string, string, common.Address, error) {
  682. // Ensure the user specified a meaningful URL, no fancy nonsense
  683. parts := strings.Split(url, "/")
  684. if len(parts) < 4 || parts[len(parts)-2] != "posts" {
  685. return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
  686. }
  687. username := parts[len(parts)-3]
  688. // Google's API isn't really friendly with direct links. Still, we don't
  689. // want to do ask read permissions from users, so just load the public posts and
  690. // scrape it for the Ethereum address and profile URL.
  691. res, err := http.Get(url)
  692. if err != nil {
  693. return "", "", common.Address{}, err
  694. }
  695. defer res.Body.Close()
  696. body, err := ioutil.ReadAll(res.Body)
  697. if err != nil {
  698. return "", "", common.Address{}, err
  699. }
  700. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  701. if address == (common.Address{}) {
  702. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  703. }
  704. var avatar string
  705. if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  706. avatar = parts[1]
  707. }
  708. return username + "@google+", avatar, address, nil
  709. }
  710. // authFacebook tries to authenticate a faucet request using Facebook posts,
  711. // returning the username, avatar URL and Ethereum address to fund on success.
  712. func authFacebook(url string) (string, string, common.Address, error) {
  713. // Ensure the user specified a meaningful URL, no fancy nonsense
  714. parts := strings.Split(url, "/")
  715. if len(parts) < 4 || parts[len(parts)-2] != "posts" {
  716. return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
  717. }
  718. username := parts[len(parts)-3]
  719. // Facebook's Graph API isn't really friendly with direct links. Still, we don't
  720. // want to do ask read permissions from users, so just load the public posts and
  721. // scrape it for the Ethereum address and profile URL.
  722. res, err := http.Get(url)
  723. if err != nil {
  724. return "", "", common.Address{}, err
  725. }
  726. defer res.Body.Close()
  727. body, err := ioutil.ReadAll(res.Body)
  728. if err != nil {
  729. return "", "", common.Address{}, err
  730. }
  731. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  732. if address == (common.Address{}) {
  733. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  734. }
  735. var avatar string
  736. if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  737. avatar = parts[1]
  738. }
  739. return username + "@facebook", avatar, address, nil
  740. }
  741. // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
  742. // without actually performing any remote authentication. This mode is prone to
  743. // Byzantine attack, so only ever use for truly private networks.
  744. func authNoAuth(url string) (string, string, common.Address, error) {
  745. address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
  746. if address == (common.Address{}) {
  747. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  748. }
  749. return address.Hex() + "@noauth", "", address, nil
  750. }