-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
private.go
340 lines (299 loc) · 10.5 KB
/
private.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
// Copyright 2019 The Smilo-blackbox Authors
// This file is part of the Smilo-blackbox library.
//
// The Smilo-blackbox library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The Smilo-blackbox library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the Smilo-blackbox library. If not, see <http://www.gnu.org/licenses/>.
package api
import (
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"strings"
"Smilo-blackbox/src/data"
"Smilo-blackbox/src/server/encoding"
"io/ioutil"
"github.com/gorilla/mux"
"Smilo-blackbox/src/crypt"
"Smilo-blackbox/src/utils"
)
// SendRaw It receives headers "bb0x-from" and "bb0x-to", payload body and returns Status Code 200 and encoded key plain text.
func SendRaw(w http.ResponseWriter, r *http.Request) {
var fromEncoded []byte
var err error
from := r.Header.Get(utils.HeaderFrom)
to := r.Header.Get(utils.HeaderTo)
if to == "" {
message := fmt.Sprintf("Invalid request: %s, invalid headers. to:%s", r.URL, to)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
if from != "" {
fromEncoded, err = base64.StdEncoding.DecodeString(from)
if err != nil {
message := fmt.Sprintf("Invalid request: %s, bb0x-from header (%s) is not a valid key.", r.URL, from)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
} else {
//use default
defaultPubKey := base64.StdEncoding.EncodeToString(crypt.GetPublicKeys()[0])
fromEncoded, err = base64.StdEncoding.DecodeString(defaultPubKey)
log.WithField("defaultPubKey", defaultPubKey).Info("Request from NOT filled, will use default PubKey")
if err != nil {
message := fmt.Sprintf("Invalid request: %s, bb0x-from header (%s) is not a valid key.", r.URL, from)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
}
encodedRecipients := strings.Split(to, ",")
var errors []string
var recipients = make([][]byte, len(encodedRecipients))
for i := 0; i < len(encodedRecipients); i++ {
decodedValue, err := base64.StdEncoding.DecodeString(encodedRecipients[i])
if err != nil {
errors = append(errors, fmt.Sprintf("bb0x-to header (%s) is not a valid key", encodedRecipients[i]))
}
recipients[i] = decodedValue
}
if len(errors) > 0 {
message := fmt.Sprintf("Invalid request: %s, %s.", r.URL, strings.Join(errors, ", "))
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
encPayload, err := ioutil.ReadAll(r.Body)
defer func() {
err := r.Body.Close()
if err != nil {
log.WithError(err).Error("Could not r.Body.Close()")
}
}()
if err != nil || encPayload == nil {
message := fmt.Sprintf("Invalid request: %s, missing payload, err: %s", r.URL, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
dbuf := make([]byte, base64.StdEncoding.DecodedLen(len(encPayload)))
n, err := base64.StdEncoding.Decode(dbuf, encPayload)
if err != nil {
message := fmt.Sprintf("Invalid request: %s, error decoding payload: (%s), %s", r.URL, encPayload, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
payload := dbuf[:n]
if len(payload) == 0 {
message := fmt.Sprintf("Invalid request: %s, len of payload after decode is zero: (%s), %s", r.URL, encPayload, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
}
encTrans := createNewEncodedTransaction(w, r, payload, fromEncoded, recipients)
if encTrans != nil {
txEncoded := base64.StdEncoding.EncodeToString(encTrans.Hash)
log.WithField("txEncoded", txEncoded).Info("Created transaction, ")
_, err := w.Write([]byte(txEncoded))
if err != nil {
log.WithError(err).Error("Could not w.Write")
}
w.Header().Set("Content-Type", "text/plain")
}
}
// Send It receives json SendRequest with from, to and payload, returns Status Code 200 and json KeyJSON with encoded key.
func Send(w http.ResponseWriter, r *http.Request) {
var sendReq SendRequest
err := json.NewDecoder(r.Body).Decode(&sendReq)
defer func() {
err := r.Body.Close()
if err != nil {
log.WithError(err).Error("Could not r.Body.Close")
}
}()
if err != nil {
message := fmt.Sprintf("Invalid request: %s, error: %s", r.URL, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
payload, sender, recipients, msgs := sendReq.Parse()
if len(msgs) > 0 {
message := fmt.Sprintf("Invalid request: %s %s", r.URL, strings.Join(msgs, "\n"))
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
encTrans := createNewEncodedTransaction(w, r, payload, sender, recipients)
if encTrans != nil {
sendResp := KeyJSON{Key: base64.StdEncoding.EncodeToString(encTrans.Hash)}
err := json.NewEncoder(w).Encode(sendResp)
if err != nil {
log.WithError(err).Error("Could not json.NewEncoder")
}
w.Header().Set("Content-Type", "application/json")
}
}
// SendSignedTx It receives header "bb0x-to" and raw transaction hash body and returns Status Code 200 and transaction hash.
func SendSignedTx(w http.ResponseWriter, r *http.Request) {
var err error
to := r.Header.Get(utils.HeaderTo)
if to == "" {
message := fmt.Sprintf("Invalid request: %s, invalid headers. to:%s", r.URL, to)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
recipients, errors := splitToString(to)
if len(errors) > 0 {
message := fmt.Sprintf("Invalid request: %s, %s.", r.URL, strings.Join(errors, ", "))
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
encodedHash, err := ioutil.ReadAll(r.Body)
defer func() {
err := r.Body.Close()
if err != nil {
log.WithError(err).Error("Could not r.Body.Close()")
}
}()
if err != nil || encodedHash == nil {
message := fmt.Sprintf("Invalid request: %s, missing transaction hash, err: %s", r.URL, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
key, err := base64.StdEncoding.DecodeString(string(encodedHash))
if err != nil {
message := fmt.Sprintf("Invalid request: %s, hash value (%s) is not a valid key.", r.URL, encodedHash)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
encRawTrans, err := data.FindEncryptedRawTransaction(key)
if err != nil || encRawTrans == nil {
message := fmt.Sprintf("Raw Transaction key: %s not found", hex.EncodeToString(key))
log.Error(message)
requestError(w, http.StatusNotFound, message)
return
}
encPayload := encoding.Deserialize(encRawTrans.EncodedPayload)
payload := encPayload.Decode(crypt.GetPublicKeys()[0])
encTrans := createNewEncodedTransaction(w, r, payload, encRawTrans.Sender, recipients)
if encTrans != nil {
txEncoded := base64.StdEncoding.EncodeToString(encTrans.Hash)
log.WithField("txEncoded", txEncoded).Info("Created transaction, ")
_, err := w.Write([]byte(txEncoded))
if err != nil {
log.WithError(err).Error("Could not w.Write")
}
w.Header().Set("Content-Type", "text/plain")
}
}
func splitToString(to string) ([][]byte, []string) {
encodedRecipients := strings.Split(to, ",")
var errors []string
var recipients = make([][]byte, len(encodedRecipients))
for i := 0; i < len(encodedRecipients); i++ {
decodedValue, err := base64.StdEncoding.DecodeString(encodedRecipients[i])
if err != nil {
errors = append(errors, fmt.Sprintf("bb0x-to header (%s) is not a valid key", encodedRecipients[i]))
}
recipients[i] = decodedValue
}
return recipients, errors
}
func createNewEncodedTransaction(w http.ResponseWriter, r *http.Request, payload []byte, fromEncoded []byte, recipients [][]byte) *data.EncryptedTransaction {
encPayload, err := encoding.EncodePayloadData(payload, fromEncoded, recipients)
if err != nil {
message := fmt.Sprintf("Error Encoding Payload on Request: url: %s, err: %s", r.URL, err)
log.Error(message)
requestError(w, http.StatusInternalServerError, message)
return nil
}
encTrans := data.NewEncryptedTransaction(*encPayload.Serialize())
err = encTrans.Save()
if err != nil {
log.WithError(err).Error("Could not encTrans.Save()")
}
pushToAllRecipients(recipients, encTrans)
return encTrans
}
func pushToAllRecipients(recipients [][]byte, encTrans *data.EncryptedTransaction) {
for _, recipient := range recipients {
PushTransactionForOtherNodes(*encTrans, recipient)
}
}
// Receive is a Deprecated API
// It receives a ReceiveRequest json with an encoded key (hash) and to values, returns decrypted payload
func Receive(w http.ResponseWriter, r *http.Request) {
var receiveReq ReceiveRequest
err := json.NewDecoder(r.Body).Decode(&receiveReq)
defer func() {
err := r.Body.Close()
if err != nil {
log.WithError(err).Error("Could not r.Body.Close()")
}
}()
if err != nil {
message := fmt.Sprintf("Invalid request: %s, error: %s", r.URL, err)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
key, to, msgs := receiveReq.Parse()
if len(msgs) > 0 {
message := fmt.Sprintf("Invalid request: %s %s", r.URL, strings.Join(msgs, "\n"))
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
RetrieveJSONPayload(w, r, key, to)
}
// TransactionGet it receives a GET request with a hash on path and query var "to" with encoded hash and to, returns decrypted payload
func TransactionGet(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
err := r.ParseForm()
if err != nil {
log.WithError(err).Error("Could not ParseForm")
return
}
encodedTo := r.Form.Get("to")
hash := params["hash"]
if hash == "" || encodedTo == "" {
message := fmt.Sprintf("Invalid request: %s, invalid query.", r.URL)
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
var errors []string
key, err := base64.URLEncoding.DecodeString(hash)
if err != nil {
errors = append(errors, "Invalid hash value.")
}
to, err2 := base64.URLEncoding.DecodeString(encodedTo)
if err2 != nil {
errors = append(errors, "Invalid reciepient(to) value.")
}
if len(errors) > 0 {
message := fmt.Sprintf("Invalid request: %s %s", r.URL, strings.Join(errors, "\n"))
log.Error(message)
requestError(w, http.StatusBadRequest, message)
return
}
RetrieveJSONPayload(w, r, key, to)
}