-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
262 lines (234 loc) · 7.91 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
package main
import (
"context"
"das-multi-device/block_parser"
"das-multi-device/cache"
"das-multi-device/config"
"das-multi-device/dao"
"das-multi-device/http_server"
"das-multi-device/prometheus"
"fmt"
"github.com/dotbitHQ/das-lib/common"
"github.com/dotbitHQ/das-lib/core"
"github.com/dotbitHQ/das-lib/dascache"
"github.com/dotbitHQ/das-lib/http_api"
"github.com/dotbitHQ/das-lib/remote_sign"
"github.com/dotbitHQ/das-lib/sign"
"github.com/dotbitHQ/das-lib/txbuilder"
"github.com/nervosnetwork/ckb-sdk-go/address"
"github.com/nervosnetwork/ckb-sdk-go/rpc"
"github.com/nervosnetwork/ckb-sdk-go/types"
"github.com/scorpiotzh/toolib"
"github.com/dotbitHQ/das-lib/http_api/logger"
"github.com/urfave/cli/v2"
"os"
"sync"
"time"
)
var (
log = logger.NewLogger("main", logger.LevelDebug)
exit = make(chan struct{})
ctxServer, cancel = context.WithCancel(context.Background())
wgServer = sync.WaitGroup{}
)
func main() {
log.Debug("start:")
app := &cli.App{
Flags: []cli.Flag{
&cli.StringFlag{
Name: "config",
Aliases: []string{"c"},
Usage: "Load configuration from `FILE`",
},
&cli.StringFlag{
Name: "mode",
Aliases: []string{"m"},
Usage: "Server Type, ``(default): api and timer server, `api`: api server, `timer`: timer server",
},
},
Action: runServer,
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func runServer(ctx *cli.Context) error {
// config file
configFilePath := ctx.String("config")
if err := config.InitCfg(configFilePath); err != nil {
return err
}
// config file watcher
watcher, err := config.AddCfgFileWatcher(configFilePath)
if err != nil {
return fmt.Errorf("AddCfgFileWatcher err: %s", err.Error())
}
// ============= service start =============
//sentry
if err := http_api.SentryInit(config.Cfg.Notify.SentryDsn); err != nil {
return fmt.Errorf("SentryInit err: %s", err.Error())
}
defer http_api.RecoverPanic()
// prometheus
prometheus.Init()
prometheus.Tools.Run()
// db
dbDao, err := dao.NewGormDB(config.Cfg.DB.Mysql, config.Cfg.DB.ParserMysql, true)
if err != nil {
return fmt.Errorf("NewGormDB err: %s", err.Error())
}
log.Debug("db ok")
// redis
red, err := toolib.NewRedisClient(config.Cfg.Cache.Redis.Addr, config.Cfg.Cache.Redis.Password, config.Cfg.Cache.Redis.DbNum)
if err != nil {
log.Errorf("NewRedisClient err: %s", err.Error())
//return fmt.Errorf("NewRedisClient err:%s", err.Error())
} else {
log.Debug("redis ok")
}
rc := cache.Initialize(red)
// das core
dasCore, dasCache, err := initDasCore()
if err != nil {
return fmt.Errorf("initDasCore err: %s", err.Error())
}
// tx builder
txBuilderBase, serverScript, err := initTxBuilder(dasCore)
if err != nil {
return fmt.Errorf("initTxBuilder err: %s", err.Error())
}
//service mode
mode := ctx.String("mode")
if mode == "api" {
if err := initApiServer(txBuilderBase, serverScript, dasCore, dasCache, dbDao, rc); err != nil {
return fmt.Errorf("initApiServer err : %s", err.Error())
}
} else if mode == "timer" {
if err := initTimer(dasCore, dbDao); err != nil {
return fmt.Errorf("initTimer err : %s", err.Error())
}
} else {
if err := initTimer(dasCore, dbDao); err != nil {
return fmt.Errorf("initTimer err : %s", err.Error())
}
if err := initApiServer(txBuilderBase, serverScript, dasCore, dasCache, dbDao, rc); err != nil {
return fmt.Errorf("initApiServer err : %s", err.Error())
}
}
// ============= service end =============
toolib.ExitMonitoring(func(sig os.Signal) {
log.Warn("ExitMonitoring:", sig.String())
if watcher != nil {
log.Warn("close watcher ... ")
_ = watcher.Close()
}
cancel()
wgServer.Wait()
log.Warn("success exit server. bye bye!")
time.Sleep(time.Second)
exit <- struct{}{}
})
<-exit
return nil
}
func initDasCore() (*core.DasCore, *dascache.DasCache, error) {
// ckb node
ckbClient, err := rpc.DialWithIndexer(config.Cfg.Chain.CkbUrl, config.Cfg.Chain.IndexUrl)
if err != nil {
return nil, nil, fmt.Errorf("rpc.DialWithIndexer err: %s", err.Error())
}
log.Info("ckb node ok")
// das init
env := core.InitEnvOpt(config.Cfg.Server.Net, common.DasContractNameConfigCellType, common.DasContractNameAccountCellType,
common.DasContractNameBalanceCellType, common.DasContractNameDispatchCellType, common.DasContractNameAlwaysSuccess,
common.DASContractNameEip712LibCellType, common.DasKeyListCellType)
ops := []core.DasCoreOption{
core.WithClient(ckbClient),
core.WithDasContractArgs(env.ContractArgs),
core.WithDasContractCodeHash(env.ContractCodeHash),
core.WithDasNetType(config.Cfg.Server.Net),
core.WithTHQCodeHash(env.THQCodeHash),
}
dasCore := core.NewDasCore(ctxServer, &wgServer, ops...)
dasCore.InitDasContract(env.MapContract)
if err := dasCore.InitDasConfigCell(); err != nil {
return nil, nil, fmt.Errorf("InitDasConfigCell err: %s", err.Error())
}
if err := dasCore.InitDasSoScript(); err != nil {
return nil, nil, fmt.Errorf("InitDasSoScript err: %s", err.Error())
}
dasCore.RunAsyncDasContract(time.Minute * 3) // contract outpoint
dasCore.RunAsyncDasConfigCell(time.Minute * 5) // config cell outpoint
dasCore.RunAsyncDasSoScript(time.Minute * 7) // so
log.Info("das contract ok")
// das cache
dasCache := dascache.NewDasCache(ctxServer, &wgServer)
dasCache.RunClearExpiredOutPoint(time.Minute * 15)
log.Info("das cache ok")
return dasCore, dasCache, nil
}
func initTxBuilder(dasCore *core.DasCore) (*txbuilder.DasTxBuilderBase, *types.Script, error) {
payServerAddressArgs := ""
var serverScript *types.Script
if config.Cfg.Server.PayServerAddress != "" {
parseAddress, err := address.Parse(config.Cfg.Server.PayServerAddress)
if err != nil {
log.Error("pay server address.Parse err: ", err.Error())
} else {
payServerAddressArgs = common.Bytes2Hex(parseAddress.Script.Args)
serverScript = parseAddress.Script
}
}
var handleSign sign.HandleSignCkbMessage
if config.Cfg.Server.RemoteSignApiUrl != "" && payServerAddressArgs != "" {
//remoteSignClient, err := sign.NewClient(ctxServer, config.Cfg.Server.RemoteSignApiUrl)
//if err != nil {
// return nil, nil, fmt.Errorf("sign.NewClient err: %s", err.Error())
//}
//handleSign = sign.RemoteSign(remoteSignClient, config.Cfg.Server.Net, payServerAddressArgs)
handleSign = remote_sign.SignTxForCKBHandle(config.Cfg.Server.RemoteSignApiUrl, config.Cfg.Server.PayServerAddress)
} else if config.Cfg.Server.PayPrivate != "" {
handleSign = sign.LocalSign(config.Cfg.Server.PayPrivate)
}
txBuilderBase := txbuilder.NewDasTxBuilderBase(ctxServer, dasCore, handleSign, payServerAddressArgs)
log.Info("tx builder ok")
return txBuilderBase, serverScript, nil
}
func initTimer(dasCore *core.DasCore, dbDao *dao.DbDao) error {
// block parser
bp := block_parser.BlockParser{
DasCore: dasCore,
CurrentBlockNumber: config.Cfg.Chain.CurrentBlockNumber,
DbDao: dbDao,
ConcurrencyNum: config.Cfg.Chain.ConcurrencyNum,
ConfirmNum: config.Cfg.Chain.ConfirmNum,
Ctx: ctxServer,
Cancel: cancel,
Wg: &wgServer,
}
if err := bp.Run(); err != nil {
return fmt.Errorf("block parser err: %s", err.Error())
}
log.Debug("block parser ok")
return nil
}
func initApiServer(txBuilderBase *txbuilder.DasTxBuilderBase, serverScript *types.Script, dasCore *core.DasCore, dasCache *dascache.DasCache, dbDao *dao.DbDao, rc *cache.RedisCache) error {
// http
hs, err := http_server.Initialize(http_server.HttpServerParams{
Address: config.Cfg.Server.HttpServerAddr,
InternalAddress: config.Cfg.Server.HttpServerInternalAddr,
DbDao: dbDao,
Rc: rc,
Ctx: ctxServer,
DasCore: dasCore,
DasCache: dasCache,
TxBuilderBase: txBuilderBase,
ServerScript: serverScript,
})
if err != nil {
return fmt.Errorf("http server Initialize err:%s", err.Error())
}
hs.Run()
log.Debug("httpserver ok")
return nil
}