forked from stellar/go
/
main.go
284 lines (238 loc) · 6.93 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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package main
import (
"fmt"
log "github.com/sirupsen/logrus"
"net/http"
"os"
"runtime"
"time"
"github.com/facebookgo/inject"
"github.com/spf13/cobra"
"github.com/stellar/go/clients/federation"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/clients/stellartoml"
"github.com/stellar/go/services/bridge/internal/config"
"github.com/stellar/go/services/bridge/internal/db"
"github.com/stellar/go/services/bridge/internal/handlers"
"github.com/stellar/go/services/bridge/internal/listener"
"github.com/stellar/go/services/bridge/internal/submitter"
supportConfig "github.com/stellar/go/support/config"
"github.com/stellar/go/support/db/schema"
"github.com/stellar/go/support/errors"
supportHttp "github.com/stellar/go/support/http"
)
var app *App
var rootCmd *cobra.Command
var migrateFlag bool
var configFile string
var versionFlag bool
var version = "N/A"
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
rootCmd.Execute()
}
func init() {
rootCmd = &cobra.Command{
Use: "bridge",
Short: "stellar bridge server",
Long: `stellar bridge server`,
Run: run,
}
rootCmd.Flags().BoolVarP(&migrateFlag, "migrate-db", "", false, "migrate DB to the newest schema version")
rootCmd.Flags().StringVarP(&configFile, "config", "c", "bridge.cfg", "path to config file")
rootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "displays bridge server version")
}
func run(cmd *cobra.Command, args []string) {
var cfg config.Config
err := supportConfig.Read(configFile, &cfg)
if err != nil {
switch cause := errors.Cause(err).(type) {
case *supportConfig.InvalidConfigError:
log.Error("config file: ", cause)
default:
log.Error(err)
}
os.Exit(-1)
}
err = cfg.Validate()
if err != nil {
log.Fatal(err.Error())
return
}
if cfg.LogFormat == "json" {
log.SetFormatter(&log.JSONFormatter{})
}
app, err = NewApp(cfg, migrateFlag, versionFlag, version)
if err != nil {
log.Fatal(err.Error())
return
}
app.Serve()
}
// App is the application object
type App struct {
config config.Config
requestHandler handlers.RequestHandler
}
// NewApp constructs an new App instance from the provided config.
func NewApp(config config.Config, migrateFlag bool, versionFlag bool, version string) (app *App, err error) {
var g inject.Graph
var database db.PostgresDatabase
if config.Database != nil {
err = database.Open(config.Database.URL)
if err != nil {
err = fmt.Errorf("Cannot connect to a DB: %s", err)
return
}
}
if migrateFlag {
var migrationsApplied int
migrationsApplied, err = schema.Migrate(
database.GetDB(),
db.Migrations,
schema.MigrateUp,
0,
)
if err != nil {
return
}
log.Info("Applied migrations: ", migrationsApplied)
os.Exit(0)
return
}
if versionFlag {
fmt.Printf("Bridge Server Version: %s \n", version)
os.Exit(0)
return
}
if len(config.APIKey) > 0 && len(config.APIKey) < 15 {
err = errors.New("api-key have to be at least 15 chars long")
return
}
requestHandler := handlers.RequestHandler{}
httpClientWithTimeout := http.Client{
Timeout: 60 * time.Second,
}
h := horizon.Client{
URL: config.Horizon,
HTTP: &httpClientWithTimeout,
AppName: "bridge-server",
}
log.Print("Creating and initializing TransactionSubmitter")
ts := submitter.NewTransactionSubmitter(&h, &database, config.NetworkPassphrase, time.Now)
if err != nil {
return
}
if config.Accounts.AuthorizingSeed == "" {
log.Warning("No accounts.authorizing_seed param. Skipping...")
} else {
log.Print("Initializing Authorizing account")
err = ts.InitAccount(config.Accounts.AuthorizingSeed)
if err != nil {
return
}
}
if config.Accounts.BaseSeed == "" {
log.Warning("No accounts.base_seed param. Skipping...")
} else {
log.Print("Initializing Base account")
err = ts.InitAccount(config.Accounts.BaseSeed)
if err != nil {
return
}
}
log.Print("TransactionSubmitter created")
log.Print("Creating and starting PaymentListener")
var paymentListener listener.PaymentListener
if config.Accounts.ReceivingAccountID == "" {
log.Warning("No accounts.receiving_account_id param. Skipping...")
} else if config.Callbacks.Receive == "" {
log.Warning("No callbacks.receive param. Skipping...")
} else {
paymentListener, err = listener.NewPaymentListener(&config, &database, &h, time.Now)
if err != nil {
return
}
err = paymentListener.Listen()
if err != nil {
return
}
log.Print("PaymentListener created")
}
stellartomlClient := stellartoml.Client{
HTTP: &httpClientWithTimeout,
}
federationClient := federation.Client{
HTTP: &httpClientWithTimeout,
StellarTOML: &stellartomlClient,
}
err = g.Provide(
&inject.Object{Value: &requestHandler},
&inject.Object{Value: &config},
&inject.Object{Value: &stellartomlClient},
&inject.Object{Value: &federationClient},
&inject.Object{Value: &h},
&inject.Object{Value: &database},
&inject.Object{Value: &ts},
&inject.Object{Value: &paymentListener},
&inject.Object{Value: &httpClientWithTimeout},
)
if err != nil {
log.Fatal("Injector: ", err)
}
if err := g.Populate(); err != nil {
log.Fatal("Injector: ", err)
}
app = &App{
config: config,
requestHandler: requestHandler,
}
return
}
// Serve starts the server
func (a *App) Serve() {
mux := supportHttp.NewAPIMux(false)
// Middlewares
headers := make(http.Header)
headers.Set("Content-Type", "application/json")
mux.Use(supportHttp.StripTrailingSlashMiddleware("/admin"))
mux.Use(supportHttp.HeadersMiddleware(headers, "/admin/"))
if a.config.APIKey != "" {
mux.Use(apiKeyMiddleware(a.config.APIKey))
}
if a.config.Accounts.AuthorizingSeed != "" {
mux.Post("/authorize", a.requestHandler.Authorize)
} else {
log.Warning("accounts.authorizing_seed not provided. /authorize endpoint will not be available.")
}
mux.Post("/create-keypair", a.requestHandler.CreateKeypair)
mux.Post("/builder", a.requestHandler.Builder)
mux.Post("/payment", a.requestHandler.Payment)
mux.Get("/payment", a.requestHandler.Payment)
mux.Post("/reprocess", a.requestHandler.Reprocess)
mux.Get("/admin/received-payments", a.requestHandler.AdminReceivedPayments)
mux.Get("/admin/received-payments/{id}", a.requestHandler.AdminReceivedPayment)
mux.Get("/admin/sent-transactions", a.requestHandler.AdminSentTransactions)
supportHttp.Run(supportHttp.Config{
ListenAddr: fmt.Sprintf(":%d", *a.config.Port),
Handler: mux,
OnStarting: func() {
log.Infof("starting bridge server")
log.Infof("listening on %d", *a.config.Port)
},
})
}
// apiKeyMiddleware checks for apiKey in a request and writes http.StatusForbidden if it's incorrect.
func apiKeyMiddleware(apiKey string) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
k := r.PostFormValue("apiKey")
if k != apiKey {
http.Error(w, "Forbidden", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}