-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.go
355 lines (323 loc) · 9.84 KB
/
main.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
package main
import (
"context"
"fmt"
"os"
"strings"
"sync"
"time"
"github.com/cometbft/cometbft/rpc/client/http"
coretypes "github.com/cometbft/cometbft/rpc/core/types"
"github.com/fatih/color"
)
var (
uniquePeers map[string]bool
uniquePeersMu sync.RWMutex
visited = struct {
sync.RWMutex
nodes map[string]bool
}{nodes: make(map[string]bool)}
earliestBlock map[string]int
earliestBlockMu sync.RWMutex
rpcAddr map[string]bool
rpcAddrMu sync.RWMutex
moniker map[string]string
monikerMu sync.RWMutex
initialNode string
totalNodesChecked int
initialChainID string
archiveNodes map[string]bool
archiveNodesMu sync.RWMutex
)
func main() {
initialNodes := []string{"http://localhost:26657"}
if len(os.Args) > 1 {
initialNodes = strings.Split(os.Args[1], " ")
}
uniquePeersMu.Lock()
uniquePeers = make(map[string]bool)
uniquePeersMu.Unlock()
start := time.Now()
color.Green("[%s] Starting RPC crawler...\n", start.Format("2006-01-02 15:04:05"))
for _, initialNode := range initialNodes {
go CheckNode(initialNode)
}
// Wait for all goroutines to finish
time.Sleep(60 * time.Second)
elapsed := time.Since(start)
color.Green("[%s] RPC crawler completed in %s\n", time.Now().Format("2006-01-02 15:04:05"), elapsed)
WriteNodesToToml(initialNodes[0])
}
func CheckNode(nodeAddr string) {
commonRPCPorts := []string{
"26657",
"36657",
"22257",
"14657",
"58657",
"33657",
"53657",
"37657",
"31657",
"10157",
"27957",
"2401",
"15957",
}
if IsNodeVisited(nodeAddr) {
return
}
MarkNodeAsVisited(nodeAddr)
// Check if the node is the initial node
if initialNode == "" {
earliestBlockMu.Lock()
earliestBlock = map[string]int{}
earliestBlockMu.Unlock()
rpcAddrMu.Lock()
rpcAddr = map[string]bool{}
rpcAddrMu.Unlock()
archiveNodesMu.Lock()
archiveNodes = map[string]bool{}
archiveNodesMu.Unlock()
monikerMu.Lock()
moniker = map[string]string{}
monikerMu.Unlock()
initialNode = nodeAddr
client, err := FetchClient(nodeAddr)
if err != nil {
color.Red("[%s] Failed to fetch status from %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
// Iterate through common RPC ports if the initial connection attempt fails
for _, port := range commonRPCPorts {
altNodeAddr := fmt.Sprintf("%s:%s", strings.Split(nodeAddr, ":")[0], port)
client, err = FetchClient(altNodeAddr)
if err == nil {
nodeAddr = altNodeAddr
break
}
}
if err != nil {
return
}
}
ctx := context.TODO()
status, err := client.Status(ctx)
if err != nil {
color.Red("[%s] cannot fetch status\n", time.Now().Format("2006-01-02 15:04:05"))
return
}
if status == nil {
color.Red("[%s] Status is nil for %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
initialChainID = status.NodeInfo.Network
moniker[nodeAddr] = status.NodeInfo.Moniker
}
// Skip if the node address is localhost and it's not the initial node
if nodeAddr != initialNode && strings.Contains(nodeAddr, "localhost") {
return
}
// Increment total nodes
totalNodesChecked++
client, err := FetchClient(nodeAddr)
if err != nil {
color.Red("[%s] Failed to fetch status from %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
if client == nil {
color.Red("[%s] Client is nil for %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
netinfo, err := FetchNetInfo(client)
if err == nil {
newPeers := 0
for _, peer := range netinfo.Peers {
rpcAddr := BuildRPCAddress(peer)
rpcAddr = NormalizeAddressWithRemoteIP(rpcAddr, peer.RemoteIP)
uniquePeersMu.Lock()
if !uniquePeers[rpcAddr] {
uniquePeers[rpcAddr] = true
newPeers++
}
uniquePeersMu.Unlock()
}
uniquePeersMu.RLock()
totalUniquePeers := len(uniquePeers)
uniquePeersMu.RUnlock()
color.Green("[%s] Got net info from %s with %d peers, and %d new peers for a total of %d unique peers in the network\n",
time.Now().Format("2006-01-02 15:04:05"), nodeAddr, len(netinfo.Peers), newPeers, totalUniquePeers)
ctx := context.TODO()
status, err := client.Status(ctx)
moniker[nodeAddr] = status.NodeInfo.Moniker
if err != nil {
color.Red("[%s] Failed to fetch client from %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
if status == nil {
color.Red("[%s] Status is nil for %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
// Verify chain_id
if status.NodeInfo.Network != initialChainID {
color.Red("[%s] Node %s is on a different chain_id\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
return
}
// Add to successful nodes
earliestBlock[nodeAddr] = int(status.SyncInfo.EarliestBlockHeight)
rpcAddr[nodeAddr] = true
// If the node has block 1, it's an archive node
if int(status.SyncInfo.EarliestBlockHeight) == 1 {
archiveNodes[nodeAddr] = true
}
var wg sync.WaitGroup
for _, peer := range netinfo.Peers {
wg.Add(1)
go func(peer coretypes.Peer) {
defer wg.Done()
ProcessPeer(peer)
}(peer)
}
wg.Wait()
} else {
color.Red("[%s] Failed to fetch net_info from %s\n", time.Now().Format("2006-01-02 15:04:05"), nodeAddr)
// Add to unsuccessful nodes
rpcAddr[nodeAddr] = false
return
}
}
func FetchClient(nodeAddr string) (client *http.HTTP, err error) {
client, err = http.NewWithTimeout(nodeAddr, "websocket", 500)
if err != nil {
return nil, err
}
return client, err
}
func BuildRPCAddress(peer coretypes.Peer) string {
rpcAddr := peer.NodeInfo.Other.RPCAddress
rpcAddr = strings.TrimPrefix(rpcAddr, "tcp://")
if len(rpcAddr) >= 9 && (rpcAddr[:9] == "0.0.0.0:" || rpcAddr[:9] == "127.0.0.1:") {
rpcAddr = peer.RemoteIP + rpcAddr[8:]
}
return rpcAddr
}
func WriteSectionToToml(file *os.File, nodeAddr string) {
sectionName, ok := moniker[nodeAddr]
if !ok || sectionName == "" {
sectionName = "default"
}
_, err := file.WriteString("[[nodes]]\n")
if err != nil {
color.Red("[%s] cannot write section to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
_, err = file.WriteString(fmt.Sprintf("name = \"%s\"\n", sectionName))
if err != nil {
color.Red("[%s] cannot write section to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
_, err = file.WriteString(fmt.Sprintf("earliest_block = %d\n", earliestBlock[nodeAddr]))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
writeStatus := func(service string, addr string, statusMap map[string]bool) {
status := "unsuccessful"
if statusMap[nodeAddr] {
status = "successful"
}
_, err = file.WriteString(fmt.Sprintf("%s = \"%s\"\n", service, addr))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
_, err = file.WriteString(fmt.Sprintf("%s_status = \"%s\"\n", service, status))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
}
writeStatus("rpc", nodeAddr, rpcAddr)
_, err = file.WriteString("\n")
if err != nil {
color.Red("[%s] cannot write escape sequence to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
}
func ProcessPeer(peer coretypes.Peer) {
commonRPCPorts := []string{
"26657",
"36657",
"22257",
"14657",
"58657",
"33657",
"53657",
"37657",
"31657",
"10157",
"27957",
"2401",
"15957",
}
rpcAddr := BuildRPCAddress(peer)
rpcAddr = NormalizeAddressWithRemoteIP(rpcAddr, peer.RemoteIP)
// Extract the IP address and port from the rpcAddr
parts := strings.Split(rpcAddr, ":")
ipAddr := parts[0]
// Iterate through common RPC ports and check each port
for _, port := range commonRPCPorts {
nodeAddr := fmt.Sprintf("%s:%s", ipAddr, port)
CheckNode("http://" + nodeAddr)
}
}
func FetchNetInfo(client *http.HTTP) (*coretypes.ResultNetInfo, error) {
ctx := context.Background()
netinfo, err := client.NetInfo(ctx)
return netinfo, err
}
func NormalizeAddressWithRemoteIP(nodeAddr string, remoteIP string) string {
nodeAddr = strings.ReplaceAll(nodeAddr, "0.0.0.0", remoteIP)
nodeAddr = strings.ReplaceAll(nodeAddr, "127.0.0.1", remoteIP)
return nodeAddr
}
func IsNodeVisited(nodeAddr string) bool {
visited.RLock()
defer visited.RUnlock()
_, ok := visited.nodes[nodeAddr]
return ok
}
func MarkNodeAsVisited(nodeAddr string) {
visited.Lock()
defer visited.Unlock()
visited.nodes[nodeAddr] = true
}
func WriteNodesToToml(initialNode string) {
file, err := os.Create("nodes.toml")
if err != nil {
color.Red("[%s] Error creating .toml file: %v\n", time.Now().Format("2006-01-02 15:04:05"), err)
return
}
defer file.Close()
// Write the source node to the file
_, err = file.WriteString(fmt.Sprintf("source_node = \"%s\"\n\n", initialNode))
if err != nil {
color.Red("[%s] cannot write source node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
_, err = file.WriteString(fmt.Sprintf("total_nodes_checked = %d\n\n", totalNodesChecked))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
WriteSectionToTomlSlice(file, "successful_rpc_nodes", rpcAddr, true)
color.Green("[%s] .toml file created with node details.\n", time.Now().Format("2006-01-02 15:04:05"))
}
func WriteSectionToTomlSlice(file *os.File, sectionName string, nodes map[string]bool, status bool) {
_, err := file.WriteString(fmt.Sprintf("%s = [\n", sectionName))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
for key, val := range nodes {
if val == status {
_, err = file.WriteString(fmt.Sprintf(" \"%s\",\n", key))
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
}
}
_, err = file.WriteString("]\n\n")
if err != nil {
color.Red("[%s] cannot write node to toml file\n", time.Now().Format("2006-01-02 15:04:05"))
}
}