faucet.go 36 KB

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