module_faucet.go 9.3 KB

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