forked from stellar/go
/
main.go
436 lines (378 loc) · 12.2 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
// Skip this file in Go <1.8 because it's using http.Server.Shutdown
// +build go1.8
package main
import (
"fmt"
"net/http"
"os"
"time"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/rpcclient"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/facebookgo/inject"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/stellar/go/clients/horizon"
"github.com/stellar/go/services/bifrost/bitcoin"
"github.com/stellar/go/services/bifrost/config"
"github.com/stellar/go/services/bifrost/database"
"github.com/stellar/go/services/bifrost/ethereum"
"github.com/stellar/go/services/bifrost/server"
"github.com/stellar/go/services/bifrost/sse"
"github.com/stellar/go/services/bifrost/stellar"
"github.com/stellar/go/services/bifrost/stress"
supportConfig "github.com/stellar/go/support/config"
"github.com/stellar/go/support/errors"
"github.com/stellar/go/support/log"
)
var rootCmd = &cobra.Command{
Use: "bifrost",
Short: "Bridge server to allow participating in Stellar based ICOs using Bitcoin and Ethereum",
}
var serverCmd = &cobra.Command{
Use: "server",
Short: "Starts backend server",
Run: func(cmd *cobra.Command, args []string) {
var (
cfgPath = rootCmd.PersistentFlags().Lookup("config").Value.String()
debugMode = rootCmd.PersistentFlags().Lookup("debug").Changed
)
if debugMode {
log.SetLevel(log.DebugLevel)
log.Debug("Debug mode ON")
}
cfg := readConfig(cfgPath)
server := createServer(cfg, false)
err := server.Start()
if err != nil {
log.WithField("err", err).Error("Error starting the server")
os.Exit(-1)
}
},
}
var stressTestCmd = &cobra.Command{
Use: "stress-test",
Short: "Starts stress test",
Long: `During stress test bitcoin and ethereum transaction will be generated randomly.
This command will create 3 server.Server's listening on ports 8000-8002.`,
Run: func(cmd *cobra.Command, args []string) {
cfgPath := rootCmd.PersistentFlags().Lookup("config").Value.String()
debugMode := rootCmd.PersistentFlags().Lookup("debug").Changed
usersPerSecond, _ := cmd.PersistentFlags().GetInt("users-per-second")
if debugMode {
log.SetLevel(log.DebugLevel)
log.Debug("Debug mode ON")
}
cfg := readConfig(cfgPath)
bitcoinAccounts := make(chan string)
bitcoinClient := &stress.RandomBitcoinClient{}
bitcoinClient.Start(bitcoinAccounts)
ethereumAccounts := make(chan string)
ethereumClient := &stress.RandomEthereumClient{}
ethereumClient.Start(ethereumAccounts)
db, err := createDatabase(cfg.Database.DSN)
if err != nil {
log.WithField("err", err).Error("Error connecting to database")
os.Exit(-1)
}
err = db.ResetBlockCounters()
if err != nil {
log.WithField("err", err).Error("Error reseting counters")
os.Exit(-1)
}
// Start servers
const numServers = 3
signers := []string{
// GBQYGXC4AZDL7PPL2H274LYA6YV7OL4IRPWCYMBYCA5FAO45WMTNKGOD
"SBX76SCADD2SBIL6M2T62BR4GELMJPZV2MFHIQX24IBVOTIT6DGNAR3D",
// GAUDK66OCTKQB737ZNRD2ILB5ZGIZOKMWT3T5TDWVIN7ANVY3RD5DXF3
"SCGJ6JRFMHWYTGVBPFXCBMMBENZM433M3JNZDRSI5PZ2DXGJLYDWR4CR",
// GDFR6QNVBUK32PGTAV3HATV3GDT7LF2SGVVLD2TOS4TCAD2ANSOH2MCW
"SAZUY2XGSILNMBLQSVMDGCCTSZNOB2EXHSFFRFJJ3GKRZIW3FTIMJYV7",
}
ports := []int{8000, 8001, 8002}
for i := 0; i < numServers; i++ {
go func(i int) {
cfg.Port = ports[i]
cfg.Stellar.SignerSecretKey = signers[i]
server := createServer(cfg, true)
// Replace clients in listeners with random transactions generators
server.BitcoinListener.Client = bitcoinClient
server.EthereumListener.Client = ethereumClient
err := server.Start()
if err != nil {
log.WithField("err", err).Error("Error starting the server")
os.Exit(-1)
}
}(i)
}
// Wait for servers to start. We could wait in a more sophisticated way but this
// is just a test code.
time.Sleep(2 * time.Second)
accounts := make(chan server.GenerateAddressResponse)
users := stress.Users{
Horizon: &horizon.Client{
URL: cfg.Stellar.Horizon,
HTTP: &http.Client{
Timeout: 60 * time.Second,
},
AppName: "bifrost",
},
NetworkPassphrase: cfg.Stellar.NetworkPassphrase,
UsersPerSecond: usersPerSecond,
BifrostPorts: ports,
IssuerPublicKey: cfg.Stellar.IssuerPublicKey,
}
go users.Start(accounts)
for {
account := <-accounts
switch account.Chain {
case string(database.ChainBitcoin):
bitcoinAccounts <- account.Address
case string(database.ChainEthereum):
ethereumAccounts <- account.Address
default:
panic("Unknown chain: " + account.Chain)
}
}
},
}
var checkKeysCmd = &cobra.Command{
Use: "check-keys",
Short: "Displays a few public keys derived using master public keys",
Run: func(cmd *cobra.Command, args []string) {
cfgPath := rootCmd.PersistentFlags().Lookup("config").Value.String()
start, _ := cmd.PersistentFlags().GetUint32("start")
count, _ := cmd.PersistentFlags().GetUint32("count")
cfg := readConfig(cfgPath)
fmt.Println("MAKE SURE YOU HAVE PRIVATE KEYS TO CORRESPONDING ADDRESSES:")
fmt.Println("Bitcoin MainNet:")
if cfg.Bitcoin != nil && cfg.Bitcoin.MasterPublicKey != "" {
bitcoinAddressGenerator, err := bitcoin.NewAddressGenerator(cfg.Bitcoin.MasterPublicKey, &chaincfg.MainNetParams)
if err != nil {
log.Error(err)
os.Exit(-1)
}
for i := uint32(start); i < start+count; i++ {
address, err := bitcoinAddressGenerator.Generate(i)
if err != nil {
fmt.Println("Error generating address", i)
continue
}
fmt.Printf("%d %s\n", i, address)
}
} else {
fmt.Println("No master key set...")
}
fmt.Println("Ethereum:")
if cfg.Ethereum != nil && cfg.Ethereum.MasterPublicKey != "" {
ethereumAddressGenerator, err := ethereum.NewAddressGenerator(cfg.Ethereum.MasterPublicKey)
if err != nil {
log.Error(err)
os.Exit(-1)
}
for i := uint32(start); i < start+count; i++ {
address, err := ethereumAddressGenerator.Generate(i)
if err != nil {
fmt.Println("Error generating address", i)
continue
}
fmt.Printf("%d %s\n", i, address)
}
} else {
fmt.Println("No master key set...")
}
},
}
var versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number",
Run: func(cmd *cobra.Command, args []string) {
fmt.Println("0.0.2")
},
}
func init() {
// TODO I think these should be default in stellar/go:
log.SetLevel(log.InfoLevel)
log.DefaultLogger.Logger.Formatter.(*logrus.TextFormatter).FullTimestamp = true
rootCmd.PersistentFlags().Bool("debug", false, "debug mode")
rootCmd.PersistentFlags().StringP("config", "c", "bifrost.cfg", "config file path")
rootCmd.AddCommand(checkKeysCmd)
rootCmd.AddCommand(serverCmd)
rootCmd.AddCommand(stressTestCmd)
rootCmd.AddCommand(versionCmd)
stressTestCmd.PersistentFlags().IntP("users-per-second", "u", 2, "users per second")
checkKeysCmd.PersistentFlags().Uint32P("start", "s", 0, "starting address index")
checkKeysCmd.PersistentFlags().Uint32P("count", "l", 10, "how many addresses generate")
}
func main() {
rootCmd.Execute()
}
func readConfig(cfgPath string) config.Config {
var cfg config.Config
err := supportConfig.Read(cfgPath, &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)
}
if cfg.AccessControlAllowOriginHeader == "" {
cfg.AccessControlAllowOriginHeader = "*"
}
return cfg
}
// createDatabase opens a DB connection and imports schema if DB is empty.
func createDatabase(dsn string) (*database.PostgresDatabase, error) {
db := &database.PostgresDatabase{}
err := db.Open(dsn)
if err != nil {
return nil, err
}
currentSchemaVersion, err := db.GetSchemaVersion()
if err != nil {
return nil, err
}
if currentSchemaVersion == 0 {
// DB clean, import
err := db.Import()
if err != nil {
return nil, errors.Wrap(err, "Error importing DB schema")
}
} else if currentSchemaVersion != database.SchemaVersion {
// Schema version invalid
return nil, errors.New("Schema version is invalid. Please create an empty DB and start Bifrost again.")
}
return db, nil
}
func createServer(cfg config.Config, stressTest bool) *server.Server {
var g inject.Graph
db, err := createDatabase(cfg.Database.DSN)
if err != nil {
log.WithField("err", err).Error("Error connecting to database")
os.Exit(-1)
}
server := &server.Server{
SignerPublicKey: cfg.SignerPublicKey(),
}
bitcoinClient := &rpcclient.Client{}
bitcoinListener := &bitcoin.Listener{}
bitcoinAddressGenerator := &bitcoin.AddressGenerator{}
ethereumClient := ðclient.Client{}
ethereumListener := ðereum.Listener{}
ethereumAddressGenerator := ðereum.AddressGenerator{}
if !stressTest {
// Configure real clients
if cfg.Bitcoin != nil {
connConfig := &rpcclient.ConnConfig{
Host: cfg.Bitcoin.RpcServer,
User: cfg.Bitcoin.RpcUser,
Pass: cfg.Bitcoin.RpcPass,
HTTPPostMode: true,
DisableTLS: true,
}
bitcoinClient, err = rpcclient.New(connConfig, nil)
if err != nil {
log.WithField("err", err).Error("Error connecting to bitcoin-core")
os.Exit(-1)
}
bitcoinListener.Enabled = true
bitcoinListener.Testnet = cfg.Bitcoin.Testnet
server.MinimumValueBtc = cfg.Bitcoin.MinimumValueBtc
var chainParams *chaincfg.Params
if cfg.Bitcoin.Testnet {
chainParams = &chaincfg.TestNet3Params
} else {
chainParams = &chaincfg.MainNetParams
}
bitcoinAddressGenerator, err = bitcoin.NewAddressGenerator(cfg.Bitcoin.MasterPublicKey, chainParams)
if err != nil {
log.Error(err)
os.Exit(-1)
}
}
if cfg.Ethereum != nil {
ethereumClient, err = ethclient.Dial("http://" + cfg.Ethereum.RpcServer)
if err != nil {
log.WithField("err", err).Error("Error connecting to geth")
os.Exit(-1)
}
ethereumListener.Enabled = true
ethereumListener.NetworkID = cfg.Ethereum.NetworkID
server.MinimumValueEth = cfg.Ethereum.MinimumValueEth
ethereumAddressGenerator, err = ethereum.NewAddressGenerator(cfg.Ethereum.MasterPublicKey)
if err != nil {
log.Error(err)
os.Exit(-1)
}
}
} else {
bitcoinListener.Enabled = true
bitcoinListener.Testnet = true
bitcoinAddressGenerator, err = bitcoin.NewAddressGenerator(cfg.Bitcoin.MasterPublicKey, &chaincfg.TestNet3Params)
if err != nil {
log.Error(err)
os.Exit(-1)
}
ethereumListener.Enabled = true
ethereumListener.NetworkID = "3"
ethereumAddressGenerator, err = ethereum.NewAddressGenerator(cfg.Ethereum.MasterPublicKey)
if err != nil {
log.Error(err)
os.Exit(-1)
}
}
stellarAccountConfigurator := &stellar.AccountConfigurator{
NetworkPassphrase: cfg.Stellar.NetworkPassphrase,
IssuerPublicKey: cfg.Stellar.IssuerPublicKey,
DistributionPublicKey: cfg.Stellar.DistributionPublicKey,
SignerSecretKey: cfg.Stellar.SignerSecretKey,
NeedsAuthorize: cfg.Stellar.NeedsAuthorize,
TokenAssetCode: cfg.Stellar.TokenAssetCode,
StartingBalance: cfg.Stellar.StartingBalance,
LockUnixTimestamp: cfg.Stellar.LockUnixTimestamp,
}
if cfg.Stellar.StartingBalance == "" {
stellarAccountConfigurator.StartingBalance = "2.1"
}
if cfg.Bitcoin != nil {
stellarAccountConfigurator.TokenPriceBTC = cfg.Bitcoin.TokenPrice
}
if cfg.Ethereum != nil {
stellarAccountConfigurator.TokenPriceETH = cfg.Ethereum.TokenPrice
}
horizonClient := &horizon.Client{
URL: cfg.Stellar.Horizon,
HTTP: &http.Client{
Timeout: 20 * time.Second,
},
AppName: "bifrost",
}
sseServer := &sse.Server{}
err = g.Provide(
&inject.Object{Value: bitcoinAddressGenerator},
&inject.Object{Value: bitcoinClient},
&inject.Object{Value: bitcoinListener},
&inject.Object{Value: &cfg},
&inject.Object{Value: db},
&inject.Object{Value: ethereumAddressGenerator},
&inject.Object{Value: ethereumClient},
&inject.Object{Value: ethereumListener},
&inject.Object{Value: horizonClient},
&inject.Object{Value: server},
&inject.Object{Value: sseServer},
&inject.Object{Value: stellarAccountConfigurator},
)
if err != nil {
log.WithField("err", err).Error("Error providing objects to injector")
os.Exit(-1)
}
if err := g.Populate(); err != nil {
log.WithField("err", err).Error("Error injecting objects")
os.Exit(-1)
}
return server
}