go-dvote/net/net.go
net/net.goRaw
1package net
2
3import (
4 "encoding/json"
5 "fmt"
6 "net/http"
7 "io"
8 "github.com/vocdoni/dvote-relay/batch"
9 "github.com/vocdoni/dvote-relay/types"
10 "github.com/vocdoni/dvote-relay/data"
11)
12
13
14
15func parse(rw http.ResponseWriter, request *http.Request) {
16 decoder := json.NewDecoder(request.Body)
17
18 var e types.Envelope
19 var b types.Ballot
20
21 err := decoder.Decode(&e)
22 if err != nil {
23 panic(err)
24 }
25
26 err = json.Unmarshal(e.Ballot, &b)
27 if err != nil {
28 panic(err)
29 }
30
31
32 //check PoW
33 //check key
34 //decrypt
35 //check franchise
36 //construct packet
37
38 //this should should be randomized, or actually taken from input
39 //b.PID = "1"
40 //b.Nullifier = []byte{1,2,3}
41 //b.Vote = []byte{4,5,6}
42 //b.Franchise = []byte{7,8,9}
43
44 err = batch.Add(b)
45 if err != nil {
46 panic(err)
47 }
48
49 j, err := json.Marshal(e)
50 if err != nil {
51 panic(err)
52 }
53 io.WriteString(rw, string(j))
54}
55
56func Sub(topic string) error {
57 subscription := data.PsSubscribe(topic)
58 fmt.Println("Subscribed > " + topic)
59 for {
60 msg, err := subscription.Next()
61 if err != nil {
62 return err
63 }
64
65 payload := msg.Data()
66
67 var e types.Envelope
68 var b types.Ballot
69
70 err = json.Unmarshal(payload, &e)
71 if err != nil {
72 return err
73 }
74
75 err = json.Unmarshal(e.Ballot, &b)
76 if err != nil {
77 return err
78 }
79
80 err = batch.Add(b)
81 if err != nil {
82 return err
83 }
84
85 fmt.Println("Got > " + string(payload))
86 }
87}
88
89func Listen(port string) {
90 http.HandleFunc("/submit", parse)
91 //add waitgroup
92 func() {
93 fmt.Println("serving on " + port)
94 err := http.ListenAndServe(":" + port, nil)
95 if err != nil {
96 panic("ListenAndServe: " + err.Error())
97 }
98 }()
99}