faucet.go 32 KB

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