/
util.go
279 lines (244 loc) · 7.34 KB
/
util.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
package server
import (
"encoding/json"
"net"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"errors"
"github.com/spf13/cobra"
"github.com/spf13/viper"
tcmd "github.com/tendermint/tendermint/cmd/tendermint/commands"
cfg "github.com/tendermint/tendermint/config"
"github.com/tendermint/tendermint/libs/cli"
tmflags "github.com/tendermint/tendermint/libs/cli/flags"
"github.com/tendermint/tendermint/libs/log"
pvm "github.com/tendermint/tendermint/privval"
"my-cosmos/cosmos-sdk/client"
"my-cosmos/cosmos-sdk/codec"
"my-cosmos/cosmos-sdk/server/config"
"my-cosmos/cosmos-sdk/version"
)
// server context
// 服务上下文
type Context struct {
Config *cfg.Config
Logger log.Logger
}
func NewDefaultContext() *Context {
return NewContext(
// 加载默认配置,这个是 具备 tendermint的node的默认配置
cfg.DefaultConfig(),
// 创建一个logger实例
log.NewTMLogger(log.NewSyncWriter(os.Stdout)),
)
}
func NewContext(config *cfg.Config, logger log.Logger) *Context {
return &Context{config, logger}
}
//___________________________________________________________________________________
// PersistentPreRunEFn returns a PersistentPreRunE function for cobra
// that initailizes the passed in context with a properly configured
// logger and config object.
func PersistentPreRunEFn(context *Context) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
if cmd.Name() == version.VersionCmd.Name() {
return nil
}
config, err := interceptLoadConfig()
if err != nil {
return err
}
err = validateConfig(config)
if err != nil {
return err
}
logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout))
logger, err = tmflags.ParseLogLevel(config.LogLevel, logger, cfg.DefaultLogLevel())
if err != nil {
return err
}
if viper.GetBool(cli.TraceFlag) {
logger = log.NewTracingLogger(logger)
}
logger = logger.With("module", "main")
context.Config = config
context.Logger = logger
return nil
}
}
// If a new config is created, change some of the default tendermint settings
func interceptLoadConfig() (conf *cfg.Config, err error) {
tmpConf := cfg.DefaultConfig()
err = viper.Unmarshal(tmpConf)
if err != nil {
// TODO: Handle with #870
panic(err)
}
rootDir := tmpConf.RootDir
configFilePath := filepath.Join(rootDir, "config/config.toml")
// Intercept only if the file doesn't already exist
if _, err := os.Stat(configFilePath); os.IsNotExist(err) {
// the following parse config is needed to create directories
conf, _ = tcmd.ParseConfig() // NOTE: ParseConfig() creates dir/files as necessary.
conf.ProfListenAddress = "localhost:6060"
conf.P2P.RecvRate = 5120000
conf.P2P.SendRate = 5120000
conf.TxIndex.IndexAllTags = true
conf.Consensus.TimeoutCommit = 5 * time.Second
cfg.WriteConfigFile(configFilePath, conf)
// Fall through, just so that its parsed into memory.
}
if conf == nil {
conf, err = tcmd.ParseConfig() // NOTE: ParseConfig() creates dir/files as necessary.
}
// create a default gaia config file if it does not exist
gaiaConfigFilePath := filepath.Join(rootDir, "config/gaiad.toml")
if _, err := os.Stat(gaiaConfigFilePath); os.IsNotExist(err) {
gaiaConf, _ := config.ParseConfig()
config.WriteConfigFile(gaiaConfigFilePath, gaiaConf)
}
viper.SetConfigName("gaiad")
err = viper.MergeInConfig()
return
}
// validate the config with the sdk's requirements.
func validateConfig(conf *cfg.Config) error {
if !conf.Consensus.CreateEmptyBlocks {
return errors.New("config option CreateEmptyBlocks = false is currently unsupported")
}
return nil
}
// add server commands
// 添加 服务的命令行参数及组件
func AddCommands(
// 入参的上下文,及编码解码器
ctx *Context, cdc *codec.Codec,
// 一个命令行实例
rootCmd *cobra.Command,
// 一个 app 构造器函数
// 一个 状态及交易的导出器函数
// 其实这个就是 newApp()
appCreator AppCreator, appExport AppExporter) {
/**
################
################
方法的主体 部分
################
################
*/
rootCmd.PersistentFlags().String("log_level", ctx.Config.LogLevel, "Log level")
// 构造一个底层 tendermint 共识的命令行实例?
tendermintCmd := &cobra.Command{
Use: "tendermint",
Short: "Tendermint subcommands",
}
// 各种把上下文添加到 底层tendermint共识命令行实例中
tendermintCmd.AddCommand(
ShowNodeIDCmd(ctx),
ShowValidatorCmd(ctx),
ShowAddressCmd(ctx),
VersionCmd(ctx),
)
// 也是各种注册命令组件
rootCmd.AddCommand(
// 添加 GaiaApp 启动回调函数
StartCmd(ctx, appCreator),
UnsafeResetAllCmd(ctx),
client.LineBreak,
tendermintCmd,
ExportCmd(ctx, cdc, appExport),
client.LineBreak,
version.VersionCmd,
)
}
//___________________________________________________________________________________
// InsertKeyJSON inserts a new JSON field/key with a given value to an existing
// JSON message. An error is returned if any serialization operation fails.
//
// NOTE: The ordering of the keys returned as the resulting JSON message is
// non-deterministic, so the client should not rely on key ordering.
func InsertKeyJSON(cdc *codec.Codec, baseJSON []byte, key string, value json.RawMessage) ([]byte, error) {
var jsonMap map[string]json.RawMessage
if err := cdc.UnmarshalJSON(baseJSON, &jsonMap); err != nil {
return nil, err
}
jsonMap[key] = value
bz, err := codec.MarshalJSONIndent(cdc, jsonMap)
return json.RawMessage(bz), err
}
// https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go
// TODO there must be a better way to get external IP
func ExternalIP() (string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return "", err
}
for _, iface := range ifaces {
if skipInterface(iface) {
continue
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
ip := addrToIP(addr)
if ip == nil || ip.IsLoopback() {
continue
}
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
return ip.String(), nil
}
}
return "", errors.New("are you connected to the network?")
}
// TrapSignal traps SIGINT and SIGTERM and terminates the server correctly.
func TrapSignal(cleanupFunc func()) {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
switch sig {
case syscall.SIGTERM:
defer cleanupFunc()
os.Exit(128 + int(syscall.SIGTERM))
case syscall.SIGINT:
defer cleanupFunc()
os.Exit(128 + int(syscall.SIGINT))
}
}()
}
// UpgradeOldPrivValFile converts old priv_validator.json file (prior to Tendermint 0.28)
// to the new priv_validator_key.json and priv_validator_state.json files.
func UpgradeOldPrivValFile(config *cfg.Config) {
if _, err := os.Stat(config.OldPrivValidatorFile()); !os.IsNotExist(err) {
if oldFilePV, err := pvm.LoadOldFilePV(config.OldPrivValidatorFile()); err == nil {
oldFilePV.Upgrade(config.PrivValidatorKeyFile(), config.PrivValidatorStateFile())
}
}
}
func skipInterface(iface net.Interface) bool {
if iface.Flags&net.FlagUp == 0 {
return true // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
return true // loopback interface
}
return false
}
func addrToIP(addr net.Addr) net.IP {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
return ip
}