Skip to content

Commit

Permalink
slight refactor / cleanup -- need to fix verify
Browse files Browse the repository at this point in the history
  • Loading branch information
rrrliu committed Jan 25, 2025
1 parent 13f8c38 commit 4877050
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 132 deletions.
117 changes: 49 additions & 68 deletions go/cmd/server/main.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// Start of Selection
package main

import (
Expand Down Expand Up @@ -34,31 +33,9 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
return
}

newCount, err := rdb.Incr(ctx, "visitorCount").Result()
if err != nil {
log.Printf("Error incrementing visitorCount in Redis: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
jsonData := fmt.Sprintf(`{
"message": {"string": "Welcome to PARCNET, visitor #%d"},
"visitorCount": {"int": %d}
}`, newCount, newCount)

var entries pod.PodEntries
if err := json.Unmarshal([]byte(jsonData), &entries); err != nil {
http.Error(w, "Error parsing POD entries: "+err.Error(), http.StatusInternalServerError)
return
}

startTime := time.Now()
podInstance, err := pod.CreateGoPodHex(privateKey, entries)
elapsed := time.Since(startTime)
log.Printf("[%s /] pod.CreatePod: %s", r.Method, elapsed)

podInstance, err := createVisitorPOD(r.Method, "/")
if err != nil {
log.Printf("[%s /] pod.CreatePod: %s", r.Method, err)
http.Error(w, "Error creating POD: "+err.Error(), http.StatusInternalServerError)
// Error already handled inside createVisitorPOD
return
}

Expand All @@ -73,7 +50,7 @@ func handleRoot(w http.ResponseWriter, r *http.Request) {
}

type signRequest struct {
Entries map[string]interface{} `json:"entries"`
Entries pod.PodEntries `json:"entries"`
}

func handleSign(w http.ResponseWriter, r *http.Request) {
Expand All @@ -89,7 +66,7 @@ func handleSign(w http.ResponseWriter, r *http.Request) {
}

startTime := time.Now()
_, jsonPod, err := pod.CreatePod(privateKey, req.Entries)
podInstance, err := pod.CreatePod(privateKey, req.Entries)
elapsed := time.Since(startTime)
log.Printf("[%s /sign] pod.CreatePod: %s", r.Method, elapsed)

Expand All @@ -100,7 +77,12 @@ func handleSign(w http.ResponseWriter, r *http.Request) {

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(jsonPod))
jsonPod, err := json.Marshal(podInstance)
if err != nil {
http.Error(w, "Error marshalling POD: "+err.Error(), http.StatusInternalServerError)
return
}
_, _ = w.Write(jsonPod)
}

type verifyResponse struct {
Expand Down Expand Up @@ -154,7 +136,7 @@ func handleZupass(w http.ResponseWriter, r *http.Request) {
}

startTime := time.Now()
podInstance, _, err := pod.CreatePod(privateKey, req.Entries)
podInstance, err := pod.CreatePod(privateKey, req.Entries)
elapsed := time.Since(startTime)
log.Printf("[%s /zupass/add] pod.CreatePod: %s", r.Method, elapsed)

Expand Down Expand Up @@ -185,32 +167,9 @@ func handleZupass(w http.ResponseWriter, r *http.Request) {
json.NewEncoder(w).Encode(response)

case http.MethodGet:
newCount, err := rdb.Incr(ctx, "visitorCount").Result()
if err != nil {
log.Printf("Error incrementing visitorCount in Redis: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

jsonData := fmt.Sprintf(`{
"message": {"string": "Welcome to PARCNET, visitor #%d"},
"visitorCount": {"int": %d}
}`, newCount, newCount)

var entries pod.PodEntries
if err := json.Unmarshal([]byte(jsonData), &entries); err != nil {
http.Error(w, "Error parsing POD entries: "+err.Error(), http.StatusInternalServerError)
return
}

startTime := time.Now()
podInstance, err := pod.CreateGoPodHex(privateKey, entries)
elapsed := time.Since(startTime)
log.Printf("[%s /zupass] pod.CreatePod: %s", r.Method, elapsed)

podInstance, err := createVisitorPOD(r.Method, "/zupass")
if err != nil {
log.Printf("[%s /zupass] pod.CreatePod: %s", r.Method, err)
http.Error(w, "Error creating POD: "+err.Error(), http.StatusInternalServerError)
// Error already handled inside createVisitorPOD
return
}

Expand All @@ -235,6 +194,39 @@ func handleZupass(w http.ResponseWriter, r *http.Request) {
}
}

func createVisitorPOD(method, endpoint string) (*pod.Pod, error) {
newCount, err := rdb.Incr(ctx, "visitorCount").Result()
if err != nil {
log.Printf("Error incrementing visitorCount in Redis: %v", err)
http.Error(nil, "Internal Server Error", http.StatusInternalServerError)
return nil, err
}

jsonData := fmt.Sprintf(`{
"message": {"string": "Welcome to PARCNET, visitor #%d"},
"visitorCount": {"int": %d}
}`, newCount, newCount)

var entries pod.PodEntries
if err := json.Unmarshal([]byte(jsonData), &entries); err != nil {
http.Error(nil, "Error parsing POD entries: "+err.Error(), http.StatusInternalServerError)
return nil, err
}

startTime := time.Now()
podInstance, err := pod.CreatePod(privateKey, entries)
elapsed := time.Since(startTime)
log.Printf("[%s %s] pod.CreatePod: %s", method, endpoint, elapsed)

if err != nil {
log.Printf("[%s %s] pod.CreatePod: %s", method, endpoint, err)
http.Error(nil, "Error creating POD: "+err.Error(), http.StatusInternalServerError)
return nil, err
}

return podInstance, nil
}

func initRedis() {
redisURL := os.Getenv("REDIS_URL")

Expand Down Expand Up @@ -262,28 +254,17 @@ func main() {
if privateKey == "" {
log.Fatal("Missing PRIVATE_KEY environment variable.")
}

if err := pod.Init(); err != nil {
log.Fatal("Failed to initialize pod: ", err)
}
log.Println("Loaded PRIVATE_KEY...")

initRedis()

// Test connection quickly (optional, but good practice)
if _, err := rdb.Ping(ctx).Result(); err != nil {
log.Fatalf("Could not connect to Redis: %v", err)
}

log.Println("Loaded PRIVATE_KEY...")
log.Println("Initialized pod service...")
log.Println("Connected to Redis...")
log.Println("Starting server on port 8080")

http.HandleFunc("/", handleRoot)
http.HandleFunc("/sign", handleSign)
http.HandleFunc("/verify", handleVerify)
http.HandleFunc("/zupass", handleZupass)

log.Println("Starting server on port 8080")

if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal("ListenAndServe Error: ", err)
}
Expand Down
19 changes: 3 additions & 16 deletions go/pod/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,26 +7,13 @@ import (
"github.com/iden3/go-iden3-crypto/v2/babyjub"
)

// CreatePod calls "create" subcommand in Rust
func CreatePod(privateKey string, entries map[string]interface{}) (*Pod, string, error) {
if err := validatePrivateKeyHex(privateKey); err != nil {
return nil, "", fmt.Errorf("invalid private key: %w", err)
}
req := podCommandRequest{
Cmd: "create",
PrivateKey: privateKey,
Entries: entries,
}
return dispatchRustCommand(req)
}

func CreateGoPodHex(privateKeyHex string, entries PodEntries) (*Pod, error) {
func CreatePod(privateKeyHex string, entries PodEntries) (*Pod, error) {
var privateKey babyjub.PrivateKey
hex.Decode(privateKey[:], []byte(privateKeyHex))
return CreateGoPod(privateKey, entries)
return signPod(privateKey, entries)
}

func CreateGoPod(privateKey babyjub.PrivateKey, entries PodEntries) (*Pod, error) {
func signPod(privateKey babyjub.PrivateKey, entries PodEntries) (*Pod, error) {
contentID, err := computeContentID(entries)
if err != nil {
return nil, fmt.Errorf("failed computing content ID: %w", err)
Expand Down
49 changes: 1 addition & 48 deletions go/pod/pod_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,6 @@ import (
"github.com/iden3/go-iden3-crypto/v2/poseidon"
)

// func TestCreatePod(t *testing.T) {
// p, j, err := CreatePod(
// "0001020304050607080900010203040506070809000102030405060708090001",
// map[string]interface{}{
// "hello": map[string]interface{}{"string": "world"},
// "year": map[string]interface{}{"int": 2000},
// "created_by": map[string]interface{}{"string": "Golang"},
// "is_valid": map[string]interface{}{"boolean": true},
// "explicit_string": map[string]interface{}{"string": "explicit"},
// },
// )
// if err != nil {
// t.Fatalf("CreatePod failed: %v", err)
// }
// if p == nil {
// t.Fatalf("Pod is nil")
// }
// if len(j) == 0 {
// t.Fatalf("JSONPOD is empty")
// }
// fmt.Println("JSONPOD", j)

// expectedJSON := "{\"entries\":{\"created_by\":{\"string\":\"Golang\"},\"explicit_string\":{\"string\":\"explicit\"},\"hello\":{\"string\":\"world\"},\"is_valid\":{\"boolean\":true},\"year\":{\"int\":2000}},\"signature\":\"t7+VVUbi7qqSc0bzNemuD8MzLPPlSt+k29H/qVbYYBRXg8bJk4SAWMLFeA2UlcRJWH4N34Ovxs3oLp0OmzVTAg\",\"signerPublicKey\":\"xDP3ppa3qjpSJO+zmTuvDM2eku7O4MKaP2yCCKnoHZ4\"}"
// if j != expectedJSON {
// t.Fatalf("JSONPOD does not match expected.\nExpected: %s\nGot: %s", expectedJSON, j)
// }
// }

// func TestVerify(t *testing.T) {
// p, _, err := CreatePod(
// "0001020304050607080900010203040506070809000102030405060708090001",
Expand Down Expand Up @@ -125,32 +97,13 @@ func TestCreateGoPod(t *testing.T) {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8,
9, 0, 1,
}
startTime := time.Now()
Init()
elapsed := time.Since(startTime)
fmt.Println()
fmt.Println("================================================")
fmt.Println()
fmt.Println("INIT TIME", elapsed)

startTime = time.Now()
_, _, err := CreatePod("0001020304050607080900010203040506070809000102030405060708090001", map[string]interface{}{"A": map[string]interface{}{"int": 123}, "B": map[string]interface{}{"int": 321}, "G": map[string]interface{}{"int": 7}, "D": map[string]interface{}{"string": "foobar"}, "C": map[string]interface{}{"boolean": false}})
elapsed = time.Since(startTime)
fmt.Println("RUST GO CREATE TIME", elapsed)
if err != nil {
t.Fatalf("CreatePod failed: %v", err)
}

startTime = time.Now()
pod, err := CreateGoPod(privKey, PodEntries{
pod, err := signPod(privKey, PodEntries{
"A": PodValue{kind: "int", intVal: 123},
"B": PodValue{kind: "int", intVal: 321},
"G": PodValue{kind: "int", intVal: -7},
"D": PodValue{kind: "string", strVal: "foobar"},
"C": PodValue{kind: "boolean", boolVal: false},
})
elapsed = time.Since(startTime)
fmt.Println("NATIVE GO CREATE TIME", elapsed)
if err != nil {
t.Fatalf("CreateGoPod failed: %v", err)
}
Expand Down

0 comments on commit 4877050

Please sign in to comment.