zkt24/z2/backend/rpc/server.go

121 lines
2.5 KiB
Go
Raw Permalink Normal View History

2024-04-25 11:51:47 +00:00
package rpc
import (
"fmt"
"net/http"
"sync"
"thesis/core"
"thesis/db"
"thesis/ent"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
)
type RegistrationInfo struct {
PublicKey string `json:"pk" binding:"required"`
Owner string `json:"owner" binding:"required"`
}
type TransactionSubmission struct {
Signer string `json:"signer" binding:"required"`
Comment string `json:"comment" binding:"required"`
Commitment string `json:"commit" binding:"required"`
Signature string `json:"sig" binding:"required"`
}
func Serve(wg *sync.WaitGroup, client *ent.Client) {
r := gin.Default()
// r.Use(cors.New(cors.Config{
// AllowOrigins: []string{"http://localhost:5173/"},
// AllowMethods: []string{"POST", "GET", "OPTIONS"},
// AllowHeaders: []string{"Origin", "Access-Control-Allow-Origin", "Content-Type"},
// ExposeHeaders: []string{"Content-Length"},
// }))
r.Use(cors.Default())
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.GET("/stats", func(c *gin.Context) {
txCount := db.GetTxCount(client)
lastBlock := db.GetLatestBlock(client)
if lastBlock != nil {
c.JSON(200, gin.H{
"status": "ok",
"data": gin.H{
"txCount": txCount,
"latestBlock": lastBlock.Hash,
"peers": 2,
},
})
return
}
c.JSON(200, gin.H{
"status": "ok",
"data": gin.H{
"txCount": 0,
"latestBlock": 0x000,
"peers": 2,
},
})
})
r.POST("/submitTx", func(c *gin.Context) {
var data TransactionSubmission
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad",
"details": "malformed data provided",
})
return
}
fmt.Println(data)
key := db.GetKeyFromHex(client, data.Signer)
err := core.AddNewTx(client, []byte(data.Comment), data.Commitment, data.Signature, key)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad",
"details": "can't process tx",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.POST("/register", func(c *gin.Context) {
var data RegistrationInfo
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad",
"details": "invalid data provided",
})
return
}
err := db.AddKey(client, data.PublicKey, data.Owner)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"status": "bad",
"details": "key already registered",
})
return
}
c.JSON(http.StatusOK, gin.H{
"status": "ok",
})
})
r.Run()
wg.Done()
}