This repository has been archived by the owner on Sep 6, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
184 lines (164 loc) · 4.77 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
package main
import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"os"
"os/user"
"path"
"strings"
"time"
"github.com/drand/drand/client"
"github.com/drand/drand/cmd/client/lib"
"github.com/drand/drand/log"
cli "github.com/urfave/cli/v2"
"github.com/kurrik/oauth1a"
"github.com/kurrik/twittergo"
)
// Automatically set through -ldflags
// Example: go install -ldflags "-X main.version=`git describe --tags`
// -X main.buildDate=`date -u +%d/%m/%Y@%H:%M:%S` -X main.gitCommit=`git rev-parse HEAD`"
var (
version = "master"
gitCommit = "none"
buildDate = "unknown"
)
var (
credsPathFlag = &cli.StringFlag{
Name: "creds",
Usage: "Location of credentials file, newline separated API key, " +
"API secret, access token, access token secret " +
"(default: ~/.twitter/CREDENTIALS)",
}
)
func main() {
app := &cli.App{
Name: "drand-relay-twitter",
Version: version,
Usage: "Twitter relay for randomness beacon",
Commands: []*cli.Command{runCmd},
}
cli.VersionPrinter = func(c *cli.Context) {
fmt.Printf("drand Twitter relay %v (date %v, commit %v)\n", version, buildDate, gitCommit)
}
err := app.Run(os.Args)
if err != nil {
fmt.Printf("error: %+v\n", err)
os.Exit(1)
}
}
var runCmd = &cli.Command{
Name: "run",
Usage: "start a drand Twitter relay process",
Flags: append(lib.ClientFlags, credsPathFlag),
Action: func(cctx *cli.Context) error {
credsPath := cctx.String(credsPathFlag.Name)
if credsPath == "" {
usr, err := user.Current()
if err != nil {
return fmt.Errorf("getting current user: %w", err)
}
credsPath = path.Join(usr.HomeDir, ".twitter", "CREDENTIALS")
}
config, user, err := loadCredentials(credsPath)
if err != nil {
return fmt.Errorf("loading credentials: %w", err)
}
twc := twittergo.NewClient(config, user)
c, err := lib.Create(cctx, false)
if err != nil {
return fmt.Errorf("creating client: %w", err)
}
watch(context.Background(), c, twc)
return nil
},
}
func loadCredentials(p string) (*oauth1a.ClientConfig, *oauth1a.UserConfig, error) {
creds, err := ioutil.ReadFile(p)
if err == nil {
lines := strings.Split(string(creds), "\n")
c := &oauth1a.ClientConfig{ConsumerKey: lines[0], ConsumerSecret: lines[1]}
u := oauth1a.NewAuthorizedConfig(lines[2], lines[3])
return c, u, nil
}
apiKey := os.Getenv("TWITTER_API_KEY")
apiSecret := os.Getenv("TWITTER_API_SECRET")
accessToken := os.Getenv("TWITTER_ACCESS_TOKEN")
accessTokenSecret := os.Getenv("TWITTER_ACCESS_TOKEN_SECRET")
if apiKey != "" && apiSecret != "" && accessToken != "" && accessTokenSecret != "" {
c := &oauth1a.ClientConfig{ConsumerKey: apiKey, ConsumerSecret: apiSecret}
u := oauth1a.NewAuthorizedConfig(accessToken, accessTokenSecret)
return c, u, nil
}
return nil, nil, err
}
func watch(ctx context.Context, c client.Watcher, twc *twittergo.Client) {
for {
ch := c.Watch(ctx)
INNER:
for {
select {
case res, ok := <-ch:
if !ok {
log.DefaultLogger().Warn("relay_twitter", "watch channel closed")
t := time.NewTimer(time.Second)
select {
case <-t.C:
break INNER
case <-ctx.Done():
return
}
}
log.DefaultLogger().Info("relay_twitter", "got randomness", "round", res.Round())
go func(res client.Result) {
loc, err := tweetRandomness(twc, res)
if err != nil {
log.DefaultLogger().Error("relay_twitter", "failed to tweet randomness", "err", err)
return
}
log.DefaultLogger().Info("relay_twitter", "tweeted randomness", "round", res.Round(), "location", loc)
}(res)
case <-ctx.Done():
return
}
}
}
}
type beaconTweet struct {
Round int `json:"round,omitempty"`
Signature string `json:"signature,omitempty"`
}
func tweetRandomness(twc *twittergo.Client, res client.Result) (string, error) {
data := url.Values{}
json, err := json.MarshalIndent(beaconTweet{
Round: int(res.Round()),
Signature: hex.EncodeToString(res.Signature()),
}, "", " ")
if err != nil {
return "", fmt.Errorf("marshaling json: %w", err)
}
data.Set("status", string(json))
body := strings.NewReader(data.Encode())
req, err := http.NewRequest("POST", "/1.1/statuses/update.json", body)
if err != nil {
return "", fmt.Errorf("parsing request: %w", err)
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
resp, err := twc.SendRequest(req)
if err != nil {
return "", fmt.Errorf("sending request: %w", err)
}
tweet := &twittergo.Tweet{}
err = resp.Parse(tweet)
if err != nil {
if rle, ok := err.(twittergo.RateLimitError); ok {
return "", fmt.Errorf("rate limited, reset at %v: %w", rle.Reset, err)
}
return "", fmt.Errorf("parsing response: %w", err)
}
return fmt.Sprintf("https://twitter.com/%s/status/%s", tweet.User().ScreenName(), tweet.IdStr()), nil
}