/
cosmosanalysis.go
306 lines (257 loc) · 7.54 KB
/
cosmosanalysis.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
// Package cosmosanalysis provides a toolset for statically analysing Cosmos SDK's
// source code and blockchain source codes based on the Cosmos SDK
package cosmosanalysis
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"golang.org/x/mod/modfile"
"github.com/ignite/cli/v29/ignite/pkg/cosmosver"
"github.com/ignite/cli/v29/ignite/pkg/errors"
"github.com/ignite/cli/v29/ignite/pkg/gomodule"
)
const (
tendermintModulePath = "github.com/cometbft/cometbft"
appFileName = "app.go"
defaultAppFilePath = "app/" + appFileName
)
var AppImplementation = []string{
"AppCodec",
"GetKey",
"GetMemKey",
"RegisterAPIRoutes",
}
// implementation tracks the implementation of an interface for a given struct.
type implementation map[string]bool
// DeepFindImplementation functions the same as FindImplementation, but walks recursively through the folder structure
// Useful if implementations might be in sub folders.
func DeepFindImplementation(modulePath string, interfaceList []string) (found []string, err error) {
err = filepath.Walk(modulePath,
func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
return nil
}
currFound, err := FindImplementation(path, interfaceList)
if err != nil {
return err
}
found = append(found, currFound...)
return nil
})
if err != nil {
return nil, err
}
return found, nil
}
// FindImplementation finds the name of all types that implement the provided interface.
func FindImplementation(modulePath string, interfaceList []string) (found []string, err error) {
// parse go packages/files under path
fset := token.NewFileSet()
pkgs, err := parser.ParseDir(fset, modulePath, nil, 0)
if err != nil {
return nil, err
}
for _, pkg := range pkgs {
var files []*ast.File
for _, f := range pkg.Files {
files = append(files, f)
}
found = append(found, findImplementationInFiles(files, interfaceList)...)
}
return found, nil
}
// FindImplementationInFile find all struct implements the interfaceList into an ast.File.
func FindImplementationInFile(n ast.Node, interfaceList []string) (found []string) {
// collect all structs under path to find out the ones that satisfies the implementation
structImplementations := make(map[string]implementation)
findImplementation(n, func(methodName, structName string) bool {
// mark the implementation that this struct satisfies.
if _, ok := structImplementations[structName]; !ok {
structImplementations[structName] = newImplementation(interfaceList)
}
structImplementations[structName][methodName] = true
return true
})
for name, impl := range structImplementations {
if checkImplementation(impl) {
found = append(found, name)
}
}
return found
}
// findImplementationInFiles find all struct implements the interfaceList into a list of ast.File.
func findImplementationInFiles(files []*ast.File, interfaceList []string) (found []string) {
// collect all structs under path to find out the ones that satisfies the implementation
structImplementations := make(map[string]implementation)
for _, f := range files {
findImplementation(f, func(methodName, structName string) bool {
// mark the implementation that this struct satisfies.
if _, ok := structImplementations[structName]; !ok {
structImplementations[structName] = newImplementation(interfaceList)
}
structImplementations[structName][methodName] = true
return true
})
}
for name, impl := range structImplementations {
if checkImplementation(impl) {
found = append(found, name)
}
}
return found
}
// findImplementation parse the ast.Node and call the callback if is a struct implementation.
func findImplementation(f ast.Node, endCallback func(methodName, structName string) bool) {
ast.Inspect(f, func(n ast.Node) bool {
// look for struct methods.
methodDecl, ok := n.(*ast.FuncDecl)
if !ok {
return true
}
// not a method.
if methodDecl.Recv == nil {
return true
}
methodName := methodDecl.Name.Name
// find the struct name that method belongs to.
t := methodDecl.Recv.List[0].Type
var ident *ast.Ident
switch t := t.(type) {
case *ast.Ident:
// method with a value receiver
ident = t
case *ast.IndexExpr:
// generic method with a value receiver
ident = t.X.(*ast.Ident)
case *ast.StarExpr:
switch t := t.X.(type) {
case *ast.Ident:
// method with a pointer receiver
ident = t
case *ast.IndexExpr:
// generic method with a pointer receiver
ident = t.X.(*ast.Ident)
default:
return true
}
default:
return true
}
structName := ident.Name
if endCallback != nil {
return endCallback(methodName, structName)
}
return true
})
}
// newImplementation returns a new object to parse implementation of an interface.
func newImplementation(interfaceList []string) implementation {
impl := make(implementation)
for _, m := range interfaceList {
impl[m] = false
}
return impl
}
// checkImplementation checks if the entire implementation is satisfied.
func checkImplementation(r implementation) bool {
for _, ok := range r {
if !ok {
return false
}
}
return true
}
// ErrPathNotChain is returned by IsChainPath() when path is not a chain path.
type ErrPathNotChain struct {
path string
err error
}
func (e ErrPathNotChain) Error() string {
return fmt.Sprintf("%s not a chain path: %v", e.path, e.err)
}
// IsChainPath returns nil if path contains a cosmos chain.
func IsChainPath(path string) error {
errf := func(err error) error {
return ErrPathNotChain{path: path, err: err}
}
modFile, err := gomodule.ParseAt(path)
if err != nil {
return errf(err)
}
if err := ValidateGoMod(modFile); err != nil {
return errf(err)
}
return nil
}
// ValidateGoMod check if the cosmos-sdk and the tendermint packages are imported.
func ValidateGoMod(module *modfile.File) error {
moduleCheck := map[string]bool{
cosmosver.CosmosModulePath: true,
tendermintModulePath: true,
}
for _, r := range module.Require {
delete(moduleCheck, r.Mod.Path)
}
for m := range moduleCheck {
return errors.Errorf("invalid go module, missing %s package dependency", m)
}
return nil
}
// FindAppFilePath looks for the app file that implements the interfaces listed in AppImplementation.
func FindAppFilePath(chainRoot string) (path string, err error) {
var found []string
err = filepath.Walk(chainRoot, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() || filepath.Ext(info.Name()) != ".go" {
return nil
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
return err
}
currFound := findImplementationInFiles([]*ast.File{f}, AppImplementation)
if len(currFound) > 0 {
found = append(found, path)
}
return nil
})
if err != nil {
return "", err
}
numFound := len(found)
if numFound == 0 {
return "", errors.New("app.go file cannot be found")
}
if numFound == 1 {
return found[0], nil
}
appFilePath := ""
for _, p := range found {
if filepath.Base(p) == appFileName {
if appFilePath != "" {
// multiple app.go found, fallback to app/app.go
return getDefaultAppFile(chainRoot)
}
appFilePath = p
}
}
if appFilePath != "" {
return appFilePath, nil
}
return getDefaultAppFile(chainRoot)
}
// getDefaultAppFile returns the default app.go file path for a chain.
func getDefaultAppFile(chainRoot string) (string, error) {
path := filepath.Join(chainRoot, defaultAppFilePath)
_, err := os.Stat(path)
return path, errors.Wrap(err, "cannot locate your app.go")
}