/
helper.go
244 lines (201 loc) · 6.25 KB
/
helper.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
package helper
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/url"
"time"
"github.com/Coinmaxify/Coinmaxify/chain"
"github.com/Coinmaxify/Coinmaxify/command"
ibftOp "github.com/Coinmaxify/Coinmaxify/consensus/ibft/proto"
"github.com/Coinmaxify/Coinmaxify/server"
"github.com/Coinmaxify/Coinmaxify/server/proto"
txpoolOp "github.com/Coinmaxify/Coinmaxify/txpool/proto"
"github.com/spf13/cobra"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"github.com/Coinmaxify/Coinmaxify/helper/common"
"github.com/ryanuber/columnize"
)
type ClientCloseResult struct {
Message string `json:"message"`
}
func (r *ClientCloseResult) GetOutput() string {
return r.Message
}
type IPBinding string
const (
LocalHostBinding IPBinding = "127.0.0.1"
AllInterfacesBinding IPBinding = "0.0.0.0"
)
// HandleSignals is a helper method for handling signals sent to the console
// Like stop, error, etc.
func HandleSignals(
closeFn func(),
outputter command.OutputFormatter,
) error {
signalCh := common.GetTerminationSignalCh()
sig := <-signalCh
closeMessage := fmt.Sprintf("\n[SIGNAL] Caught signal: %v\n", sig)
closeMessage += "Gracefully shutting down client...\n"
outputter.SetCommandResult(
&ClientCloseResult{
Message: closeMessage,
},
)
outputter.WriteOutput()
// Call the Minimal server close callback
gracefulCh := make(chan struct{})
go func() {
if closeFn != nil {
closeFn()
}
close(gracefulCh)
}()
select {
case <-signalCh:
return errors.New("shutdown by signal channel")
case <-time.After(5 * time.Second):
return errors.New("shutdown by timeout")
case <-gracefulCh:
return nil
}
}
// FormatList formats a list, using a specific blank value replacement
func FormatList(in []string) string {
columnConf := columnize.DefaultConfig()
columnConf.Empty = "<none>"
return columnize.Format(in, columnConf)
}
// FormatKV formats key value pairs:
//
// Key = Value
//
// Key = <none>
func FormatKV(in []string) string {
columnConf := columnize.DefaultConfig()
columnConf.Empty = "<none>"
columnConf.Glue = " = "
return columnize.Format(in, columnConf)
}
// GetTxPoolClientConnection returns the TxPool operator client connection
func GetTxPoolClientConnection(address string) (
txpoolOp.TxnPoolOperatorClient,
error,
) {
conn, err := GetGRPCConnection(address)
if err != nil {
return nil, err
}
return txpoolOp.NewTxnPoolOperatorClient(conn), nil
}
// GetSystemClientConnection returns the System operator client connection
func GetSystemClientConnection(address string) (
proto.SystemClient,
error,
) {
conn, err := GetGRPCConnection(address)
if err != nil {
return nil, err
}
return proto.NewSystemClient(conn), nil
}
// GetIBFTOperatorClientConnection returns the IBFT operator client connection
func GetIBFTOperatorClientConnection(address string) (
ibftOp.IbftOperatorClient,
error,
) {
conn, err := GetGRPCConnection(address)
if err != nil {
return nil, err
}
return ibftOp.NewIbftOperatorClient(conn), nil
}
// GetGRPCConnection returns a grpc client connection
func GetGRPCConnection(address string) (*grpc.ClientConn, error) {
conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
return nil, fmt.Errorf("failed to connect to server: %w", err)
}
return conn, nil
}
// GetGRPCAddress extracts the set GRPC address
func GetGRPCAddress(cmd *cobra.Command) string {
if cmd.Flags().Changed(command.GRPCAddressFlagLEGACY) {
// The legacy GRPC flag was set, use that value
return cmd.Flag(command.GRPCAddressFlagLEGACY).Value.String()
}
return cmd.Flag(command.GRPCAddressFlag).Value.String()
}
// GetJSONRPCAddress extracts the set JSON-RPC address
func GetJSONRPCAddress(cmd *cobra.Command) string {
return cmd.Flag(command.JSONRPCFlag).Value.String()
}
// RegisterJSONOutputFlag registers the --json output setting for all child commands
func RegisterJSONOutputFlag(cmd *cobra.Command) {
cmd.PersistentFlags().Bool(
command.JSONOutputFlag,
false,
"get all outputs in json format (default false)",
)
}
// RegisterGRPCAddressFlag registers the base GRPC address flag for all child commands
func RegisterGRPCAddressFlag(cmd *cobra.Command) {
cmd.PersistentFlags().String(
command.GRPCAddressFlag,
fmt.Sprintf("%s:%d", LocalHostBinding, server.DefaultGRPCPort),
"the GRPC interface",
)
}
// RegisterLegacyGRPCAddressFlag registers the legacy GRPC address flag for all child commands
func RegisterLegacyGRPCAddressFlag(cmd *cobra.Command) {
cmd.PersistentFlags().String(
command.GRPCAddressFlagLEGACY,
fmt.Sprintf("%s:%d", LocalHostBinding, server.DefaultGRPCPort),
"the GRPC interface",
)
// Mark the legacy grpc flag as hidden
_ = cmd.PersistentFlags().MarkHidden(command.GRPCAddressFlagLEGACY)
}
// ParseGRPCAddress parses the passed in GRPC address
func ParseGRPCAddress(grpcAddress string) (*net.TCPAddr, error) {
return net.ResolveTCPAddr("tcp", grpcAddress)
}
// RegisterJSONRPCFlag registers the base JSON-RPC address flag for all child commands
func RegisterJSONRPCFlag(cmd *cobra.Command) {
cmd.PersistentFlags().String(
command.JSONRPCFlag,
fmt.Sprintf("%s:%d", AllInterfacesBinding, server.DefaultJSONRPCPort),
"the JSON-RPC interface",
)
}
// ParseJSONRPCAddress parses the passed in JSONRPC address
func ParseJSONRPCAddress(jsonrpcAddress string) (*url.URL, error) {
return url.ParseRequestURI(jsonrpcAddress)
}
// ResolveAddr resolves the passed in TCP address
// The second param is the default ip to bind to, if no ip address is specified
func ResolveAddr(address string, defaultIP IPBinding) (*net.TCPAddr, error) {
addr, err := net.ResolveTCPAddr("tcp", address)
if err != nil {
return nil, fmt.Errorf("failed to parse addr '%s': %w", address, err)
}
if addr.IP == nil {
addr.IP = net.ParseIP(string(defaultIP))
}
return addr, nil
}
// WriteGenesisConfigToDisk writes the passed in configuration to a genesis file at the specified path
func WriteGenesisConfigToDisk(genesisConfig *chain.Chain, genesisPath string) error {
data, err := json.MarshalIndent(genesisConfig, "", " ")
if err != nil {
return fmt.Errorf("failed to generate genesis: %w", err)
}
//nolint:gosec
if err := ioutil.WriteFile(genesisPath, data, 0644); err != nil {
return fmt.Errorf("failed to write genesis: %w", err)
}
return nil
}