Skip to content

Commit 6ada9f0

Browse files
authored
Merge pull request #22107 from karalabe/faucet-twitter
cmd: support v1.1 Twitter API in faucet, fix puppeth
2 parents 1951e20 + e4571d8 commit 6ada9f0

4 files changed

Lines changed: 118 additions & 52 deletions

File tree

‎cmd/faucet/README.md‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Faucet
2+
3+
The `faucet` is a simplistic web application with the goal of distributing small amounts of Ether in private and test networks.
4+
5+
Users need to post their Ethereum addresses to fund in a Twitter status update or public Facebook post and share the link to the faucet. The faucet will in turn deduplicate user requests and send the Ether. After a funding round, the faucet prevents the same user requesting again for a pre-configured amount of time, proportional to the amount of Ether requested.
6+
7+
## Operation
8+
9+
The `faucet` is a single binary app (everything included) with all configurations set via command line flags and a few files.
10+
11+
First thing's first, the `faucet` needs to connect to an Ethereum network, for which it needs the necessary genesis and network infos. Each of the following flags must be set:
12+
13+
- `--genesis` is a path to a file containin the network `genesis.json`
14+
- `--network` is the devp2p network id used during connection
15+
- `--bootnodes` is a list of `enode://` ids to join the network through
16+
17+
The `faucet` will use the `les` protocol to join the configured Ethereum network and will store its data in `$HOME/.faucet` (currently not configurable).
18+
19+
## Funding
20+
21+
To be able to distribute funds, the `faucet` needs access to an already funded Ethereum account. This can be configured via:
22+
23+
- `--account.json` is a path to the Ethereum account's JSON key file
24+
- `--account.pass` is a path to a text file with the decryption passphrase
25+
26+
The faucet is able to distribute various amounts of Ether in exchange for various timeouts. These can be configured via:
27+
28+
- `--faucet.amount` is the number of Ethers to send by default
29+
- `--faucet.minutes` is the time to wait before allowing a rerequest
30+
- `--faucet.tiers` is the funding tiers to support (x3 time, x2.5 funds)
31+
32+
## Sybil protection
33+
34+
To prevent the same user from exhausting funds in a loop, the `faucet` ties requests to social networks and captcha resolvers.
35+
36+
Captcha protection uses Google's invisible ReCaptcha, thus the `faucet` needs to run on a live domain. The domain needs to be registered in Google's systems to retrieve the captcha API token and secrets. After doing so, captcha protection may be enabled via:
37+
38+
- `--captcha.token` is the API token for ReCaptcha
39+
- `--captcha.secret` is the API secret for ReCaptcha
40+
41+
Sybil protection via Twitter requires an API key as of 15th December, 2020. To obtain it, a Twitter user must be upgraded to developer status and a new Twitter App deployed with it. The app's `Bearer` token is required by the faucet to retrieve tweet data:
42+
43+
- `--twitter.token` is the Bearer token for `v2` API access
44+
- `--twitter.token.v1` is the Bearer token for `v1` API access
45+
46+
Sybil protection via Facebook uses the website to directly download post data thus does not currently require an API configuration.
47+
48+
## Miscellaneous
49+
50+
Beside the above - mostly essential - CLI flags, there are a number that can be used to fine tune the `faucet`'s operation. Please see `faucet --help` for a full list.

‎cmd/faucet/faucet.go‎

Lines changed: 62 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,8 @@ var (
8484
noauthFlag = flag.Bool("noauth", false, "Enables funding requests without authentication")
8585
logFlag = flag.Int("loglevel", 3, "Log level to use for Ethereum and the faucet")
8686

87-
twitterBearerToken = flag.String("twitter.token", "", "Twitter bearer token to authenticate with the twitter API")
87+
twitterTokenFlag = flag.String("twitter.token", "", "Bearer token to authenticate with the v2 Twitter API")
88+
twitterTokenV1Flag = flag.String("twitter.token.v1", "", "Bearer token to authenticate with the v1.1 Twitter API")
8889
)
8990

9091
var (
@@ -245,6 +246,7 @@ func newFaucet(genesis *core.Genesis, port int, enodes []*discv5.Node, network u
245246
cfg.NetworkId = network
246247
cfg.Genesis = genesis
247248
utils.SetDNSDiscoveryDefaults(&cfg, genesis.ToBlock(nil).Hash())
249+
248250
lesBackend, err := les.New(stack, &cfg)
249251
if err != nil {
250252
return nil, fmt.Errorf("Failed to register the Ethereum service: %w", err)
@@ -388,8 +390,7 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
388390
if err = conn.ReadJSON(&msg); err != nil {
389391
return
390392
}
391-
if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://gist.github.com/") && !strings.HasPrefix(msg.URL, "https://twitter.com/") &&
392-
!strings.HasPrefix(msg.URL, "https://plus.google.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
393+
if !*noauthFlag && !strings.HasPrefix(msg.URL, "https://twitter.com/") && !strings.HasPrefix(msg.URL, "https://www.facebook.com/") {
393394
if err = sendError(conn, errors.New("URL doesn't link to supported services")); err != nil {
394395
log.Warn("Failed to send URL error to client", "err", err)
395396
return
@@ -451,21 +452,8 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
451452
address common.Address
452453
)
453454
switch {
454-
case strings.HasPrefix(msg.URL, "https://gist.github.com/"):
455-
if err = sendError(conn, errors.New("GitHub authentication discontinued at the official request of GitHub")); err != nil {
456-
log.Warn("Failed to send GitHub deprecation to client", "err", err)
457-
return
458-
}
459-
continue
460-
case strings.HasPrefix(msg.URL, "https://plus.google.com/"):
461-
//lint:ignore ST1005 Google is a company name and should be capitalized.
462-
if err = sendError(conn, errors.New("Google+ authentication discontinued as the service was sunset")); err != nil {
463-
log.Warn("Failed to send Google+ deprecation to client", "err", err)
464-
return
465-
}
466-
continue
467455
case strings.HasPrefix(msg.URL, "https://twitter.com/"):
468-
id, username, avatar, address, err = authTwitter(msg.URL, *twitterBearerToken)
456+
id, username, avatar, address, err = authTwitter(msg.URL, *twitterTokenV1Flag, *twitterTokenFlag)
469457
case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
470458
username, avatar, address, err = authFacebook(msg.URL)
471459
id = username
@@ -690,23 +678,31 @@ func sendSuccess(conn *websocket.Conn, msg string) error {
690678

691679
// authTwitter tries to authenticate a faucet request using Twitter posts, returning
692680
// the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success.
693-
func authTwitter(url string, token string) (string, string, string, common.Address, error) {
681+
func authTwitter(url string, tokenV1, tokenV2 string) (string, string, string, common.Address, error) {
694682
// Ensure the user specified a meaningful URL, no fancy nonsense
695683
parts := strings.Split(url, "/")
696684
if len(parts) < 4 || parts[len(parts)-2] != "status" {
697685
//lint:ignore ST1005 This error is to be displayed in the browser
698686
return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
699687
}
700-
688+
// Strip any query parameters from the tweet id and ensure it's numeric
689+
tweetID := strings.Split(parts[len(parts)-1], "?")[0]
690+
if !regexp.MustCompile("^[0-9]+$").MatchString(tweetID) {
691+
return "", "", "", common.Address{}, errors.New("Invalid Tweet URL")
692+
}
701693
// Twitter's API isn't really friendly with direct links.
702694
// It is restricted to 300 queries / 15 minute with an app api key.
703695
// Anything more will require read only authorization from the users and that we want to avoid.
704696

705-
// If twitter bearer token is provided, use the twitter api
706-
if token != "" {
707-
return authTwitterWithToken(parts[len(parts)-1], token)
697+
// If Twitter bearer token is provided, use the API, selecting the version
698+
// the user would prefer (currently there's a limit of 1 v2 app / developer
699+
// but unlimited v1.1 apps).
700+
switch {
701+
case tokenV1 != "":
702+
return authTwitterWithTokenV1(tweetID, tokenV1)
703+
case tokenV2 != "":
704+
return authTwitterWithTokenV2(tweetID, tokenV2)
708705
}
709-
710706
// Twiter API token isn't provided so we just load the public posts
711707
// and scrape it for the Ethereum address and profile URL. We need to load
712708
// the mobile page though since the main page loads tweet contents via JS.
@@ -742,19 +738,49 @@ func authTwitter(url string, token string) (string, string, string, common.Addre
742738
return username + "@twitter", username, avatar, address, nil
743739
}
744740

745-
// authTwitterWithToken tries to authenticate a faucet request using Twitter's API, returning
746-
// the uniqueness identifier (user id/username), username, avatar URL and Ethereum address to fund on success.
747-
func authTwitterWithToken(tweetID string, token string) (string, string, string, common.Address, error) {
748-
// Strip any query parameters from the tweet id
749-
sanitizedTweetID := strings.Split(tweetID, "?")[0]
741+
// authTwitterWithTokenV1 tries to authenticate a faucet request using Twitter's v1
742+
// API, returning the user id, username, avatar URL and Ethereum address to fund on
743+
// success.
744+
func authTwitterWithTokenV1(tweetID string, token string) (string, string, string, common.Address, error) {
745+
// Query the tweet details from Twitter
746+
url := fmt.Sprintf("https://api.twitter.com/1.1/statuses/show.json?id=%s", tweetID)
747+
req, err := http.NewRequest("GET", url, nil)
748+
if err != nil {
749+
return "", "", "", common.Address{}, err
750+
}
751+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
752+
res, err := http.DefaultClient.Do(req)
753+
if err != nil {
754+
return "", "", "", common.Address{}, err
755+
}
756+
defer res.Body.Close()
750757

751-
// Ensure numeric tweetID
752-
if !regexp.MustCompile("^[0-9]+$").MatchString(sanitizedTweetID) {
753-
return "", "", "", common.Address{}, errors.New("Invalid Tweet URL")
758+
var result struct {
759+
Text string `json:"text"`
760+
User struct {
761+
ID string `json:"id_str"`
762+
Username string `json:"screen_name"`
763+
Avatar string `json:"profile_image_url"`
764+
} `json:"user"`
754765
}
766+
err = json.NewDecoder(res.Body).Decode(&result)
767+
if err != nil {
768+
return "", "", "", common.Address{}, err
769+
}
770+
address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Text))
771+
if address == (common.Address{}) {
772+
//lint:ignore ST1005 This error is to be displayed in the browser
773+
return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
774+
}
775+
return result.User.ID + "@twitter", result.User.Username, result.User.Avatar, address, nil
776+
}
755777

778+
// authTwitterWithTokenV2 tries to authenticate a faucet request using Twitter's v2
779+
// API, returning the user id, username, avatar URL and Ethereum address to fund on
780+
// success.
781+
func authTwitterWithTokenV2(tweetID string, token string) (string, string, string, common.Address, error) {
756782
// Query the tweet details from Twitter
757-
url := fmt.Sprintf("https://api.twitter.com/2/tweets/%s?expansions=author_id&user.fields=profile_image_url", sanitizedTweetID)
783+
url := fmt.Sprintf("https://api.twitter.com/2/tweets/%s?expansions=author_id&user.fields=profile_image_url", tweetID)
758784
req, err := http.NewRequest("GET", url, nil)
759785
if err != nil {
760786
return "", "", "", common.Address{}, err
@@ -769,15 +795,13 @@ func authTwitterWithToken(tweetID string, token string) (string, string, string,
769795
var result struct {
770796
Data struct {
771797
AuthorID string `json:"author_id"`
772-
ID string `json:"id"`
773798
Text string `json:"text"`
774799
} `json:"data"`
775800
Includes struct {
776801
Users []struct {
777-
ProfileImageURL string `json:"profile_image_url"`
778-
Username string `json:"username"`
779-
ID string `json:"id"`
780-
Name string `json:"name"`
802+
ID string `json:"id"`
803+
Username string `json:"username"`
804+
Avatar string `json:"profile_image_url"`
781805
} `json:"users"`
782806
} `json:"includes"`
783807
}
@@ -792,7 +816,7 @@ func authTwitterWithToken(tweetID string, token string) (string, string, string,
792816
//lint:ignore ST1005 This error is to be displayed in the browser
793817
return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
794818
}
795-
return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].ProfileImageURL, address, nil
819+
return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].Avatar, address, nil
796820
}
797821

798822
// authFacebook tries to authenticate a faucet request using Facebook posts,

‎cmd/puppeth/module_faucet.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ ENTRYPOINT [ \
4646
"--faucet.name", "{{.FaucetName}}", "--faucet.amount", "{{.FaucetAmount}}", "--faucet.minutes", "{{.FaucetMinutes}}", "--faucet.tiers", "{{.FaucetTiers}}", \
4747
"--account.json", "/account.json", "--account.pass", "/account.pass" \
4848
{{if .CaptchaToken}}, "--captcha.token", "{{.CaptchaToken}}", "--captcha.secret", "{{.CaptchaSecret}}"{{end}}{{if .NoAuth}}, "--noauth"{{end}} \
49-
{{if .TwitterToken}}, "--twitter.token", "{{.TwitterToken}}",
49+
{{if .TwitterToken}}, "--twitter.token.v1", "{{.TwitterToken}}"{{end}} \
5050
]`
5151

5252
// faucetComposefile is the docker-compose.yml file required to deploy and maintain

‎cmd/puppeth/wizard_faucet.go‎

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -102,29 +102,21 @@ func (w *wizard) deployFaucet() {
102102
infos.captchaSecret = w.readPassword()
103103
}
104104
}
105-
106-
// Accessing the twitter api requires a bearer token, request it
105+
// Accessing the Twitter API requires a bearer token, request it
107106
if infos.twitterToken != "" {
108107
fmt.Println()
109-
fmt.Println("Reuse previous twitter API Bearer token (y/n)? (default = yes)")
108+
fmt.Println("Reuse previous Twitter API token (y/n)? (default = yes)")
110109
if !w.readDefaultYesNo(true) {
111110
infos.twitterToken = ""
112111
}
113112
}
114113
if infos.twitterToken == "" {
115114
// No previous twitter token (or old one discarded)
116115
fmt.Println()
117-
fmt.Println("Enable twitter API (y/n)? (default = no)")
118-
if !w.readDefaultYesNo(false) {
119-
log.Warn("The faucet will fallback to using direct calls")
120-
} else {
121-
// Twitter api explicitly requested, read the bearer token
122-
fmt.Println()
123-
fmt.Printf("What is the twitter API Bearer token?\n")
124-
infos.twitterToken = w.readString()
125-
}
116+
fmt.Println()
117+
fmt.Printf("What is the Twitter API app Bearer token?\n")
118+
infos.twitterToken = w.readString()
126119
}
127-
128120
// Figure out where the user wants to store the persistent data
129121
fmt.Println()
130122
if infos.node.datadir == "" {

0 commit comments

Comments
 (0)