faucet.go 32 KB

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