-
Notifications
You must be signed in to change notification settings - Fork 15
/
main.go
421 lines (395 loc) · 11.8 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
/*
* Copyright (C) 2018 The ontology Authors
* This file is part of The ontology library.
*
* The ontology is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* The ontology is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with The ontology. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"runtime"
"time"
"github.com/ontio/ontology/common/constants"
"github.com/ethereum/go-ethereum/common/fdlimit"
eventbus "github.com/ontio/ontology-eventbus/log"
"github.com/ontio/ontology-rosetta/log"
"github.com/ontio/ontology-rosetta/process"
"github.com/ontio/ontology-rosetta/services"
"github.com/ontio/ontology-rosetta/version"
"github.com/ontio/ontology/cmd"
"github.com/ontio/ontology/cmd/utils"
"github.com/ontio/ontology/common"
"github.com/ontio/ontology/common/config"
nodelog "github.com/ontio/ontology/common/log"
"github.com/ontio/ontology/core/genesis"
"github.com/ontio/ontology/core/ledger"
"github.com/ontio/ontology/events"
bactor "github.com/ontio/ontology/http/base/actor"
"github.com/ontio/ontology/p2pserver"
"github.com/ontio/ontology/txnpool"
"github.com/ontio/ontology/txnpool/proc"
"github.com/urfave/cli"
)
var disableLogFile bool
var (
offlineFlag = cli.BoolFlag{
Name: "offline",
Usage: "Run the Rosetta server in offline mode",
}
serverConfigFlag = cli.StringFlag{
Name: "server-config",
Value: "./server-config.json",
Usage: "Path to the config `<file>` for this Rosetta server",
}
validateStoreFlag = cli.BoolFlag{
Name: "validate-store",
Usage: "Validate the indexed data in the Rosetta server's internal data store",
}
)
type token struct {
Contract string `json:"contract"`
Decimals int32 `json:"decimals"`
Symbol string `json:"symbol"`
Wasm bool `json:"wasm"`
}
type serverConfig struct {
BlockWait uint32 `json:"block_wait_seconds"`
OEP4Tokens []*token `json:"oep4_tokens"`
Port uint32 `json:"port"`
tokens []*services.OEP4Token
waitTime time.Duration
}
func setupApp() *cli.App {
app := cli.NewApp()
app.Action = run
app.Copyright = "Copyright (c) The Ontology Authors"
app.Usage = "Ontology Rosetta Server"
app.Version = fmt.Sprintf(
"Ontology Rosetta Server: %s, Ontology Node: %s",
version.Rosetta, version.Node,
)
app.Flags = []cli.Flag{
// rosetta server settings
serverConfigFlag,
offlineFlag,
validateStoreFlag,
// base settings
utils.ConfigFlag,
utils.DataDirFlag,
utils.DisableLogFileFlag,
utils.LogDirFlag,
utils.LogLevelFlag,
utils.WasmVerifyMethodFlag,
// txpool settings
utils.DisableBroadcastNetTxFlag,
utils.DisableSyncVerifyTxFlag,
utils.GasLimitFlag,
utils.GasPriceFlag,
utils.TxpoolPreExecDisableFlag,
// p2p settings
utils.MaxConnInBoundFlag,
utils.MaxConnInBoundForSingleIPFlag,
utils.MaxConnOutBoundFlag,
utils.NetworkIdFlag,
utils.NodePortFlag,
utils.ReservedPeersFileFlag,
utils.ReservedPeersOnlyFlag,
}
app.Before = func(context *cli.Context) error {
runtime.GOMAXPROCS(runtime.NumCPU())
return nil
}
// NOTE(tav): Unfortunately, cmd.flagGroup isn't exported, so we resort to
// overriding the group for the import command as they are unused within
// this application.
idx := len(cmd.AppHelpFlagGroups) - 2
group := cmd.AppHelpFlagGroups[idx]
group.Name = "ROSETTA SERVER"
group.Flags = []cli.Flag{
serverConfigFlag,
offlineFlag,
validateStoreFlag,
}
cmd.AppHelpFlagGroups[idx] = group
return app
}
func cliBool(ctx *cli.Context, flag cli.Flag) bool {
return ctx.GlobalBool(utils.GetFlagName(flag))
}
func initLedger(ctx *cli.Context, cfg *config.OntologyConfig) *ledger.Ledger {
events.Init()
constants.BLOCKHEIGHT_ADD_DECIMALS_MAINNET = 0
bookKeepers, err := config.DefConfig.GetBookkeepers()
if err != nil {
log.Errorf("GetBookkeepers error: %s", err)
}
genesisConfig := config.DefConfig.Genesis
genesisBlock, err := genesis.BuildGenesisBlock(bookKeepers, genesisConfig)
if err != nil {
log.Errorf("genesisBlock error %s", err)
}
dbDir := utils.GetStoreDirPath(config.DefConfig.Common.DataDir, config.DefConfig.P2PNode.NetworkName)
ldg, err := ledger.InitLedger(dbDir, config.GetStateHashCheckHeight(cfg.P2PNode.NetworkId), bookKeepers, genesisBlock)
if err != nil {
log.Fatalf("Failed to open ledger: %s", err)
}
process.SetExitHandler(func() {
log.Info("Closing ledger")
if err := ldg.Close(); err != nil {
log.Errorf("Failed to close ledger: %s", err)
}
})
log.Info("Ledger init success")
ledger.DefLedger = ldg
return ldg
}
func initLog(ctx *cli.Context) {
disableLogFile = cliBool(ctx, utils.DisableLogFileFlag)
level := ctx.GlobalInt(utils.GetFlagName(utils.LogLevelFlag))
log.InitLog(level, os.Stdout)
if disableLogFile {
eventbus.InitLogWriter(os.Stdout)
nodelog.InitLog(level, os.Stdout)
} else {
dir := ctx.GlobalString(utils.GetFlagName(utils.LogDirFlag))
dir = filepath.Join(dir, "") + string(os.PathSeparator)
eventbus.InitLog(dir)
// NOTE(tav): We override the global PATH variable as it is used by
// nodelog.CheckRotateLogFile when rotating log files.
nodelog.PATH = dir
nodelog.InitLog(level, dir, log.Stdout)
}
}
func initP2PNode(ctx *cli.Context, cfg *config.OntologyConfig, txpoolSvr *proc.TXPoolServer) *p2pserver.P2PServer {
if cfg.Genesis.ConsensusType == config.CONSENSUS_TYPE_SOLO {
return nil
}
p2p, err := p2pserver.NewServer(nil, proc.NewTxPoolService(txpoolSvr))
if err != nil {
log.Fatalf("Failed to create Node P2P server: %s", err)
}
err = p2p.Start()
if err != nil {
log.Fatalf("p2p service start error: %s", err)
}
txpoolSvr.Net = p2p.GetNetwork()
bactor.SetNetServer(p2p.GetNetwork())
p2p.WaitForPeersStart()
log.Infof("P2P init success")
return p2p
}
func initNodeConfig(ctx *cli.Context) *config.OntologyConfig {
log.Infof("Ontology Node version: %s", version.Node)
log.Infof("Ontology Rosetta Server version: %s", version.Rosetta)
cfg, err := cmd.SetOntologyConfig(ctx)
if err != nil {
log.Fatalf("Failed to process node config: %s", err)
}
return cfg
}
func initServer(ctx *cli.Context,
cfg *config.OntologyConfig,
scfg *serverConfig,
node *p2pserver.P2PServer,
offline bool,
) {
store := initStore(cfg, scfg, offline)
done := make(chan bool, 1)
process.SetExitHandler(func() {
if !offline {
<-done
}
store.Close()
})
if !offline {
ctx, cancel := context.WithCancel(context.Background())
go store.IndexBlocks(ctx, services.IndexConfig{
Done: done,
WaitTime: scfg.waitTime,
})
process.SetExitHandler(cancel)
}
router, err := services.Router(node, store, offline)
if err != nil {
log.Fatalf("Failed to load the Rosetta HTTP router: %s", err)
}
srv := &http.Server{
Addr: fmt.Sprintf(":%d", scfg.Port),
Handler: router,
ReadTimeout: 30 * time.Second,
WriteTimeout: 30 * time.Second,
}
log.Infof("Starting Rosetta Server on port %d", scfg.Port)
go func() {
process.SetExitHandler(func() {
log.Info("Shutting down Rosetta HTTP Server gracefully")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Errorf("Failed to shutdown Rosetta HTTP Server gracefully: %s", err)
}
})
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Rosetta HTTP Server failed: %s", err)
}
}()
}
func initServerConfig(ctx *cli.Context) *serverConfig {
path := ctx.GlobalString(utils.GetFlagName(serverConfigFlag))
f, err := os.Open(path)
if err != nil {
log.Fatalf("Failed to open %q: %s", path, err)
}
defer f.Close()
data, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalf("Failed to read %q: %s", path, err)
}
cfg := &serverConfig{}
err = json.Unmarshal(data, cfg)
if err != nil {
log.Fatalf("Failed to decode %q: %s", path, err)
}
if cfg.BlockWait == 0 {
cfg.BlockWait = 1
}
cfg.waitTime = time.Duration(cfg.BlockWait) * time.Second
for idx, token := range cfg.OEP4Tokens {
if token.Contract == "" {
log.Fatalf(
`Missing "contract" field for OEP4 token at offset %d in %q`,
idx, path,
)
}
contract, err := common.AddressFromHexString(token.Contract)
if err != nil {
log.Fatalf(
"Invalid OEP4 contract address %q found in %q: %s",
token.Contract, path, err,
)
}
if token.Decimals < 0 {
log.Fatalf(
`Invalid "decimals" value for OEP4 token at offset %d in %q: %d`,
idx, path, token.Decimals,
)
}
if token.Symbol == "" {
log.Fatalf(
`Missing "symbol" field for OEP4 token %q in %q`,
token.Contract, path,
)
}
cfg.tokens = append(cfg.tokens, &services.OEP4Token{
Contract: contract,
Decimals: token.Decimals,
Symbol: token.Symbol,
Wasm: token.Wasm,
})
}
if cfg.Port > 65535 {
log.Fatalf("Invalid port %d specified in %q", cfg.Port, path)
}
return cfg
}
func initStore(cfg *config.OntologyConfig, scfg *serverConfig, offline bool) *services.Store {
dbDir := utils.GetStoreDirPath(config.DefConfig.Common.DataDir, config.DefConfig.P2PNode.NetworkName)
store, err := services.NewStore(filepath.Join(
dbDir,
cfg.P2PNode.NetworkName,
"store",
), scfg.tokens, offline)
if err != nil {
log.Fatalf("Unable to open the internal data store: %s", err)
}
return store
}
func initTxPool(ctx *cli.Context) *proc.TXPoolServer {
disablePreExec := ctx.GlobalBool(utils.GetFlagName(utils.TxpoolPreExecDisableFlag))
bactor.DisableSyncVerifyTx = ctx.GlobalBool(utils.GetFlagName(utils.DisableSyncVerifyTxFlag))
disableBroadcastNetTx := ctx.GlobalBool(utils.GetFlagName(utils.DisableBroadcastNetTxFlag))
txPoolServer, err := txnpool.StartTxnPoolServer(disablePreExec, disableBroadcastNetTx)
if err != nil {
log.Fatalf("init txpool error: %s", err)
}
bactor.SetTxnPoolPid(txPoolServer.GetPID())
bactor.SetTxPoolService(proc.NewTxPoolService(txPoolServer))
log.Infof("TxPool init success")
return txPoolServer
}
func run(ctx *cli.Context) {
initLog(ctx)
setMaxOpenFiles()
cfg := initNodeConfig(ctx)
scfg := initServerConfig(ctx)
if cliBool(ctx, validateStoreFlag) {
runValidateStore(ctx, cfg, scfg)
} else if cliBool(ctx, offlineFlag) {
runOffline(ctx, cfg, scfg)
} else {
runOnline(ctx, cfg, scfg)
}
}
func runOffline(ctx *cli.Context, cfg *config.OntologyConfig, scfg *serverConfig) {
initServer(ctx, cfg, scfg, &p2pserver.P2PServer{}, true)
select {}
}
func runOnline(ctx *cli.Context, cfg *config.OntologyConfig, scfg *serverConfig) {
ldg := initLedger(ctx, cfg)
txpool := initTxPool(ctx)
node := initP2PNode(ctx, cfg, txpool)
initServer(ctx, cfg, scfg, node, false)
ticker := time.NewTicker(config.DEFAULT_GEN_BLOCK_TIME * time.Second)
for range ticker.C {
log.Infof("CurrentBlockHeight = %d", ldg.GetCurrentBlockHeight())
if !disableLogFile {
nodelog.CheckRotateLogFile()
}
}
}
func runValidateStore(ctx *cli.Context, cfg *config.OntologyConfig, scfg *serverConfig) {
initLedger(ctx, cfg)
store := initStore(cfg, scfg, false)
log.Info("Started indexing any missing blocks")
store.IndexBlocks(context.Background(), services.IndexConfig{
ExitEarly: true,
WaitTime: scfg.waitTime,
})
log.Info("Finished indexing blocks")
store.Validate()
}
func setMaxOpenFiles() {
max, err := fdlimit.Maximum()
if err != nil {
log.Errorf("Failed to get fdlimit: %s", err)
return
}
_, err = fdlimit.Raise(uint64(max))
if err != nil {
log.Errorf("Failed to raise fdlimit: %s", err)
return
}
}
func main() {
if err := setupApp().Run(os.Args); err != nil {
cmd.PrintErrorMsg(err.Error())
os.Exit(1)
}
}