faucet.go 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755
  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. captchaToken = flag.String("captcha.token", "", "Recaptcha site key to authenticate client side")
  73. captchaSecret = flag.String("captcha.secret", "", "Recaptcha secret key to authenticate server side")
  74. noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication")
  75. logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet")
  76. )
  77. var (
  78. ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
  79. )
  80. func main() {
  81. // Parse the flags and set up the logger to print everything requested
  82. flag.Parse()
  83. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
  84. // Construct the payout tiers
  85. amounts := make([]string, *tiersFlag)
  86. periods := make([]string, *tiersFlag)
  87. for i := 0; i < *tiersFlag; i++ {
  88. // Calculate the amount for the next tier and format it
  89. amount := float64(*payoutFlag) * math.Pow(2.5, float64(i))
  90. amounts[i] = fmt.Sprintf("%s Ethers", strconv.FormatFloat(amount, 'f', -1, 64))
  91. if amount == 1 {
  92. amounts[i] = strings.TrimSuffix(amounts[i], "s")
  93. }
  94. // Calculate the period for the next tier and format it
  95. period := *minutesFlag * int(math.Pow(3, float64(i)))
  96. periods[i] = fmt.Sprintf("%d mins", period)
  97. if period%60 == 0 {
  98. period /= 60
  99. periods[i] = fmt.Sprintf("%d hours", period)
  100. if period%24 == 0 {
  101. period /= 24
  102. periods[i] = fmt.Sprintf("%d days", period)
  103. }
  104. }
  105. if period == 1 {
  106. periods[i] = strings.TrimSuffix(periods[i], "s")
  107. }
  108. }
  109. // Load up and render the faucet website
  110. tmpl, err := Asset("faucet.html")
  111. if err != nil {
  112. log.Crit("Failed to load the faucet template", "err", err)
  113. }
  114. website := new(bytes.Buffer)
  115. err = template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
  116. "Network": *netnameFlag,
  117. "Amounts": amounts,
  118. "Periods": periods,
  119. "Recaptcha": *captchaToken,
  120. "NoAuth": *noauthFlag,
  121. })
  122. if err != nil {
  123. log.Crit("Failed to render the faucet template", "err", err)
  124. }
  125. // Load and parse the genesis block requested by the user
  126. blob, err := ioutil.ReadFile(*genesisFlag)
  127. if err != nil {
  128. log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
  129. }
  130. genesis := new(core.Genesis)
  131. if err = json.Unmarshal(blob, genesis); err != nil {
  132. log.Crit("Failed to parse genesis block json", "err", err)
  133. }
  134. // Convert the bootnodes to internal enode representations
  135. var enodes []*discv5.Node
  136. for _, boot := range strings.Split(*bootFlag, ",") {
  137. if url, err := discv5.ParseNode(boot); err == nil {
  138. enodes = append(enodes, url)
  139. } else {
  140. log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
  141. }
  142. }
  143. // Load up the account key and decrypt its password
  144. if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
  145. log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
  146. }
  147. // Delete trailing newline in password
  148. pass := strings.TrimSuffix(string(blob), "\n")
  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.VersionWithMeta,
  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. MaxPeers: 25,
  203. BootstrapNodesV5: enodes,
  204. },
  205. })
  206. if err != nil {
  207. return nil, err
  208. }
  209. // Assemble the Ethereum light client protocol
  210. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  211. cfg := eth.DefaultConfig
  212. cfg.SyncMode = downloader.LightSync
  213. cfg.NetworkId = network
  214. cfg.Genesis = genesis
  215. return les.New(ctx, &cfg)
  216. }); err != nil {
  217. return nil, err
  218. }
  219. // Assemble the ethstats monitoring and reporting service'
  220. if stats != "" {
  221. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  222. var serv *les.LightEthereum
  223. ctx.Service(&serv)
  224. return ethstats.New(stats, nil, serv)
  225. }); err != nil {
  226. return nil, err
  227. }
  228. }
  229. // Boot up the client and ensure it connects to bootnodes
  230. if err := stack.Start(); err != nil {
  231. return nil, err
  232. }
  233. for _, boot := range enodes {
  234. old, _ := discover.ParseNode(boot.String())
  235. stack.Server().AddPeer(old)
  236. }
  237. // Attach to the client and retrieve and interesting metadatas
  238. api, err := stack.Attach()
  239. if err != nil {
  240. stack.Stop()
  241. return nil, err
  242. }
  243. client := ethclient.NewClient(api)
  244. return &faucet{
  245. config: genesis.Config,
  246. stack: stack,
  247. client: client,
  248. index: index,
  249. keystore: ks,
  250. account: ks.Accounts()[0],
  251. timeouts: make(map[string]time.Time),
  252. update: make(chan struct{}, 1),
  253. }, nil
  254. }
  255. // close terminates the Ethereum connection and tears down the faucet.
  256. func (f *faucet) close() error {
  257. return f.stack.Stop()
  258. }
  259. // listenAndServe registers the HTTP handlers for the faucet and boots it up
  260. // for service user funding requests.
  261. func (f *faucet) listenAndServe(port int) error {
  262. go f.loop()
  263. http.HandleFunc("/", f.webHandler)
  264. http.Handle("/api", websocket.Handler(f.apiHandler))
  265. return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
  266. }
  267. // webHandler handles all non-api requests, simply flattening and returning the
  268. // faucet website.
  269. func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
  270. w.Write(f.index)
  271. }
  272. // apiHandler handles requests for Ether grants and transaction statuses.
  273. func (f *faucet) apiHandler(conn *websocket.Conn) {
  274. // Start tracking the connection and drop at the end
  275. defer conn.Close()
  276. f.lock.Lock()
  277. f.conns = append(f.conns, conn)
  278. f.lock.Unlock()
  279. defer func() {
  280. f.lock.Lock()
  281. for i, c := range f.conns {
  282. if c == conn {
  283. f.conns = append(f.conns[:i], f.conns[i+1:]...)
  284. break
  285. }
  286. }
  287. f.lock.Unlock()
  288. }()
  289. // Gather the initial stats from the network to report
  290. var (
  291. head *types.Header
  292. balance *big.Int
  293. nonce uint64
  294. err error
  295. )
  296. for {
  297. // Attempt to retrieve the stats, may error on no faucet connectivity
  298. ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
  299. head, err = f.client.HeaderByNumber(ctx, nil)
  300. if err == nil {
  301. balance, err = f.client.BalanceAt(ctx, f.account.Address, head.Number)
  302. if err == nil {
  303. nonce, err = f.client.NonceAt(ctx, f.account.Address, nil)
  304. }
  305. }
  306. cancel()
  307. // If stats retrieval failed, wait a bit and retry
  308. if err != nil {
  309. if err = sendError(conn, errors.New("Faucet offline: "+err.Error())); err != nil {
  310. log.Warn("Failed to send faucet error to client", "err", err)
  311. return
  312. }
  313. time.Sleep(3 * time.Second)
  314. continue
  315. }
  316. // Initial stats reported successfully, proceed with user interaction
  317. break
  318. }
  319. // Send over the initial stats and the latest header
  320. if err = send(conn, map[string]interface{}{
  321. "funds": balance.Div(balance, ether),
  322. "funded": nonce,
  323. "peers": f.stack.Server().PeerCount(),
  324. "requests": f.reqs,
  325. }, 3*time.Second); err != nil {
  326. log.Warn("Failed to send initial stats to client", "err", err)
  327. return
  328. }
  329. if err = send(conn, head, 3*time.Second); err != nil {
  330. log.Warn("Failed to send initial header to client", "err", err)
  331. return
  332. }
  333. // Keep reading requests from the websocket until the connection breaks
  334. for {
  335. // Fetch the next funding request and validate against github
  336. var msg struct {
  337. URL string `json:"url"`
  338. Tier uint `json:"tier"`
  339. Captcha string `json:"captcha"`
  340. }
  341. if err = websocket.JSON.Receive(conn, &msg); err != nil {
  342. return
  343. }
  344. if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
  345. !strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
  346. if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil {
  347. log.Warn("Failed to send URL error to client", "err", err)
  348. return
  349. }
  350. continue
  351. }
  352. if msg.Tier >= uint(*tiersFlag) {
  353. if err = sendError(conn, errors.New("Invalid funding tier requested")); err != nil {
  354. log.Warn("Failed to send tier error to client", "err", err)
  355. return
  356. }
  357. continue
  358. }
  359. log.Info("Faucet funds requested", "url", msg.URL, "tier", msg.Tier)
  360. // If captcha verifications are enabled, make sure we're not dealing with a robot
  361. if *captchaToken != "" {
  362. form := url.Values{}
  363. form.Add("secret", *captchaSecret)
  364. form.Add("response", msg.Captcha)
  365. res, err := http.PostForm("https://www.google.com/recaptcha/api/siteverify", form)
  366. if err != nil {
  367. if err = sendError(conn, err); err != nil {
  368. log.Warn("Failed to send captcha post error to client", "err", err)
  369. return
  370. }
  371. continue
  372. }
  373. var result struct {
  374. Success bool `json:"success"`
  375. Errors json.RawMessage `json:"error-codes"`
  376. }
  377. err = json.NewDecoder(res.Body).Decode(&result)
  378. res.Body.Close()
  379. if err != nil {
  380. if err = sendError(conn, err); err != nil {
  381. log.Warn("Failed to send captcha decode error to client", "err", err)
  382. return
  383. }
  384. continue
  385. }
  386. if !result.Success {
  387. log.Warn("Captcha verification failed", "err", string(result.Errors))
  388. if err = sendError(conn, errors.New("Beep-bop, you're a robot!")); err != nil {
  389. log.Warn("Failed to send captcha failure to client", "err", err)
  390. return
  391. }
  392. continue
  393. }
  394. }
  395. // Retrieve the Ethereum address to fund, the requesting user and a profile picture
  396. var (
  397. username string
  398. avatar string
  399. address common.Address
  400. )
  401. switch {
  402. case strings.HasPrefix(msg.URL, "https://gist.github.com/"):
  403. if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil {
  404. log.Warn("Failed to send GitHub deprecation to client", "err", err)
  405. return
  406. }
  407. continue
  408. case strings.HasPrefix(msg.URL, "https://twitter.com/"):
  409. username, avatar, address, err = authTwitter(msg.URL)
  410. case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
  411. username, avatar, address, err = authGooglePlus(msg.URL)
  412. case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
  413. username, avatar, address, err = authFacebook(msg.URL)
  414. case *noauthFlag:
  415. username, avatar, address, err = authNoAuth(msg.URL)
  416. default:
  417. err = errors.New("Something funky happened, please open an issue at https://github.com/ethereum/go-ethereum/issues")
  418. }
  419. if err != nil {
  420. if err = sendError(conn, err); err != nil {
  421. log.Warn("Failed to send prefix error to client", "err", err)
  422. return
  423. }
  424. continue
  425. }
  426. log.Info("Faucet request valid", "url", msg.URL, "tier", msg.Tier, "user", username, "address", address)
  427. // Ensure the user didn't request funds too recently
  428. f.lock.Lock()
  429. var (
  430. fund bool
  431. timeout time.Time
  432. )
  433. if timeout = f.timeouts[username]; time.Now().After(timeout) {
  434. // User wasn't funded recently, create the funding transaction
  435. amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
  436. amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
  437. amount = new(big.Int).Div(amount, new(big.Int).Exp(big.NewInt(2), big.NewInt(int64(msg.Tier)), nil))
  438. tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, amount, 21000, f.price, nil)
  439. signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainID)
  440. if err != nil {
  441. f.lock.Unlock()
  442. if err = sendError(conn, err); err != nil {
  443. log.Warn("Failed to send transaction creation error to client", "err", err)
  444. return
  445. }
  446. continue
  447. }
  448. // Submit the transaction and mark as funded if successful
  449. if err := f.client.SendTransaction(context.Background(), signed); err != nil {
  450. f.lock.Unlock()
  451. if err = sendError(conn, err); err != nil {
  452. log.Warn("Failed to send transaction transmission error to client", "err", err)
  453. return
  454. }
  455. continue
  456. }
  457. f.reqs = append(f.reqs, &request{
  458. Avatar: avatar,
  459. Account: address,
  460. Time: time.Now(),
  461. Tx: signed,
  462. })
  463. f.timeouts[username] = time.Now().Add(time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute)
  464. fund = true
  465. }
  466. f.lock.Unlock()
  467. // Send an error if too frequent funding, othewise a success
  468. if !fund {
  469. if err = sendError(conn, fmt.Errorf("%s left until next allowance", common.PrettyDuration(timeout.Sub(time.Now())))); err != nil { // nolint: gosimple
  470. log.Warn("Failed to send funding error to client", "err", err)
  471. return
  472. }
  473. continue
  474. }
  475. if err = sendSuccess(conn, fmt.Sprintf("Funding request accepted for %s into %s", username, address.Hex())); err != nil {
  476. log.Warn("Failed to send funding success to client", "err", err)
  477. return
  478. }
  479. select {
  480. case f.update <- struct{}{}:
  481. default:
  482. }
  483. }
  484. }
  485. // loop keeps waiting for interesting events and pushes them out to connected
  486. // websockets.
  487. func (f *faucet) loop() {
  488. // Wait for chain events and push them to clients
  489. heads := make(chan *types.Header, 16)
  490. sub, err := f.client.SubscribeNewHead(context.Background(), heads)
  491. if err != nil {
  492. log.Crit("Failed to subscribe to head events", "err", err)
  493. }
  494. defer sub.Unsubscribe()
  495. // Start a goroutine to update the state from head notifications in the background
  496. update := make(chan *types.Header)
  497. go func() {
  498. for head := range update {
  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. }
  549. }()
  550. // Wait for various events and assing to the appropriate background threads
  551. for {
  552. select {
  553. case head := <-heads:
  554. // New head arrived, send if for state update if there's none running
  555. select {
  556. case update <- head:
  557. default:
  558. }
  559. case <-f.update:
  560. // Pending requests updated, stream to clients
  561. f.lock.RLock()
  562. for _, conn := range f.conns {
  563. if err := send(conn, map[string]interface{}{"requests": f.reqs}, time.Second); err != nil {
  564. log.Warn("Failed to send requests to client", "err", err)
  565. conn.Close()
  566. }
  567. }
  568. f.lock.RUnlock()
  569. }
  570. }
  571. }
  572. // sends transmits a data packet to the remote end of the websocket, but also
  573. // setting a write deadline to prevent waiting forever on the node.
  574. func send(conn *websocket.Conn, value interface{}, timeout time.Duration) error {
  575. if timeout == 0 {
  576. timeout = 60 * time.Second
  577. }
  578. conn.SetWriteDeadline(time.Now().Add(timeout))
  579. return websocket.JSON.Send(conn, value)
  580. }
  581. // sendError transmits an error to the remote end of the websocket, also setting
  582. // the write deadline to 1 second to prevent waiting forever.
  583. func sendError(conn *websocket.Conn, err error) error {
  584. return send(conn, map[string]string{"error": err.Error()}, time.Second)
  585. }
  586. // sendSuccess transmits a success message to the remote end of the websocket, also
  587. // setting the write deadline to 1 second to prevent waiting forever.
  588. func sendSuccess(conn *websocket.Conn, msg string) error {
  589. return send(conn, map[string]string{"success": msg}, time.Second)
  590. }
  591. // authTwitter tries to authenticate a faucet request using Twitter posts, returning
  592. // the username, avatar URL and Ethereum address to fund on success.
  593. func authTwitter(url string) (string, string, common.Address, error) {
  594. // Ensure the user specified a meaningful URL, no fancy nonsense
  595. parts := strings.Split(url, "/")
  596. if len(parts) < 4 || parts[len(parts)-2] != "status" {
  597. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  598. }
  599. // Twitter's API isn't really friendly with direct links. Still, we don't
  600. // want to do ask read permissions from users, so just load the public posts and
  601. // scrape it for the Ethereum address and profile URL.
  602. res, err := http.Get(url)
  603. if err != nil {
  604. return "", "", common.Address{}, err
  605. }
  606. defer res.Body.Close()
  607. // Resolve the username from the final redirect, no intermediate junk
  608. parts = strings.Split(res.Request.URL.String(), "/")
  609. if len(parts) < 4 || parts[len(parts)-2] != "status" {
  610. return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
  611. }
  612. username := parts[len(parts)-3]
  613. body, err := ioutil.ReadAll(res.Body)
  614. if err != nil {
  615. return "", "", common.Address{}, err
  616. }
  617. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  618. if address == (common.Address{}) {
  619. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  620. }
  621. var avatar string
  622. if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  623. avatar = parts[1]
  624. }
  625. return username + "@twitter", avatar, address, nil
  626. }
  627. // authGooglePlus tries to authenticate a faucet request using GooglePlus posts,
  628. // returning the username, avatar URL and Ethereum address to fund on success.
  629. func authGooglePlus(url string) (string, string, common.Address, error) {
  630. // Ensure the user specified a meaningful URL, no fancy nonsense
  631. parts := strings.Split(url, "/")
  632. if len(parts) < 4 || parts[len(parts)-2] != "posts" {
  633. return "", "", common.Address{}, errors.New("Invalid Google+ post URL")
  634. }
  635. username := parts[len(parts)-3]
  636. // Google's API isn't really friendly with direct links. Still, we don't
  637. // want to do ask read permissions from users, so just load the public posts and
  638. // scrape it for the Ethereum address and profile URL.
  639. res, err := http.Get(url)
  640. if err != nil {
  641. return "", "", common.Address{}, err
  642. }
  643. defer res.Body.Close()
  644. body, err := ioutil.ReadAll(res.Body)
  645. if err != nil {
  646. return "", "", common.Address{}, err
  647. }
  648. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  649. if address == (common.Address{}) {
  650. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  651. }
  652. var avatar string
  653. if parts = regexp.MustCompile("src=\"([^\"]+googleusercontent.com[^\"]+photo.jpg)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  654. avatar = parts[1]
  655. }
  656. return username + "@google+", avatar, address, nil
  657. }
  658. // authFacebook tries to authenticate a faucet request using Facebook posts,
  659. // returning the username, avatar URL and Ethereum address to fund on success.
  660. func authFacebook(url string) (string, string, common.Address, error) {
  661. // Ensure the user specified a meaningful URL, no fancy nonsense
  662. parts := strings.Split(url, "/")
  663. if len(parts) < 4 || parts[len(parts)-2] != "posts" {
  664. return "", "", common.Address{}, errors.New("Invalid Facebook post URL")
  665. }
  666. username := parts[len(parts)-3]
  667. // Facebook's Graph API isn't really friendly with direct links. Still, we don't
  668. // want to do ask read permissions from users, so just load the public posts and
  669. // scrape it for the Ethereum address and profile URL.
  670. res, err := http.Get(url)
  671. if err != nil {
  672. return "", "", common.Address{}, err
  673. }
  674. defer res.Body.Close()
  675. body, err := ioutil.ReadAll(res.Body)
  676. if err != nil {
  677. return "", "", common.Address{}, err
  678. }
  679. address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
  680. if address == (common.Address{}) {
  681. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  682. }
  683. var avatar string
  684. if parts = regexp.MustCompile("src=\"([^\"]+fbcdn.net[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
  685. avatar = parts[1]
  686. }
  687. return username + "@facebook", avatar, address, nil
  688. }
  689. // authNoAuth tries to interpret a faucet request as a plain Ethereum address,
  690. // without actually performing any remote authentication. This mode is prone to
  691. // Byzantine attack, so only ever use for truly private networks.
  692. func authNoAuth(url string) (string, string, common.Address, error) {
  693. address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(url))
  694. if address == (common.Address{}) {
  695. return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
  696. }
  697. return address.Hex() + "@noauth", "", address, nil
  698. }