faucet.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. // Copyright 2017 The go-ethereum Authors
  2. // This file is part of go-ethereum.
  3. //
  4. // go-ethereum is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // go-ethereum is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with go-ethereum. If not, see <http://www.gnu.org/licenses/>.
  16. // faucet is a Ether faucet backed by a light client.
  17. package main
  18. //go:generate go-bindata -nometadata -o website.go faucet.html
  19. import (
  20. "bytes"
  21. "context"
  22. "encoding/json"
  23. "flag"
  24. "fmt"
  25. "html/template"
  26. "io/ioutil"
  27. "math/big"
  28. "net/http"
  29. "os"
  30. "path/filepath"
  31. "strings"
  32. "sync"
  33. "time"
  34. "github.com/ethereum/go-ethereum/accounts"
  35. "github.com/ethereum/go-ethereum/accounts/keystore"
  36. "github.com/ethereum/go-ethereum/common"
  37. "github.com/ethereum/go-ethereum/core"
  38. "github.com/ethereum/go-ethereum/core/types"
  39. "github.com/ethereum/go-ethereum/eth"
  40. "github.com/ethereum/go-ethereum/ethclient"
  41. "github.com/ethereum/go-ethereum/ethstats"
  42. "github.com/ethereum/go-ethereum/les"
  43. "github.com/ethereum/go-ethereum/log"
  44. "github.com/ethereum/go-ethereum/node"
  45. "github.com/ethereum/go-ethereum/p2p/discover"
  46. "github.com/ethereum/go-ethereum/p2p/discv5"
  47. "github.com/ethereum/go-ethereum/p2p/nat"
  48. "github.com/ethereum/go-ethereum/params"
  49. "golang.org/x/net/websocket"
  50. )
  51. var (
  52. genesisFlag = flag.String("genesis", "", "Genesis json file to seed the chain with")
  53. apiPortFlag = flag.Int("apiport", 8080, "Listener port for the HTTP API connection")
  54. ethPortFlag = flag.Int("ethport", 30303, "Listener port for the devp2p connection")
  55. bootFlag = flag.String("bootnodes", "", "Comma separated bootnode enode URLs to seed with")
  56. netFlag = flag.Int("network", 0, "Network ID to use for the Ethereum protocol")
  57. statsFlag = flag.String("ethstats", "", "Ethstats network monitoring auth string")
  58. netnameFlag = flag.String("faucet.name", "", "Network name to assign to the faucet")
  59. payoutFlag = flag.Int("faucet.amount", 1, "Number of Ethers to pay out per user request")
  60. minutesFlag = flag.Int("faucet.minutes", 1440, "Number of minutes to wait between funding rounds")
  61. accJSONFlag = flag.String("account.json", "", "Key json file to fund user requests with")
  62. accPassFlag = flag.String("account.pass", "", "Decryption password to access faucet funds")
  63. githubUser = flag.String("github.user", "", "GitHub user to authenticate with for Gist access")
  64. githubToken = flag.String("github.token", "", "GitHub personal token to access Gists with")
  65. logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet")
  66. )
  67. var (
  68. ether = new(big.Int).Exp(big.NewInt(10), big.NewInt(18), nil)
  69. )
  70. func main() {
  71. // Parse the flags and set up the logger to print everything requested
  72. flag.Parse()
  73. log.Root().SetHandler(log.LvlFilterHandler(log.Lvl(*logFlag), log.StreamHandler(os.Stderr, log.TerminalFormat(true))))
  74. // Load up and render the faucet website
  75. tmpl, err := Asset("faucet.html")
  76. if err != nil {
  77. log.Crit("Failed to load the faucet template", "err", err)
  78. }
  79. period := fmt.Sprintf("%d minute(s)", *minutesFlag)
  80. if *minutesFlag%60 == 0 {
  81. period = fmt.Sprintf("%d hour(s)", *minutesFlag/60)
  82. }
  83. website := new(bytes.Buffer)
  84. template.Must(template.New("").Parse(string(tmpl))).Execute(website, map[string]interface{}{
  85. "Network": *netnameFlag,
  86. "Amount": *payoutFlag,
  87. "Period": period,
  88. })
  89. // Load and parse the genesis block requested by the user
  90. blob, err := ioutil.ReadFile(*genesisFlag)
  91. if err != nil {
  92. log.Crit("Failed to read genesis block contents", "genesis", *genesisFlag, "err", err)
  93. }
  94. genesis := new(core.Genesis)
  95. if err = json.Unmarshal(blob, genesis); err != nil {
  96. log.Crit("Failed to parse genesis block json", "err", err)
  97. }
  98. // Convert the bootnodes to internal enode representations
  99. var enodes []*discv5.Node
  100. for _, boot := range strings.Split(*bootFlag, ",") {
  101. if url, err := discv5.ParseNode(boot); err == nil {
  102. enodes = append(enodes, url)
  103. } else {
  104. log.Error("Failed to parse bootnode URL", "url", boot, "err", err)
  105. }
  106. }
  107. // Load up the account key and decrypt its password
  108. if blob, err = ioutil.ReadFile(*accPassFlag); err != nil {
  109. log.Crit("Failed to read account password contents", "file", *accPassFlag, "err", err)
  110. }
  111. pass := string(blob)
  112. ks := keystore.NewKeyStore(filepath.Join(os.Getenv("HOME"), ".faucet", "keys"), keystore.StandardScryptN, keystore.StandardScryptP)
  113. if blob, err = ioutil.ReadFile(*accJSONFlag); err != nil {
  114. log.Crit("Failed to read account key contents", "file", *accJSONFlag, "err", err)
  115. }
  116. acc, err := ks.Import(blob, pass, pass)
  117. if err != nil {
  118. log.Crit("Failed to import faucet signer account", "err", err)
  119. }
  120. ks.Unlock(acc, pass)
  121. // Assemble and start the faucet light service
  122. faucet, err := newFaucet(genesis, *ethPortFlag, enodes, *netFlag, *statsFlag, ks, website.Bytes())
  123. if err != nil {
  124. log.Crit("Failed to start faucet", "err", err)
  125. }
  126. defer faucet.close()
  127. if err := faucet.listenAndServe(*apiPortFlag); err != nil {
  128. log.Crit("Failed to launch faucet API", "err", err)
  129. }
  130. }
  131. // request represents an accepted funding request.
  132. type request struct {
  133. Username string `json:"username"` // GitHub user for displaying an avatar
  134. Account common.Address `json:"account"` // Ethereum address being funded
  135. Time time.Time `json:"time"` // Timestamp when te request was accepted
  136. Tx *types.Transaction `json:"tx"` // Transaction funding the account
  137. }
  138. // faucet represents a crypto faucet backed by an Ethereum light client.
  139. type faucet struct {
  140. config *params.ChainConfig // Chain configurations for signing
  141. stack *node.Node // Ethereum protocol stack
  142. client *ethclient.Client // Client connection to the Ethereum chain
  143. index []byte // Index page to serve up on the web
  144. keystore *keystore.KeyStore // Keystore containing the single signer
  145. account accounts.Account // Account funding user faucet requests
  146. nonce uint64 // Current pending nonce of the faucet
  147. price *big.Int // Current gas price to issue funds with
  148. conns []*websocket.Conn // Currently live websocket connections
  149. history map[string]time.Time // History of users and their funding requests
  150. reqs []*request // Currently pending funding requests
  151. update chan struct{} // Channel to signal request updates
  152. lock sync.RWMutex // Lock protecting the faucet's internals
  153. }
  154. func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network int, stats string, ks *keystore.KeyStore, index []byte) (*faucet, error) {
  155. // Assemble the raw devp2p protocol stack
  156. stack, err := node.New(&node.Config{
  157. Name: "geth",
  158. Version: params.Version,
  159. DataDir: filepath.Join(os.Getenv("HOME"), ".faucet"),
  160. NAT: nat.Any(),
  161. DiscoveryV5: true,
  162. ListenAddr: fmt.Sprintf(":%d", port),
  163. DiscoveryV5Addr: fmt.Sprintf(":%d", port+1),
  164. MaxPeers: 25,
  165. BootstrapNodesV5: enodes,
  166. })
  167. if err != nil {
  168. return nil, err
  169. }
  170. // Assemble the Ethereum light client protocol
  171. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  172. return les.New(ctx, &eth.Config{
  173. LightMode: true,
  174. NetworkId: network,
  175. Genesis: genesis,
  176. GasPrice: big.NewInt(20 * params.Shannon),
  177. GpoBlocks: 10,
  178. GpoPercentile: 50,
  179. EthashCacheDir: "ethash",
  180. EthashCachesInMem: 2,
  181. EthashCachesOnDisk: 3,
  182. })
  183. }); err != nil {
  184. return nil, err
  185. }
  186. // Assemble the ethstats monitoring and reporting service'
  187. if stats != "" {
  188. if err := stack.Register(func(ctx *node.ServiceContext) (node.Service, error) {
  189. var serv *les.LightEthereum
  190. ctx.Service(&serv)
  191. return ethstats.New(stats, nil, serv)
  192. }); err != nil {
  193. return nil, err
  194. }
  195. }
  196. // Boot up the client and ensure it connects to bootnodes
  197. if err := stack.Start(); err != nil {
  198. return nil, err
  199. }
  200. for _, boot := range enodes {
  201. old, _ := discover.ParseNode(boot.String())
  202. stack.Server().AddPeer(old)
  203. }
  204. // Attach to the client and retrieve and interesting metadatas
  205. api, err := stack.Attach()
  206. if err != nil {
  207. stack.Stop()
  208. return nil, err
  209. }
  210. client := ethclient.NewClient(api)
  211. return &faucet{
  212. config: genesis.Config,
  213. stack: stack,
  214. client: client,
  215. index: index,
  216. keystore: ks,
  217. account: ks.Accounts()[0],
  218. history: make(map[string]time.Time),
  219. update: make(chan struct{}, 1),
  220. }, nil
  221. }
  222. // close terminates the Ethereum connection and tears down the faucet.
  223. func (f *faucet) close() error {
  224. return f.stack.Stop()
  225. }
  226. // listenAndServe registers the HTTP handlers for the faucet and boots it up
  227. // for service user funding requests.
  228. func (f *faucet) listenAndServe(port int) error {
  229. go f.loop()
  230. http.HandleFunc("/", f.webHandler)
  231. http.Handle("/api", websocket.Handler(f.apiHandler))
  232. return http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
  233. }
  234. // webHandler handles all non-api requests, simply flattening and returning the
  235. // faucet website.
  236. func (f *faucet) webHandler(w http.ResponseWriter, r *http.Request) {
  237. w.Write(f.index)
  238. }
  239. // apiHandler handles requests for Ether grants and transaction statuses.
  240. func (f *faucet) apiHandler(conn *websocket.Conn) {
  241. // Start tracking the connection and drop at the end
  242. f.lock.Lock()
  243. f.conns = append(f.conns, conn)
  244. f.lock.Unlock()
  245. defer func() {
  246. f.lock.Lock()
  247. for i, c := range f.conns {
  248. if c == conn {
  249. f.conns = append(f.conns[:i], f.conns[i+1:]...)
  250. break
  251. }
  252. }
  253. f.lock.Unlock()
  254. }()
  255. // Send a few initial stats to the client
  256. balance, _ := f.client.BalanceAt(context.Background(), f.account.Address, nil)
  257. nonce, _ := f.client.NonceAt(context.Background(), f.account.Address, nil)
  258. websocket.JSON.Send(conn, map[string]interface{}{
  259. "funds": balance.Div(balance, ether),
  260. "funded": nonce,
  261. "peers": f.stack.Server().PeerCount(),
  262. "requests": f.reqs,
  263. })
  264. header, _ := f.client.HeaderByNumber(context.Background(), nil)
  265. websocket.JSON.Send(conn, header)
  266. // Keep reading requests from the websocket until the connection breaks
  267. for {
  268. // Fetch the next funding request and validate against github
  269. var msg struct {
  270. URL string `json:"url"`
  271. }
  272. if err := websocket.JSON.Receive(conn, &msg); err != nil {
  273. return
  274. }
  275. if !strings.HasPrefix(msg.URL, "https://gist.github.com/") {
  276. websocket.JSON.Send(conn, map[string]string{"error": "URL doesn't link to GitHub Gists"})
  277. continue
  278. }
  279. log.Info("Faucet funds requested", "gist", msg.URL)
  280. // Retrieve the gist from the GitHub Gist APIs
  281. parts := strings.Split(msg.URL, "/")
  282. req, _ := http.NewRequest("GET", "https://api.github.com/gists/"+parts[len(parts)-1], nil)
  283. if *githubUser != "" {
  284. req.SetBasicAuth(*githubUser, *githubToken)
  285. }
  286. res, err := http.DefaultClient.Do(req)
  287. if err != nil {
  288. websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
  289. continue
  290. }
  291. var gist struct {
  292. Owner struct {
  293. Login string `json:"login"`
  294. } `json:"owner"`
  295. Files map[string]struct {
  296. Content string `json:"content"`
  297. } `json:"files"`
  298. }
  299. err = json.NewDecoder(res.Body).Decode(&gist)
  300. res.Body.Close()
  301. if err != nil {
  302. websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
  303. continue
  304. }
  305. if gist.Owner.Login == "" {
  306. websocket.JSON.Send(conn, map[string]string{"error": "Nice try ;)"})
  307. continue
  308. }
  309. // Iterate over all the files and look for Ethereum addresses
  310. var address common.Address
  311. for _, file := range gist.Files {
  312. if len(file.Content) == 2+common.AddressLength*2 {
  313. address = common.HexToAddress(file.Content)
  314. }
  315. }
  316. if address == (common.Address{}) {
  317. websocket.JSON.Send(conn, map[string]string{"error": "No Ethereum address found to fund"})
  318. continue
  319. }
  320. // Ensure the user didn't request funds too recently
  321. f.lock.Lock()
  322. var (
  323. fund bool
  324. elapsed time.Duration
  325. )
  326. if elapsed = time.Since(f.history[gist.Owner.Login]); elapsed > time.Duration(*minutesFlag)*time.Minute {
  327. // User wasn't funded recently, create the funding transaction
  328. tx := types.NewTransaction(f.nonce+uint64(len(f.reqs)), address, new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether), big.NewInt(21000), f.price, nil)
  329. signed, err := f.keystore.SignTx(f.account, tx, f.config.ChainId)
  330. if err != nil {
  331. websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
  332. f.lock.Unlock()
  333. continue
  334. }
  335. // Submit the transaction and mark as funded if successful
  336. if err := f.client.SendTransaction(context.Background(), signed); err != nil {
  337. websocket.JSON.Send(conn, map[string]string{"error": err.Error()})
  338. f.lock.Unlock()
  339. continue
  340. }
  341. f.reqs = append(f.reqs, &request{
  342. Username: gist.Owner.Login,
  343. Account: address,
  344. Time: time.Now(),
  345. Tx: signed,
  346. })
  347. f.history[gist.Owner.Login] = time.Now()
  348. fund = true
  349. }
  350. f.lock.Unlock()
  351. // Send an error if too frequent funding, othewise a success
  352. if !fund {
  353. websocket.JSON.Send(conn, map[string]string{"error": fmt.Sprintf("User already funded %s ago", common.PrettyDuration(elapsed))})
  354. continue
  355. }
  356. websocket.JSON.Send(conn, map[string]string{"success": fmt.Sprintf("Funding request accepted for %s into %s", gist.Owner.Login, address.Hex())})
  357. select {
  358. case f.update <- struct{}{}:
  359. default:
  360. }
  361. }
  362. }
  363. // loop keeps waiting for interesting events and pushes them out to connected
  364. // websockets.
  365. func (f *faucet) loop() {
  366. // Wait for chain events and push them to clients
  367. heads := make(chan *types.Header, 16)
  368. sub, err := f.client.SubscribeNewHead(context.Background(), heads)
  369. if err != nil {
  370. log.Crit("Failed to subscribe to head events", "err", err)
  371. }
  372. defer sub.Unsubscribe()
  373. for {
  374. select {
  375. case head := <-heads:
  376. // New chain head arrived, query the current stats and stream to clients
  377. balance, _ := f.client.BalanceAt(context.Background(), f.account.Address, nil)
  378. balance = new(big.Int).Div(balance, ether)
  379. price, _ := f.client.SuggestGasPrice(context.Background())
  380. nonce, _ := f.client.NonceAt(context.Background(), f.account.Address, nil)
  381. f.lock.Lock()
  382. f.price, f.nonce = price, nonce
  383. for len(f.reqs) > 0 && f.reqs[0].Tx.Nonce() < f.nonce {
  384. f.reqs = f.reqs[1:]
  385. }
  386. f.lock.Unlock()
  387. f.lock.RLock()
  388. for _, conn := range f.conns {
  389. if err := websocket.JSON.Send(conn, map[string]interface{}{
  390. "funds": balance,
  391. "funded": f.nonce,
  392. "peers": f.stack.Server().PeerCount(),
  393. "requests": f.reqs,
  394. }); err != nil {
  395. log.Warn("Failed to send stats to client", "err", err)
  396. conn.Close()
  397. continue
  398. }
  399. if err := websocket.JSON.Send(conn, head); err != nil {
  400. log.Warn("Failed to send header to client", "err", err)
  401. conn.Close()
  402. }
  403. }
  404. f.lock.RUnlock()
  405. case <-f.update:
  406. // Pending requests updated, stream to clients
  407. f.lock.RLock()
  408. for _, conn := range f.conns {
  409. if err := websocket.JSON.Send(conn, map[string]interface{}{"requests": f.reqs}); err != nil {
  410. log.Warn("Failed to send requests to client", "err", err)
  411. conn.Close()
  412. }
  413. }
  414. f.lock.RUnlock()
  415. }
  416. }
  417. }