Repository navigation
Expand file tree
/
Copy pathhttp.go
More file actions
179 lines (158 loc) · 5.27 KB
/
Copy pathhttp.go
File metadata and controls
179 lines (158 loc) · 5.27 KB
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
package ccq
import (
"crypto/ecdsa"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"sort"
"time"
"github.com/certusone/wormhole/node/pkg/common"
gossipv1 "github.com/certusone/wormhole/node/pkg/proto/gossip/v1"
"github.com/certusone/wormhole/node/pkg/query"
"github.com/gorilla/mux"
pubsub "github.com/libp2p/go-libp2p-pubsub"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
)
type queryRequest struct {
Bytes string `json:"bytes"`
Signature string `json:"signature"`
}
type queryResponse struct {
Bytes string `json:"bytes"`
Signatures []string `json:"signatures"`
}
type httpServer struct {
topic *pubsub.Topic
logger *zap.Logger
env common.Environment
permissions Permissions
signerKey *ecdsa.PrivateKey
pendingResponses *PendingResponses
}
func (s *httpServer) handleQuery(w http.ResponseWriter, r *http.Request) {
// Set CORS headers for all requests.
w.Header().Set("Access-Control-Allow-Origin", "*")
// Set CORS headers for the preflight request
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "PUT, POST")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, X-Api-Key")
w.Header().Set("Access-Control-Max-Age", "3600")
w.WriteHeader(http.StatusNoContent)
return
}
var q queryRequest
err := json.NewDecoder(r.Body).Decode(&q)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// There should be one and only one API key in the header.
apiKey, exists := r.Header["X-Api-Key"]
if !exists || len(apiKey) != 1 {
s.logger.Debug("received a request without an api key", zap.Stringer("url", r.URL), zap.Error(err))
http.Error(w, "api key is missing", http.StatusUnauthorized)
return
}
queryRequestBytes, err := hex.DecodeString(q.Bytes)
if err != nil {
s.logger.Debug("failed to decode request bytes", zap.Error(err))
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
signature, err := hex.DecodeString(q.Signature)
if err != nil {
s.logger.Debug("failed to decode signature bytes", zap.Error(err))
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
signedQueryRequest := &gossipv1.SignedQueryRequest{
QueryRequest: queryRequestBytes,
Signature: signature,
}
if status, err := validateRequest(s.logger, s.env, s.permissions, s.signerKey, apiKey[0], signedQueryRequest); err != nil {
// Don't need to log here because the details were logged in the function.
http.Error(w, err.Error(), status)
return
}
m := gossipv1.GossipMessage{
Message: &gossipv1.GossipMessage_SignedQueryRequest{
SignedQueryRequest: signedQueryRequest,
},
}
b, err := proto.Marshal(&m)
if err != nil {
s.logger.Error("failed to marshal gossip message", zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
pendingResponse := NewPendingResponse(signedQueryRequest)
added := s.pendingResponses.Add(pendingResponse)
if !added {
http.Error(w, "Duplicate request", http.StatusBadRequest)
return
}
err = s.topic.Publish(r.Context(), b)
if err != nil {
s.logger.Error("failed to publish gossip message", zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
s.pendingResponses.Remove(pendingResponse)
return
}
// Wait for the response or timeout
select {
case <-time.After(query.RequestTimeout + 5*time.Second):
http.Error(w, "Timed out waiting for response", http.StatusGatewayTimeout)
case res := <-pendingResponse.ch:
resBytes, err := res.Response.Marshal()
if err != nil {
s.logger.Error("failed to marshal response", zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
break
}
// Signature indices must be ascending for on-chain verification
sort.Slice(res.Signatures, func(i, j int) bool {
return res.Signatures[i].Index < res.Signatures[j].Index
})
signatures := make([]string, 0, len(res.Signatures))
for _, s := range res.Signatures {
// ECDSA signature + a byte for the index of the guardian in the guardian set
signature := fmt.Sprintf("%s%02x", s.Signature, uint8(s.Index))
signatures = append(signatures, signature)
}
w.Header().Add("Content-Type", "application/json")
err = json.NewEncoder(w).Encode(&queryResponse{
Signatures: signatures,
Bytes: hex.EncodeToString(resBytes),
})
if err != nil {
s.logger.Error("failed to encode response", zap.Error(err))
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
s.pendingResponses.Remove(pendingResponse)
}
func (s *httpServer) handleHealth(w http.ResponseWriter, r *http.Request) {
s.logger.Debug("health check")
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "ok")
}
func NewHTTPServer(addr string, t *pubsub.Topic, permissions Permissions, signerKey *ecdsa.PrivateKey, p *PendingResponses, logger *zap.Logger, env common.Environment) *http.Server {
s := &httpServer{
topic: t,
permissions: permissions,
signerKey: signerKey,
pendingResponses: p,
logger: logger,
env: env,
}
r := mux.NewRouter()
r.HandleFunc("/v1/query", s.handleQuery).Methods("PUT", "POST", "OPTIONS")
r.HandleFunc("/v1/health", s.handleHealth).Methods("GET")
return &http.Server{
Addr: addr,
Handler: r,
ReadHeaderTimeout: 5 * time.Second,
}
}