Skip to content

Commit b47f4ca

Browse files
authored
cmd/faucet: use Twitter API instead of scraping webpage (#21850)
This PR adds support for using Twitter API to query the tweet and author details. There are two reasons behind this change: - Twitter will be deprecating the legacy website on 15th December. The current method is expected to stop working then. - More importantly, the current system uses Twitter handle for spam protection but the Twitter handle can be changed via automated calls. This allows bots to use the same tweet to withdraw funds infinite times as long as they keep changing their handle between every request. The Rinkeby as well as the Goerli faucet are being actively drained via this method. This PR changes the spam protection to be based on Twitter IDs instead of usernames. A user can not change their Twitter ID.
1 parent 62dc59c commit b47f4ca

3 files changed

Lines changed: 110 additions & 13 deletions

File tree

‎cmd/faucet/faucet.go‎

Lines changed: 80 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,8 @@ var (
8383

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")
86+
87+
twitterBearerToken = flag.String("twitter.token", "", "Twitter bearer token to authenticate with the twitter API")
8688
)
8789

8890
var (
@@ -443,6 +445,7 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
443445
}
444446
// Retrieve the Ethereum address to fund, the requesting user and a profile picture
445447
var (
448+
id string
446449
username string
447450
avatar string
448451
address common.Address
@@ -462,11 +465,13 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
462465
}
463466
continue
464467
case strings.HasPrefix(msg.URL, "https://twitter.com/"):
465-
username, avatar, address, err = authTwitter(msg.URL)
468+
id, username, avatar, address, err = authTwitter(msg.URL, *twitterBearerToken)
466469
case strings.HasPrefix(msg.URL, "https://www.facebook.com/"):
467470
username, avatar, address, err = authFacebook(msg.URL)
471+
id = username
468472
case *noauthFlag:
469473
username, avatar, address, err = authNoAuth(msg.URL)
474+
id = username
470475
default:
471476
//lint:ignore ST1005 This error is to be displayed in the browser
472477
err = errors.New("Something funky happened, please open an issue at https://github.com/ethereum/go-ethereum/issues")
@@ -486,7 +491,7 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
486491
fund bool
487492
timeout time.Time
488493
)
489-
if timeout = f.timeouts[username]; time.Now().After(timeout) {
494+
if timeout = f.timeouts[id]; time.Now().After(timeout) {
490495
// User wasn't funded recently, create the funding transaction
491496
amount := new(big.Int).Mul(big.NewInt(int64(*payoutFlag)), ether)
492497
amount = new(big.Int).Mul(amount, new(big.Int).Exp(big.NewInt(5), big.NewInt(int64(msg.Tier)), nil))
@@ -520,7 +525,7 @@ func (f *faucet) apiHandler(w http.ResponseWriter, r *http.Request) {
520525
timeout := time.Duration(*minutesFlag*int(math.Pow(3, float64(msg.Tier)))) * time.Minute
521526
grace := timeout / 288 // 24h timeout => 5m grace
522527

523-
f.timeouts[username] = time.Now().Add(timeout - grace)
528+
f.timeouts[id] = time.Now().Add(timeout - grace)
524529
fund = true
525530
}
526531
f.lock.Unlock()
@@ -684,48 +689,110 @@ func sendSuccess(conn *websocket.Conn, msg string) error {
684689
}
685690

686691
// authTwitter tries to authenticate a faucet request using Twitter posts, returning
687-
// the username, avatar URL and Ethereum address to fund on success.
688-
func authTwitter(url string) (string, string, common.Address, error) {
692+
// 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) {
689694
// Ensure the user specified a meaningful URL, no fancy nonsense
690695
parts := strings.Split(url, "/")
691696
if len(parts) < 4 || parts[len(parts)-2] != "status" {
692697
//lint:ignore ST1005 This error is to be displayed in the browser
693-
return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
698+
return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
699+
}
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+
705+
// If twitter bearer token is provided, use the twitter api
706+
if token != "" {
707+
return authTwitterWithToken(parts[len(parts)-1], token)
694708
}
695-
// Twitter's API isn't really friendly with direct links. Still, we don't
696-
// want to do ask read permissions from users, so just load the public posts
709+
710+
// Twiter API token isn't provided so we just load the public posts
697711
// and scrape it for the Ethereum address and profile URL. We need to load
698712
// the mobile page though since the main page loads tweet contents via JS.
699713
url = strings.Replace(url, "https://twitter.com/", "https://mobile.twitter.com/", 1)
700714

701715
res, err := http.Get(url)
702716
if err != nil {
703-
return "", "", common.Address{}, err
717+
return "", "", "", common.Address{}, err
704718
}
705719
defer res.Body.Close()
706720

707721
// Resolve the username from the final redirect, no intermediate junk
708722
parts = strings.Split(res.Request.URL.String(), "/")
709723
if len(parts) < 4 || parts[len(parts)-2] != "status" {
710724
//lint:ignore ST1005 This error is to be displayed in the browser
711-
return "", "", common.Address{}, errors.New("Invalid Twitter status URL")
725+
return "", "", "", common.Address{}, errors.New("Invalid Twitter status URL")
712726
}
713727
username := parts[len(parts)-3]
714728

715729
body, err := ioutil.ReadAll(res.Body)
716730
if err != nil {
717-
return "", "", common.Address{}, err
731+
return "", "", "", common.Address{}, err
718732
}
719733
address := common.HexToAddress(string(regexp.MustCompile("0x[0-9a-fA-F]{40}").Find(body)))
720734
if address == (common.Address{}) {
721735
//lint:ignore ST1005 This error is to be displayed in the browser
722-
return "", "", common.Address{}, errors.New("No Ethereum address found to fund")
736+
return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
723737
}
724738
var avatar string
725739
if parts = regexp.MustCompile("src=\"([^\"]+twimg.com/profile_images[^\"]+)\"").FindStringSubmatch(string(body)); len(parts) == 2 {
726740
avatar = parts[1]
727741
}
728-
return username + "@twitter", avatar, address, nil
742+
return username + "@twitter", username, avatar, address, nil
743+
}
744+
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]
750+
751+
// Ensure numeric tweetID
752+
if !regexp.MustCompile("^[0-9]+$").MatchString(sanitizedTweetID) {
753+
return "", "", "", common.Address{}, errors.New("Invalid Tweet URL")
754+
}
755+
756+
// 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)
758+
req, err := http.NewRequest("GET", url, nil)
759+
if err != nil {
760+
return "", "", "", common.Address{}, err
761+
}
762+
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token))
763+
res, err := http.DefaultClient.Do(req)
764+
if err != nil {
765+
return "", "", "", common.Address{}, err
766+
}
767+
defer res.Body.Close()
768+
769+
var result struct {
770+
Data struct {
771+
AuthorID string `json:"author_id"`
772+
ID string `json:"id"`
773+
Text string `json:"text"`
774+
} `json:"data"`
775+
Includes struct {
776+
Users []struct {
777+
ProfileImageURL string `json:"profile_image_url"`
778+
Username string `json:"username"`
779+
ID string `json:"id"`
780+
Name string `json:"name"`
781+
} `json:"users"`
782+
} `json:"includes"`
783+
}
784+
785+
err = json.NewDecoder(res.Body).Decode(&result)
786+
if err != nil {
787+
return "", "", "", common.Address{}, err
788+
}
789+
790+
address := common.HexToAddress(regexp.MustCompile("0x[0-9a-fA-F]{40}").FindString(result.Data.Text))
791+
if address == (common.Address{}) {
792+
//lint:ignore ST1005 This error is to be displayed in the browser
793+
return "", "", "", common.Address{}, errors.New("No Ethereum address found to fund")
794+
}
795+
return result.Data.AuthorID + "@twitter", result.Includes.Users[0].Username, result.Includes.Users[0].ProfileImageURL, address, nil
729796
}
730797

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

‎cmd/puppeth/module_faucet.go‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +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}}",
4950
]`
5051

5152
// faucetComposefile is the docker-compose.yml file required to deploy and maintain
@@ -71,6 +72,7 @@ services:
7172
- FAUCET_TIERS={{.FaucetTiers}}
7273
- CAPTCHA_TOKEN={{.CaptchaToken}}
7374
- CAPTCHA_SECRET={{.CaptchaSecret}}
75+
- TWITTER_TOKEN={{.TwitterToken}}
7476
- NO_AUTH={{.NoAuth}}{{if .VHost}}
7577
- VIRTUAL_HOST={{.VHost}}
7678
- VIRTUAL_PORT=8080{{end}}
@@ -103,6 +105,7 @@ func deployFaucet(client *sshClient, network string, bootnodes []string, config
103105
"FaucetMinutes": config.minutes,
104106
"FaucetTiers": config.tiers,
105107
"NoAuth": config.noauth,
108+
"TwitterToken": config.twitterToken,
106109
})
107110
files[filepath.Join(workdir, "Dockerfile")] = dockerfile.Bytes()
108111

@@ -120,6 +123,7 @@ func deployFaucet(client *sshClient, network string, bootnodes []string, config
120123
"FaucetMinutes": config.minutes,
121124
"FaucetTiers": config.tiers,
122125
"NoAuth": config.noauth,
126+
"TwitterToken": config.twitterToken,
123127
})
124128
files[filepath.Join(workdir, "docker-compose.yaml")] = composefile.Bytes()
125129

@@ -152,6 +156,7 @@ type faucetInfos struct {
152156
noauth bool
153157
captchaToken string
154158
captchaSecret string
159+
twitterToken string
155160
}
156161

157162
// Report converts the typed struct into a plain string->string map, containing
@@ -165,6 +170,7 @@ func (info *faucetInfos) Report() map[string]string {
165170
"Funding cooldown (base tier)": fmt.Sprintf("%d mins", info.minutes),
166171
"Funding tiers": strconv.Itoa(info.tiers),
167172
"Captha protection": fmt.Sprintf("%v", info.captchaToken != ""),
173+
"Using Twitter API": fmt.Sprintf("%v", info.twitterToken != ""),
168174
"Ethstats username": info.node.ethstats,
169175
}
170176
if info.noauth {
@@ -243,5 +249,6 @@ func checkFaucet(client *sshClient, network string) (*faucetInfos, error) {
243249
captchaToken: infos.envvars["CAPTCHA_TOKEN"],
244250
captchaSecret: infos.envvars["CAPTCHA_SECRET"],
245251
noauth: infos.envvars["NO_AUTH"] == "true",
252+
twitterToken: infos.envvars["TWITTER_TOKEN"],
246253
}, nil
247254
}

‎cmd/puppeth/wizard_faucet.go‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,29 @@ func (w *wizard) deployFaucet() {
102102
infos.captchaSecret = w.readPassword()
103103
}
104104
}
105+
106+
// Accessing the twitter api requires a bearer token, request it
107+
if infos.twitterToken != "" {
108+
fmt.Println()
109+
fmt.Println("Reuse previous twitter API Bearer token (y/n)? (default = yes)")
110+
if !w.readDefaultYesNo(true) {
111+
infos.twitterToken = ""
112+
}
113+
}
114+
if infos.twitterToken == "" {
115+
// No previous twitter token (or old one discarded)
116+
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+
}
126+
}
127+
105128
// Figure out where the user wants to store the persistent data
106129
fmt.Println()
107130
if infos.node.datadir == "" {

0 commit comments

Comments
 (0)