-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrpc.go
381 lines (323 loc) · 10.7 KB
/
rpc.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
package client
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/mit-dci/go-bverify/logging"
"github.com/mit-dci/go-bverify/wire"
"github.com/gorilla/mux"
)
// RpcServer runs a simple JSON based API for clients to start and maintain
// logs using the client
type RpcServer struct {
cli *Client
}
// NewRpcServer creates a new RPC server
func NewRpcServer(c *Client) *RpcServer {
return &RpcServer{cli: c}
}
type StartLogParameters struct {
InitialStatement string // The statement (in clear text) you wish to start the log with
}
type StartLogReply struct {
LogID string // The Log ID (hex encoded bytes)
}
// StartLog is an RPC method to start a new log
func (s *RpcServer) StartLog(w http.ResponseWriter, r *http.Request) {
// Decode the passed in parameters
decoder := json.NewDecoder(r.Body)
var params StartLogParameters
err := decoder.Decode(¶ms)
if err != nil {
s.writeError(w, fmt.Errorf("Error decoding json: %s", err.Error()))
return
}
// Start the log
logId, err := s.cli.StartLogText(params.InitialStatement)
if err != nil {
s.writeError(w, fmt.Errorf("Error decoding json: %s", err.Error()))
return
}
// Return the LogID as reply to the caller
reply := StartLogReply{}
reply.LogID = hex.EncodeToString(logId[:])
json.NewEncoder(w).Encode(reply)
}
type AppendLogParameters struct {
LogID string // The ID of the log to append to (in hexadecimal format)
Index uint64 // The 0-based index of the statement that is to be written
Statement string // The statement (in clear text) to append to the log
}
type AppendLogReply struct {
Success bool
}
// AppendLog is an RPC method to append to an existing log
func (s *RpcServer) AppendLog(w http.ResponseWriter, r *http.Request) {
// Decode the passed in parameters
decoder := json.NewDecoder(r.Body)
var params AppendLogParameters
err := decoder.Decode(¶ms)
if err != nil {
s.writeError(w, fmt.Errorf("Error decoding json: %s", err.Error()))
return
}
// Decode the passed in LogID
hexLogID, err := hex.DecodeString(params.LogID)
if err != nil {
s.writeError(w, fmt.Errorf("Error decoding hex: %s", err.Error()))
return
}
logId32 := [32]byte{}
copy(logId32[:], hexLogID)
// Append to the log
err = s.cli.AppendLogText(params.Index, logId32, params.Statement)
if err != nil {
s.writeError(w, fmt.Errorf("Error decoding json: %s", err.Error()))
return
}
// Generate a reply and send it back to the caller
reply := AppendLogReply{}
reply.Success = true
json.NewEncoder(w).Encode(reply)
}
type ErrorResponse struct {
Error bool
ErrorDetails string
}
func (s *RpcServer) writeError(w http.ResponseWriter, err error) {
resp := ErrorResponse{Error: true, ErrorDetails: err.Error()}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
json.NewEncoder(w).Encode(resp)
}
type StatusReply struct {
BlockHeight int32 `json:"blockHeight"`
Synced bool `json:"synced"`
}
// Status is an RPC method to fetch the status of the server
func (s *RpcServer) Status(w http.ResponseWriter, r *http.Request) {
reply := StatusReply{}
reply.BlockHeight = s.cli.SPVHeight()
reply.Synced = s.cli.SPVSynced()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(reply)
}
// AddForeignLog is an RPC method to instruct this client to keep updated
// proofs for the given log statement
func (s *RpcServer) AddForeignLog(w http.ResponseWriter, r *http.Request) {
// The passed in bytes should be deserializable as a ForeignStatement
b, err := ioutil.ReadAll(r.Body)
if err != nil {
s.writeError(w, fmt.Errorf("Could not read proof from request body: %s", err.Error()))
return
}
dec, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
s.writeError(w, fmt.Errorf("Request body is not valid base64: %s", err.Error()))
return
}
fs := wire.ForeignStatementFromBytes(dec)
err = s.cli.AddForeignLog(fs)
if err != nil {
s.writeError(w, fmt.Errorf("Error adding foreign log: %s", err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(true)
}
type VerificationResult struct {
Statement string
Valid bool
Error string
PubKey string
BlockHash string
TxHash string
BlockTimestamp int64
}
func (s *RpcServer) VerifyOnce(w http.ResponseWriter, r *http.Request) {
verify := func() VerificationResult {
v := VerificationResult{}
// The passed in bytes should be deserializable as a ForeignStatement
b, err := ioutil.ReadAll(r.Body)
if err != nil {
v.Valid = false
v.Error = fmt.Sprintf("Could not read proof from request body: %s", err.Error())
return v
}
dec, err := base64.StdEncoding.DecodeString(string(b))
if err != nil {
v.Valid = false
v.Error = fmt.Sprintf("Request body is not valid base64: %s", err.Error())
return v
}
fs := wire.ForeignStatementFromBytes(dec)
logId, hash, err := s.cli.GetForeignLogIDAndHash(fs)
if err != nil {
v.Valid = false
v.Error = fmt.Sprintf("Could not read foreign statement: %s", err.Error())
return v
}
// TODO: Get proof from server if it's nil?
val, err := fs.Proof.Get(logId[:])
if err != nil || !bytes.Equal(val, hash[:]) {
v.Valid = false
v.Error = fmt.Sprintf("Provided proof does not contain correct value for the provided log: %v - [%x vs %x]", err, val, hash)
return v
}
// Calculate the commitment from the partial tree we got from the
// server and check if it is a known commitment
rootHash := fs.Proof.Commitment()
c, err := s.cli.getCommitment(rootHash)
if err != nil {
v.Valid = false
v.Error = fmt.Sprintf("Could not get commitment from the given proof: %s", err.Error())
return v
}
block, err := s.cli.GetBlockHeaderByHash(c.IncludedInBlock)
if err != nil {
v.Valid = false
v.Error = "Could not fetch block details for this log's last committed statement"
return v
}
v.Valid = true
v.BlockHash = c.IncludedInBlock.String()
v.PubKey = hex.EncodeToString(fs.PubKey[:])
v.Statement = fs.StatementPreimage
v.TxHash = c.TxHash.String()
v.BlockTimestamp = block.Timestamp.Unix()
return v
}
result := verify()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(result)
}
type LogInfo struct {
Foreign bool
LogID string
LastStatement string
LastIndex int64
LastCommitment string
LastCommitmentProof string
LastCommitmentBlock string
LastCommitmentTimestamp int64
Valid bool
Error string
}
// Logs will return a list of known logs and their last statements and proofs
func (s *RpcServer) Logs(w http.ResponseWriter, r *http.Request) {
logIds, err := s.cli.GetAllLogIDs()
if err != nil {
s.writeError(w, fmt.Errorf("Unable to fetch logs: %s", err.Error()))
return
}
logs := make([]LogInfo, len(logIds))
for i, l := range logIds {
logs[i].Foreign = s.cli.IsForeignLog(l)
logs[i].LogID = hex.EncodeToString(l[:])
idx, _, err := s.cli.GetLastCommittedLog(l)
if err == nil {
logs[i].Valid = true
logs[i].LastIndex = idx
logs[i].LastStatement, err = s.cli.GetLogPreimage(l, uint64(idx))
if err != nil {
logs[i].Valid = false
logs[i].Error = "Could not fetch preimage for this log's last committed statement"
} else {
lastCommitHex, err := s.cli.GetLogCommitment(l, uint64(idx))
if err != nil {
logs[i].Valid = false
logs[i].Error = "Could not fetch the commitment hash for this log's last committed statement"
} else {
logs[i].LastCommitment = hex.EncodeToString(lastCommitHex[:])
comm, err := s.cli.getCommitment(lastCommitHex[:])
if err != nil {
logs[i].Valid = false
logs[i].Error = "Could not fetch commitment details for this log's last committed statement"
} else {
logs[i].LastCommitmentProof = hex.EncodeToString(comm.MerkleProof.Bytes())
logs[i].LastCommitmentBlock = hex.EncodeToString(comm.IncludedInBlock[:])
block, err := s.cli.GetBlockHeaderByHash(comm.IncludedInBlock)
if err != nil {
logs[i].Valid = false
logs[i].Error = "Could not fetch block details for this log's last committed statement"
} else {
logs[i].LastCommitmentTimestamp = block.Timestamp.Unix()
}
}
}
}
} else {
logs[i].Valid = false
logs[i].Error = "Could not find a commitment for this log (yet)"
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(logs)
}
// Logs will return a list of known logs and their last statements and proofs
func (s *RpcServer) Export(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
logIdHex, err := hex.DecodeString(vars["logId"])
if err != nil || len(logIdHex) != 32 {
s.writeError(w, fmt.Errorf("Invalid Log ID"))
return
}
logId32 := [32]byte{}
copy(logId32[:], logIdHex)
fs, err := s.cli.ExportLog(logId32)
if err != nil {
s.writeError(w, fmt.Errorf("Unable to export log: %s", err.Error()))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(fs.Bytes())
}
type JsonCommitment struct {
Commitment string
TxHash string
TriggeredAtBlockHeight int
IncludedInBlock string
}
// Commitments will return a list of server commitments
func (s *RpcServer) Commitments(w http.ResponseWriter, r *http.Request) {
comms, err := s.cli.getAllCommitments()
if err != nil {
s.writeError(w, fmt.Errorf("Error reading commitments: %s", err.Error()))
return
}
jsonComms := make([]JsonCommitment, len(comms))
for i, c := range comms {
jsonComms[i] = JsonCommitment{
Commitment: hex.EncodeToString(c.Commitment[:]),
IncludedInBlock: hex.EncodeToString(c.IncludedInBlock[:]),
TxHash: hex.EncodeToString(c.TxHash[:]),
TriggeredAtBlockHeight: c.TriggeredAtBlockHeight,
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
json.NewEncoder(w).Encode(jsonComms)
}
// Start starts the RPC server listening to client connections
func (s *RpcServer) Start() error {
r := mux.NewRouter()
r.HandleFunc("/start", s.StartLog).Methods("POST")
r.HandleFunc("/append", s.AppendLog).Methods("POST")
r.HandleFunc("/status", s.Status).Methods("GET")
r.HandleFunc("/addforeignlog", s.AddForeignLog).Methods("POST")
r.HandleFunc("/verifyonce", s.VerifyOnce).Methods("POST")
r.HandleFunc("/logs", s.Logs).Methods("GET")
r.HandleFunc("/commitments", s.Commitments).Methods("GET")
r.HandleFunc("/export/{logId}", s.Export).Methods("GET")
logging.Debugf("Server is listening on localhost:8001")
return http.ListenAndServe("localhost:8001", r)
}