forked from EscanBE/evermint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
block.go
92 lines (77 loc) · 2.41 KB
/
block.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
package inspect
import (
"cosmossdk.io/errors"
"encoding/json"
"fmt"
dbm "github.com/cometbft/cometbft-db"
tmstore "github.com/cometbft/cometbft/store"
"github.com/cosmos/cosmos-sdk/server"
"github.com/spf13/cobra"
"path/filepath"
"strconv"
"strings"
)
func BlockCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "block [latest | <height>]",
Short: "Get a specific block or latest block persisted in the db, marshal to JSON and print out",
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
var reqHeight int64
reqHeightStr := strings.TrimSpace(strings.ToLower(args[0]))
switch strings.TrimSpace(strings.ToLower(args[0])) {
case "latest", "last", "0", "newest", "-1", "":
reqHeight = 0 // ya I know, but it's enhance the readability of the code
break
default:
var err error
reqHeight, err = strconv.ParseInt(reqHeightStr, 10, 64)
if err != nil {
panic(errors.Wrap(err, fmt.Sprintf("bad block height: %s", reqHeightStr)))
}
if reqHeight < 0 {
panic("invalid block height")
}
break
}
serverCtx := server.GetServerContextFromCmd(cmd)
cfg := serverCtx.Config
home := cfg.RootDir
dataDir := filepath.Join(home, "data")
db, err := dbm.NewDB("blockstore", server.GetAppDBBackend(serverCtx.Viper), dataDir)
if err != nil {
panic(errors.Wrap(err, "error while opening db"))
}
blockStoreState := tmstore.LoadBlockStoreState(db)
if reqHeight == 0 {
reqHeight = blockStoreState.Height
} else {
if reqHeight > blockStoreState.Height {
panic(fmt.Sprintf("requested height %d is greater than latest height %d in db", reqHeight, blockStoreState.Height))
}
}
if reqHeight == blockStoreState.Height {
fmt.Println("Requested latest block height:", reqHeight)
} else {
fmt.Println("Latest block height:", blockStoreState.Height)
fmt.Println("Requested block height:", reqHeight)
}
blockStore := tmstore.NewBlockStore(db)
block := blockStore.LoadBlock(reqHeight)
bz, err := json.Marshal(block)
if err != nil {
panic(errors.Wrap(err, "failed to marshal block to JSON"))
}
fmt.Println("--- Block ---")
fmt.Println(string(bz))
meta := blockStore.LoadBaseMeta()
bz, err = json.Marshal(meta)
if err != nil {
panic(errors.Wrap(err, "failed to marshal block meta to JSON"))
}
fmt.Println("--- Meta ---")
fmt.Println(string(bz))
},
}
return cmd
}