module_faucet.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  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. package main
  17. import (
  18. "bytes"
  19. "encoding/json"
  20. "fmt"
  21. "html/template"
  22. "math/rand"
  23. "path/filepath"
  24. "strconv"
  25. "strings"
  26. "github.com/ethereum/go-ethereum/common"
  27. "github.com/ethereum/go-ethereum/log"
  28. )
  29. // faucetDockerfile is the Dockerfile required to build a faucet container to
  30. // grant crypto tokens based on GitHub authentications.
  31. var faucetDockerfile = `
  32. FROM ethereum/client-go:alltools-latest
  33. ADD genesis.json /genesis.json
  34. ADD account.json /account.json
  35. ADD account.pass /account.pass
  36. EXPOSE 8080 30303 30303/udp
  37. ENTRYPOINT [ \
  38. "faucet", "--genesis", "/genesis.json", "--network", "{{.NetworkID}}", "--bootnodes", "{{.Bootnodes}}", "--ethstats", "{{.Ethstats}}", "--ethport", "{{.EthPort}}", \
  39. "--faucet.name", "{{.FaucetName}}", "--faucet.amount", "{{.FaucetAmount}}", "--faucet.minutes", "{{.FaucetMinutes}}", "--faucet.tiers", "{{.FaucetTiers}}", \
  40. "--account.json", "/account.json", "--account.pass", "/account.pass" \
  41. {{if .CaptchaToken}}, "--captcha.token", "{{.CaptchaToken}}", "--captcha.secret", "{{.CaptchaSecret}}"{{end}}{{if .NoAuth}}, "--noauth"{{end}} \
  42. ]`
  43. // faucetComposefile is the docker-compose.yml file required to deploy and maintain
  44. // a crypto faucet.
  45. var faucetComposefile = `
  46. version: '2'
  47. services:
  48. faucet:
  49. build: .
  50. image: {{.Network}}/faucet
  51. container_name: {{.Network}}_faucet_1
  52. ports:
  53. - "{{.EthPort}}:{{.EthPort}}"
  54. - "{{.EthPort}}:{{.EthPort}}/udp"{{if not .VHost}}
  55. - "{{.ApiPort}}:8080"{{end}}
  56. volumes:
  57. - {{.Datadir}}:/root/.faucet
  58. environment:
  59. - ETH_PORT={{.EthPort}}
  60. - ETH_NAME={{.EthName}}
  61. - FAUCET_AMOUNT={{.FaucetAmount}}
  62. - FAUCET_MINUTES={{.FaucetMinutes}}
  63. - FAUCET_TIERS={{.FaucetTiers}}
  64. - CAPTCHA_TOKEN={{.CaptchaToken}}
  65. - CAPTCHA_SECRET={{.CaptchaSecret}}
  66. - NO_AUTH={{.NoAuth}}{{if .VHost}}
  67. - VIRTUAL_HOST={{.VHost}}
  68. - VIRTUAL_PORT=8080{{end}}
  69. logging:
  70. driver: "json-file"
  71. options:
  72. max-size: "1m"
  73. max-file: "10"
  74. restart: always
  75. `
  76. // deployFaucet deploys a new faucet container to a remote machine via SSH,
  77. // docker and docker-compose. If an instance with the specified network name
  78. // already exists there, it will be overwritten!
  79. func deployFaucet(client *sshClient, network string, bootnodes []string, config *faucetInfos, nocache bool) ([]byte, error) {
  80. // Generate the content to upload to the server
  81. workdir := fmt.Sprintf("%d", rand.Int63())
  82. files := make(map[string][]byte)
  83. dockerfile := new(bytes.Buffer)
  84. template.Must(template.New("").Parse(faucetDockerfile)).Execute(dockerfile, map[string]interface{}{
  85. "NetworkID": config.node.network,
  86. "Bootnodes": strings.Join(bootnodes, ","),
  87. "Ethstats": config.node.ethstats,
  88. "EthPort": config.node.port,
  89. "CaptchaToken": config.captchaToken,
  90. "CaptchaSecret": config.captchaSecret,
  91. "FaucetName": strings.Title(network),
  92. "FaucetAmount": config.amount,
  93. "FaucetMinutes": config.minutes,
  94. "FaucetTiers": config.tiers,
  95. "NoAuth": config.noauth,
  96. })
  97. files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
  98. composefile := new(bytes.Buffer)
  99. template.Must(template.New("").Parse(faucetComposefile)).Execute(composefile, map[string]interface{}{
  100. "Network": network,
  101. "Datadir": config.node.datadir,
  102. "VHost": config.host,
  103. "ApiPort": config.port,
  104. "EthPort": config.node.port,
  105. "EthName": config.node.ethstats[:strings.Index(config.node.ethstats, ":")],
  106. "CaptchaToken": config.captchaToken,
  107. "CaptchaSecret": config.captchaSecret,
  108. "FaucetAmount": config.amount,
  109. "FaucetMinutes": config.minutes,
  110. "FaucetTiers": config.tiers,
  111. "NoAuth": config.noauth,
  112. })
  113. files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
  114. files[filepath.Join(workdir, "genesis.json")] = config.node.genesis
  115. files[filepath.Join(workdir, "account.json")] = []byte(config.node.keyJSON)
  116. files[filepath.Join(workdir, "account.pass")] = []byte(config.node.keyPass)
  117. // Upload the deployment files to the remote server (and clean up afterwards)
  118. if out, err := client.Upload(files); err != nil {
  119. return out, err
  120. }
  121. defer client.Run("rm -rf " + workdir)
  122. // Build and deploy the faucet service
  123. if nocache {
  124. return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s build --pull --no-cache && docker-compose -p %s up -d --force-recreate --timeout 60", workdir, network, network))
  125. }
  126. return nil, client.Stream(fmt.Sprintf("cd %s && docker-compose -p %s up -d --build --force-recreate --timeout 60", workdir, network))
  127. }
  128. // faucetInfos is returned from a faucet status check to allow reporting various
  129. // configuration parameters.
  130. type faucetInfos struct {
  131. node *nodeInfos
  132. host string
  133. port int
  134. amount int
  135. minutes int
  136. tiers int
  137. noauth bool
  138. captchaToken string
  139. captchaSecret string
  140. }
  141. // Report converts the typed struct into a plain string->string map, containing
  142. // most - but not all - fields for reporting to the user.
  143. func (info *faucetInfos) Report() map[string]string {
  144. report := map[string]string{
  145. "Website address": info.host,
  146. "Website listener port": strconv.Itoa(info.port),
  147. "Ethereum listener port": strconv.Itoa(info.node.port),
  148. "Funding amount (base tier)": fmt.Sprintf("%d Ethers", info.amount),
  149. "Funding cooldown (base tier)": fmt.Sprintf("%d mins", info.minutes),
  150. "Funding tiers": strconv.Itoa(info.tiers),
  151. "Captha protection": fmt.Sprintf("%v", info.captchaToken != ""),
  152. "Ethstats username": info.node.ethstats,
  153. }
  154. if info.noauth {
  155. report["Debug mode (no auth)"] = "enabled"
  156. }
  157. if info.node.keyJSON != "" {
  158. var key struct {
  159. Address string `json:"address"`
  160. }
  161. if err := json.Unmarshal([]byte(info.node.keyJSON), &key); err == nil {
  162. report["Funding account"] = common.HexToAddress(key.Address).Hex()
  163. } else {
  164. log.Error("Failed to retrieve signer address", "err", err)
  165. }
  166. }
  167. return report
  168. }
  169. // checkFaucet does a health-check against a faucet server to verify whether
  170. // it's running, and if yes, gathering a collection of useful infos about it.
  171. func checkFaucet(client *sshClient, network string) (*faucetInfos, error) {
  172. // Inspect a possible faucet container on the host
  173. infos, err := inspectContainer(client, fmt.Sprintf("%s_faucet_1", network))
  174. if err != nil {
  175. return nil, err
  176. }
  177. if !infos.running {
  178. return nil, ErrServiceOffline
  179. }
  180. // Resolve the port from the host, or the reverse proxy
  181. port := infos.portmap["8080/tcp"]
  182. if port == 0 {
  183. if proxy, _ := checkNginx(client, network); proxy != nil {
  184. port = proxy.port
  185. }
  186. }
  187. if port == 0 {
  188. return nil, ErrNotExposed
  189. }
  190. // Resolve the host from the reverse-proxy and the config values
  191. host := infos.envvars["VIRTUAL_HOST"]
  192. if host == "" {
  193. host = client.server
  194. }
  195. amount, _ := strconv.Atoi(infos.envvars["FAUCET_AMOUNT"])
  196. minutes, _ := strconv.Atoi(infos.envvars["FAUCET_MINUTES"])
  197. tiers, _ := strconv.Atoi(infos.envvars["FAUCET_TIERS"])
  198. // Retrieve the funding account information
  199. var out []byte
  200. keyJSON, keyPass := "", ""
  201. if out, err = client.Run(fmt.Sprintf("docker exec %s_faucet_1 cat /account.json", network)); err == nil {
  202. keyJSON = string(bytes.TrimSpace(out))
  203. }
  204. if out, err = client.Run(fmt.Sprintf("docker exec %s_faucet_1 cat /account.pass", network)); err == nil {
  205. keyPass = string(bytes.TrimSpace(out))
  206. }
  207. // Run a sanity check to see if the port is reachable
  208. if err = checkPort(host, port); err != nil {
  209. log.Warn("Faucet service seems unreachable", "server", host, "port", port, "err", err)
  210. }
  211. // Container available, assemble and return the useful infos
  212. return &faucetInfos{
  213. node: &nodeInfos{
  214. datadir: infos.volumes["/root/.faucet"],
  215. port: infos.portmap[infos.envvars["ETH_PORT"]+"/tcp"],
  216. ethstats: infos.envvars["ETH_NAME"],
  217. keyJSON: keyJSON,
  218. keyPass: keyPass,
  219. },
  220. host: host,
  221. port: port,
  222. amount: amount,
  223. minutes: minutes,
  224. tiers: tiers,
  225. captchaToken: infos.envvars["CAPTCHA_TOKEN"],
  226. captchaSecret: infos.envvars["CAPTCHA_SECRET"],
  227. noauth: infos.envvars["NO_AUTH"] == "true",
  228. }, nil
  229. }