forked from gnolang/gno
-
Notifications
You must be signed in to change notification settings - Fork 0
/
start.go
432 lines (363 loc) · 10.6 KB
/
start.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
package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/gnolang/gno/gno.land/pkg/gnoland"
"github.com/gnolang/gno/gno.land/pkg/log"
"github.com/gnolang/gno/gnovm/pkg/gnoenv"
abci "github.com/gnolang/gno/tm2/pkg/bft/abci/types"
"github.com/gnolang/gno/tm2/pkg/bft/config"
"github.com/gnolang/gno/tm2/pkg/bft/node"
"github.com/gnolang/gno/tm2/pkg/bft/privval"
bft "github.com/gnolang/gno/tm2/pkg/bft/types"
"github.com/gnolang/gno/tm2/pkg/commands"
"github.com/gnolang/gno/tm2/pkg/crypto"
"github.com/gnolang/gno/tm2/pkg/events"
osm "github.com/gnolang/gno/tm2/pkg/os"
"github.com/gnolang/gno/tm2/pkg/telemetry"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const defaultNodeDir = "gnoland-data"
var errMissingGenesis = errors.New("missing genesis.json")
var startGraphic = strings.ReplaceAll(`
__ __
___ ____ ___ / /__ ____ ___/ /
/ _ '/ _ \/ _ \_ / / _ '/ _ \/ _ /
\_, /_//_/\___(_)_/\_,_/_//_/\_,_/
/___/
`, "'", "`")
type startCfg struct {
gnoRootDir string // TODO: remove as part of https://github.com/gnolang/gno/issues/1952
skipFailingGenesisTxs bool // TODO: remove as part of https://github.com/gnolang/gno/issues/1952
genesisBalancesFile string // TODO: remove as part of https://github.com/gnolang/gno/issues/1952
genesisTxsFile string // TODO: remove as part of https://github.com/gnolang/gno/issues/1952
genesisRemote string // TODO: remove as part of https://github.com/gnolang/gno/issues/1952
genesisFile string
chainID string
dataDir string
genesisMaxVMCycles int64
config string
lazyInit bool
logLevel string
logFormat string
}
func newStartCmd(io commands.IO) *commands.Command {
cfg := &startCfg{}
return commands.NewCommand(
commands.Metadata{
Name: "start",
ShortUsage: "start [flags]",
ShortHelp: "starts the Gnoland blockchain node",
LongHelp: "Starts the Gnoland blockchain node, with accompanying setup",
},
cfg,
func(ctx context.Context, _ []string) error {
return execStart(ctx, cfg, io)
},
)
}
func (c *startCfg) RegisterFlags(fs *flag.FlagSet) {
gnoroot := gnoenv.RootDir()
defaultGenesisBalancesFile := filepath.Join(gnoroot, "gno.land", "genesis", "genesis_balances.txt")
defaultGenesisTxsFile := filepath.Join(gnoroot, "gno.land", "genesis", "genesis_txs.jsonl")
fs.BoolVar(
&c.skipFailingGenesisTxs,
"skip-failing-genesis-txs",
false,
"don't panic when replaying invalid genesis txs",
)
fs.StringVar(
&c.genesisBalancesFile,
"genesis-balances-file",
defaultGenesisBalancesFile,
"initial distribution file",
)
fs.StringVar(
&c.genesisTxsFile,
"genesis-txs-file",
defaultGenesisTxsFile,
"initial txs to replay",
)
fs.StringVar(
&c.genesisFile,
"genesis",
"genesis.json",
"the path to the genesis.json",
)
fs.StringVar(
&c.chainID,
"chainid",
"dev",
"the ID of the chain",
)
fs.StringVar(
&c.gnoRootDir,
"gnoroot-dir",
gnoroot,
"the root directory of the gno repository",
)
fs.StringVar(
&c.dataDir,
"data-dir",
defaultNodeDir,
"the path to the node's data directory",
)
fs.StringVar(
&c.genesisRemote,
"genesis-remote",
"localhost:26657",
"replacement for '%%REMOTE%%' in genesis",
)
fs.Int64Var(
&c.genesisMaxVMCycles,
"genesis-max-vm-cycles",
100_000_000,
"set maximum allowed vm cycles per operation. Zero means no limit.",
)
fs.StringVar(
&c.config,
flagConfigFlag,
"",
"the flag config file (optional)",
)
fs.StringVar(
&c.logLevel,
"log-level",
zapcore.DebugLevel.String(),
"log level for the gnoland node,",
)
fs.StringVar(
&c.logFormat,
"log-format",
log.ConsoleFormat.String(),
"log format for the gnoland node",
)
fs.BoolVar(
&c.lazyInit,
"lazy",
false,
"flag indicating if lazy init is enabled. Generates the node secrets, configuration, and genesis.json",
)
}
func execStart(ctx context.Context, c *startCfg, io commands.IO) error {
// Get the absolute path to the node's data directory
nodeDir, err := filepath.Abs(c.dataDir)
if err != nil {
return fmt.Errorf("unable to get absolute path for data directory, %w", err)
}
// Get the absolute path to the node's genesis.json
genesisPath, err := filepath.Abs(c.genesisFile)
if err != nil {
return fmt.Errorf("unable to get absolute path for the genesis.json, %w", err)
}
// Initialize the logger
zapLogger, err := initializeLogger(io.Out(), c.logLevel, c.logFormat)
if err != nil {
return fmt.Errorf("unable to initialize zap logger, %w", err)
}
defer func() {
// Sync the logger before exiting
_ = zapLogger.Sync()
}()
// Wrap the zap logger
logger := log.ZapLoggerToSlog(zapLogger)
if c.lazyInit {
if err := lazyInitNodeDir(io, nodeDir); err != nil {
return fmt.Errorf("unable to lazy-init the node directory, %w", err)
}
}
// Load the configuration
cfg, err := config.LoadConfig(nodeDir)
if err != nil {
return fmt.Errorf("%s, %w", tryConfigInit, err)
}
// Check if the genesis.json exists
if !osm.FileExists(genesisPath) {
if !c.lazyInit {
return errMissingGenesis
}
// Load the private validator secrets
privateKey := privval.LoadFilePV(
cfg.PrivValidatorKeyFile(),
cfg.PrivValidatorStateFile(),
)
// Init a new genesis.json
if err := lazyInitGenesis(io, c, genesisPath, privateKey.GetPubKey()); err != nil {
return fmt.Errorf("unable to initialize genesis.json, %w", err)
}
}
// Initialize telemetry
if err := telemetry.Init(*cfg.Telemetry); err != nil {
return fmt.Errorf("unable to initialize telemetry, %w", err)
}
// Print the starting graphic
if c.logFormat != string(log.JSONFormat) {
io.Println(startGraphic)
}
// Create a top-level shared event switch
evsw := events.NewEventSwitch()
// Create application and node
cfg.LocalApp, err = gnoland.NewApp(nodeDir, c.skipFailingGenesisTxs, evsw, logger)
if err != nil {
return fmt.Errorf("unable to create the Gnoland app, %w", err)
}
// Create a default node, with the given setup
gnoNode, err := node.DefaultNewNode(cfg, genesisPath, evsw, logger)
if err != nil {
return fmt.Errorf("unable to create the Gnoland node, %w", err)
}
// Start the node (async)
if err := gnoNode.Start(); err != nil {
return fmt.Errorf("unable to start the Gnoland node, %w", err)
}
// Set up the wait context
nodeCtx, _ := signal.NotifyContext(
ctx,
os.Interrupt,
syscall.SIGINT,
syscall.SIGTERM,
syscall.SIGQUIT,
)
// Wait for the exit signal
<-nodeCtx.Done()
if !gnoNode.IsRunning() {
return nil
}
// Gracefully stop the gno node
if err := gnoNode.Stop(); err != nil {
return fmt.Errorf("unable to gracefully stop the Gnoland node, %w", err)
}
return nil
}
// lazyInitNodeDir initializes new secrets, and a default configuration
// in the given node directory, if not present
func lazyInitNodeDir(io commands.IO, nodeDir string) error {
var (
configPath = constructConfigPath(nodeDir)
secretsPath = constructSecretsPath(nodeDir)
)
// Check if the configuration already exists
if !osm.FileExists(configPath) {
// Create the gnoland config options
cfg := &configInitCfg{
configCfg: configCfg{
configPath: constructConfigPath(nodeDir),
},
}
// Run gnoland config init
if err := execConfigInit(cfg, io); err != nil {
return fmt.Errorf("unable to initialize config, %w", err)
}
io.Printfln("WARN: Initialized default node config at %q", filepath.Dir(cfg.configPath))
io.Println()
}
// Create the gnoland secrets options
secrets := &secretsInitCfg{
commonAllCfg: commonAllCfg{
dataDir: secretsPath,
},
forceOverwrite: false, // existing secrets shouldn't be pruned
}
// Run gnoland secrets init
err := execSecretsInit(secrets, []string{}, io)
if err == nil {
io.Printfln("WARN: Initialized default node secrets at %q", secrets.dataDir)
return nil
}
// Check if the error is valid
if errors.Is(err, errOverwriteNotEnabled) {
// No new secrets were generated
return nil
}
return fmt.Errorf("unable to initialize secrets, %w", err)
}
// lazyInitGenesis a new genesis.json file, with a signle validator
func lazyInitGenesis(
io commands.IO,
c *startCfg,
genesisPath string,
publicKey crypto.PubKey,
) error {
// Check if the genesis.json is present
if osm.FileExists(genesisPath) {
return nil
}
// Generate the new genesis.json file
if err := generateGenesisFile(genesisPath, publicKey, c); err != nil {
return fmt.Errorf("unable to generate genesis file, %w", err)
}
io.Printfln("WARN: Initialized genesis.json at %q", genesisPath)
return nil
}
// initializeLogger initializes the zap logger using the given format and log level,
// outputting to the given IO
func initializeLogger(io io.WriteCloser, logLevel, logFormat string) (*zap.Logger, error) {
// Initialize the log level
level, err := zapcore.ParseLevel(logLevel)
if err != nil {
return nil, fmt.Errorf("unable to parse log level, %w", err)
}
// Initialize the log format
format := log.Format(strings.ToLower(logFormat))
// Initialize the zap logger
return log.GetZapLoggerFn(format)(io, level), nil
}
func generateGenesisFile(genesisFile string, pk crypto.PubKey, c *startCfg) error {
gen := &bft.GenesisDoc{}
gen.GenesisTime = time.Now()
gen.ChainID = c.chainID
gen.ConsensusParams = abci.ConsensusParams{
Block: &abci.BlockParams{
// TODO: update limits.
MaxTxBytes: 1_000_000, // 1MB,
MaxDataBytes: 2_000_000, // 2MB,
MaxGas: 100_000_000, // 100M gas
TimeIotaMS: 100, // 100ms
},
}
gen.Validators = []bft.GenesisValidator{
{
Address: pk.Address(),
PubKey: pk,
Power: 10,
Name: "testvalidator",
},
}
// Load balances files
balances, err := gnoland.LoadGenesisBalancesFile(c.genesisBalancesFile)
if err != nil {
return fmt.Errorf("unable to load genesis balances file %q: %w", c.genesisBalancesFile, err)
}
// Load examples folder
examplesDir := filepath.Join(c.gnoRootDir, "examples")
pkgsTxs, err := gnoland.LoadPackagesFromDir(examplesDir, genesisDeployAddress, genesisDeployFee)
if err != nil {
return fmt.Errorf("unable to load examples folder: %w", err)
}
// Load Genesis TXs
genesisTxs, err := gnoland.LoadGenesisTxsFile(c.genesisTxsFile, c.chainID, c.genesisRemote)
if err != nil {
return fmt.Errorf("unable to load genesis txs file: %w", err)
}
genesisTxs = append(pkgsTxs, genesisTxs...)
// Construct genesis AppState.
gen.AppState = gnoland.GnoGenesisState{
Balances: balances,
Txs: genesisTxs,
}
// Write genesis state
if err := gen.SaveAs(genesisFile); err != nil {
return fmt.Errorf("unable to write genesis file %q: %w", genesisFile, err)
}
return nil
}