-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
477 lines (407 loc) · 11.4 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
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/shirou/gopsutil/v3/mem"
"github.com/shirou/gopsutil/v3/process"
_ "github.com/shirou/gopsutil/v3/process"
"io/ioutil"
"math"
"net/http"
"os"
"os/exec"
"regexp"
"runtime"
"strings"
)
func main() {
port := ":8080"
gin.SetMode(gin.ReleaseMode)
router := gin.Default()
router.Use(func(context *gin.Context) {
context.Header("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Headers", "*")
context.Header("Access-Control-Allow-Methods", "*")
if context.Request.Method == "OPTIONS" {
context.Status(200)
context.Abort()
}
})
installSpeedCLI()
router.POST("/exportAuthToken", exportNodeType)
router.POST("/getBalance", getBalance)
router.POST("/pfb", sendPfb)
router.GET("/getNodeInfo", getNodeInfo)
router.GET("/getSamplerStats", getSamplerStats)
router.GET("/location", location)
router.GET("/speedInfo", runSpeedCLI)
router.GET("/getRamCpuMemUsage", getRamCpuMemUsage)
router.GET("/getCelestiaCpuUsage", getCelestiaCpuUsage)
fmt.Println("server is running at", port)
err := router.Run(port)
if err != nil {
fmt.Println(err)
panic(err)
return
}
}
type Node struct {
NodeType string
}
type Response struct {
JSONRPC string `json:"jsonrpc"`
Result Result `json:"result"`
ID int `json:"id"`
}
type Result struct {
HeadOfSampledChain int `json:"head_of_sampled_chain"`
HeadOfCatchup int `json:"head_of_catchup"`
NetworkHeadHeight int `json:"network_head_height"`
Concurrency int `json:"concurrency"`
CatchUpDone bool `json:"catch_up_done"`
IsRunning bool `json:"is_running"`
}
func exportNodeType(c *gin.Context) {
body := Node{}
data, err := c.GetRawData()
if err != nil {
c.AbortWithStatusJSON(406, "Input format is wrong")
return
}
if err := json.Unmarshal(data, &body); err != nil {
c.AbortWithStatusJSON(400, "Can't match with the struct")
return
}
fmt.Println(body.NodeType)
cmd := exec.Command("celestia", body.NodeType, "auth", "admin", "--p2p.network", "blockspacerace")
output, err := cmd.Output()
if err != nil {
fmt.Println("Error:", err)
return
}
// Parse the output to retrieve the token
token := strings.TrimSpace(string(output))
// Set the environment variable
err = os.Setenv("CELESTIA_NODE_AUTH_TOKEN", token)
if err != nil {
fmt.Println("Error setting environment variable:", err)
return
}
fmt.Println(token)
c.JSON(200, gin.H{
"Token": token,
})
}
func getSamplerStats(c *gin.Context) {
cmd := exec.Command("celestia", "rpc", "das", "SamplingStats")
cmd.Env = append(os.Environ(), "HOME=/root")
output, err := cmd.Output()
if err != nil {
c.AbortWithStatusJSON(400, "Something went wrong with linux command")
fmt.Println("Error:", err)
return
}
fmt.Println(string(output))
var resp Response
err = json.Unmarshal([]byte(output), &resp)
if err != nil {
c.AbortWithStatusJSON(400, "Something went wrong with unmarshalling")
fmt.Println("Error:", err)
return
}
c.JSON(200, gin.H{
"jsonrpc": resp.JSONRPC,
"id": resp.ID,
"result": gin.H{
"head_of_sampled_chain": resp.Result.HeadOfSampledChain,
"head_of_catchup": resp.Result.HeadOfCatchup,
"network_head_height": resp.Result.NetworkHeadHeight,
"concurrency": resp.Result.Concurrency,
"catch_up_done": resp.Result.CatchUpDone,
"is_running": resp.Result.IsRunning,
},
})
}
type MyResponse struct {
JSONRPC string `json:"jsonrpc"`
Result MyResult `json:"result"`
ID int `json:"id"`
}
type MyResult struct {
Type int `json:"type"`
APIVersion string `json:"api_version"`
}
func getNodeInfo(c *gin.Context) {
cmd := exec.Command("celestia", "rpc", "das", "SamplingStats")
output, err := cmd.Output()
if err != nil {
c.AbortWithStatusJSON(400, "Something went wrong with linux command")
fmt.Println("Error:", err)
return
}
fmt.Println(string(output))
var resp MyResponse
err = json.Unmarshal([]byte(output), &resp)
if err != nil {
c.AbortWithStatusJSON(400, "Something went wrong with unmarshalling")
fmt.Println("Error:", err)
return
}
c.JSON(200, gin.H{
"jsonrpc": resp.JSONRPC,
"id": resp.ID,
"result": gin.H{"type": resp.Result.Type, "api_version": resp.Result.APIVersion},
})
}
func installSpeedCLI() {
packageName := "speedtest-cli"
// Check if the package is already installed
checkCmd := exec.Command("dpkg", "-s", packageName)
checkOutput, _ := checkCmd.CombinedOutput()
if strings.Contains(string(checkOutput), "Status: install ok installed") {
fmt.Printf("Package '%s' is already installed.\n", packageName)
return
}
// Install the package
installCmd := exec.Command("apt", "install", packageName)
output, err := installCmd.CombinedOutput()
if err != nil {
fmt.Println("Error:", err)
fmt.Println("Command output:", string(output))
return
}
fmt.Println(string(output))
}
type LocationInfo struct {
Status string `json:"status"`
Country string `json:"country"`
CountryCode string `json:"countryCode"`
Region string `json:"region"`
RegionName string `json:"regionName"`
City string `json:"city"`
Zip string `json:"zip"`
Latitude float64 `json:"lat"`
Longitude float64 `json:"lon"`
Timezone string `json:"timezone"`
ISP string `json:"isp"`
Organization string `json:"org"`
AS string `json:"as"`
Query string `json:"query"`
}
func location(c *gin.Context) {
cmd := exec.Command("curl", "-s", "http://ip-api.com/json")
output, err := cmd.Output()
if err != nil {
fmt.Println("Error:", err)
return
}
var locationInfo LocationInfo
err = json.Unmarshal([]byte(string(output)), &locationInfo)
if err != nil {
fmt.Println("Error:", err)
c.AbortWithStatusJSON(400, "Something went wrong with unmarshalling")
return
}
c.JSON(200, gin.H{
"Status": locationInfo.Status,
"Country": locationInfo.Country,
"Country Code": locationInfo.CountryCode,
"Region": locationInfo.Region,
"Region Name": locationInfo.RegionName,
"City": locationInfo.City,
"ZIP": locationInfo.Zip,
"Latitude": locationInfo.Latitude,
"Longitude": locationInfo.Longitude,
"Timezone": locationInfo.Timezone,
"ISP": locationInfo.ISP,
"Organization": locationInfo.Organization,
"AS": locationInfo.AS,
"Query": locationInfo.Query,
})
}
func extractLocation(output string) (city, region, country string) {
outputLines := strings.Split(output, "\n")
if len(outputLines) >= 3 {
city = strings.Trim(outputLines[0], `"`)
region = strings.Trim(outputLines[1], `"`)
country = strings.Trim(outputLines[2], `"`)
}
return city, region, country
}
func runSpeedCLI(c *gin.Context) {
cmd := exec.Command("speedtest-cli")
output, err := cmd.CombinedOutput()
if err != nil {
c.AbortWithStatusJSON(400, "Something went wrong with linux command")
return
}
// Extract upload and download speed values
reDownload := regexp.MustCompile(`Download:\s+(\d+\.\d+)\s+([KM]bit/s)`)
reUpload := regexp.MustCompile(`Upload:\s+(\d+\.\d+)\s+([KM]bit/s)`)
downloadSpeed := reDownload.FindStringSubmatch(string(output))
uploadSpeed := reUpload.FindStringSubmatch(string(output))
var uploadSpeedVal string
var downloadSpeedVal string
if len(downloadSpeed) == 3 {
downloadValue := downloadSpeed[1]
downloadUnit := downloadSpeed[2]
downloadSpeedVal = downloadValue + downloadUnit
} else {
fmt.Println("Failed to extract download speed.")
}
if len(uploadSpeed) == 3 {
uploadValue := uploadSpeed[1]
uploadUnit := uploadSpeed[2]
uploadSpeedVal = uploadValue + uploadUnit
fmt.Println("Upload Speed:", uploadValue, uploadUnit)
} else {
fmt.Println("Failed to extract upload speed.")
}
c.JSON(200, gin.H{
"download": downloadSpeedVal,
"upload": uploadSpeedVal,
})
}
func getRamCpuMemUsage(c *gin.Context) {
v, err := mem.VirtualMemory()
if err != nil {
fmt.Println("err ram usage", err)
}
totalRAM := math.Round(float64(v.Total)/(1024*1024*1024)*100) / 100
usedRAM := math.Round(float64(v.Used)/(1024*1024*1024)*100) / 100
totalCPU := runtime.NumCPU()
c.JSON(200, gin.H{
"totalRam": totalRAM,
"usedRam": usedRAM,
"totalCPU": totalCPU,
})
}
func getCelestiaCpuUsage(c *gin.Context) {
processes, err := process.Processes()
if err != nil {
fmt.Println("err Cpu Celestia", err)
return
}
for _, proc := range processes {
name, err := proc.Name()
if err != nil {
continue
}
if name == "celestia" {
cpuPercent, err := proc.CPUPercent()
if err != nil {
fmt.Println("err Cpu Celestia", err)
}
c.JSON(200, gin.H{
"cpuPercent": math.Round(cpuPercent) / 100,
})
break
}
}
}
type getBalanceSt struct {
IpAddress string
}
type BalanceResponse struct {
Denom string
Amount string
}
func getBalance(c *gin.Context) {
bodyIp := getBalanceSt{}
rawInput, err := c.GetRawData()
if err != nil {
c.AbortWithStatusJSON(406, "Invalid input format")
return
}
if err := json.Unmarshal(rawInput, &bodyIp); err != nil {
c.AbortWithStatusJSON(400, "Struct mismatch")
return
}
url := fmt.Sprintf("http://%s:26659/balance", bodyIp.IpAddress)
resp, err := http.Get(url)
if err != nil {
fmt.Println("Error making the request:", err)
return
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading the response:", err)
return
}
var balanceResponse BalanceResponse
err = json.Unmarshal(body, &balanceResponse)
if err != nil {
fmt.Println("Error unmarshalling JSON:", err)
return
}
c.JSON(200, gin.H{
"denom": balanceResponse.Denom,
"amount": balanceResponse.Amount,
})
}
type PFB struct {
NamespaceId string `json:"namespace_id"`
Data string `json:"data"`
GasLimit int `json:"gas_limit"`
Fee int `json:"fee"`
IpAddress string `json:"ip_address"`
}
type ResponseData struct {
Height int64 `json:"height"`
TxHash string `json:"txhash"`
Data string `json:"data"`
RawLog string `json:"raw_log"`
GasWanted int64 `json:"gas_wanted"`
GasUsed int64 `json:"gas_used"`
Events []struct {
Type string `json:"type"`
Attributes []struct {
Key string `json:"key"`
Value string `json:"value"`
Index bool `json:"index"`
} `json:"attributes"`
} `json:"events"`
}
func sendPfb(c *gin.Context) {
body := PFB{}
rawInput, err := c.GetRawData()
if err != nil {
c.AbortWithStatusJSON(406, "Invalid input format")
return
}
if err := json.Unmarshal(rawInput, &body); err != nil {
c.AbortWithStatusJSON(400, "Struct mismatch")
return
}
pfb := PFB{
NamespaceId: body.NamespaceId,
Data: body.Data,
GasLimit: body.GasLimit,
Fee: body.Fee,
}
jsonData, err := json.Marshal(pfb)
if err != nil {
fmt.Println("Error encoding JSON:", err)
return
}
url := fmt.Sprintf("http://%s:26659/submit_pfb", body.IpAddress)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
fmt.Println("Error making the request:", err)
c.AbortWithStatusJSON(400, "Make sure you have enough Tia use our tool to check it out")
return
}
defer resp.Body.Close()
bodyHead, err := ioutil.ReadAll(resp.Body)
responseData := ResponseData{}
err = json.Unmarshal(bodyHead, &responseData)
if err != nil {
fmt.Println("Error parsing the JSON response:", err)
c.AbortWithStatusJSON(400, "Make sure you have enough Tia use our tool to check it out")
return
}
c.JSON(200, responseData)
}