/
messages.go
274 lines (245 loc) · 8.79 KB
/
messages.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
// Copyright 2019 Finobo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package handlers
import (
"encoding/binary"
"encoding/json"
"net/http"
"time"
"github.com/mailchain/mailchain/cmd/internal/http/params"
"github.com/mailchain/mailchain/encoding"
"github.com/mailchain/mailchain/errs"
"github.com/mailchain/mailchain/internal/address"
"github.com/mailchain/mailchain/internal/envelope"
"github.com/mailchain/mailchain/internal/keystore"
"github.com/mailchain/mailchain/internal/keystore/kdf/multi"
"github.com/mailchain/mailchain/internal/mailbox"
"github.com/mailchain/mailchain/stores"
"github.com/pkg/errors"
)
// GetMessages returns a handler get spec.
func GetMessages(inbox stores.State, cache stores.Cache, ks keystore.Store, deriveKeyOptions multi.OptionsBuilders) func(w http.ResponseWriter, r *http.Request) { //nolint: funlen, gocyclo
// Get swagger:route GET /messages Messages GetMessages
//
// Get Mailchain messages.
//
// Check the protocol, network, address combination for Mailchain messages.
// Responses:
// 200: GetMessagesResponse
// 422: ValidationError
return func(w http.ResponseWriter, r *http.Request) {
req, err := parseGetMessagesRequest(r)
if err != nil {
errs.JSONWriter(w, r, http.StatusUnprocessableEntity, errors.WithStack(err))
return
}
if !ks.HasAddress(req.addressBytes, req.Protocol, req.Network) {
errs.JSONWriter(w, r, http.StatusNotAcceptable, errors.Errorf("no private key found for address"))
return
}
txs, err := inbox.GetTransactions(req.Protocol, req.Network, req.addressBytes)
if err != nil {
errs.JSONWriter(w, r, http.StatusInternalServerError, errors.WithStack(err))
return
}
messages := make([]getMessage, 0, len(txs))
for _, tx := range txs {
env, err := envelope.Unmarshal(tx.EnvelopeData)
if err != nil {
messages = append(messages, getMessage{Status: errors.WithMessagef(err, "failed to unmarshal envelope, %s", encoding.EncodeHexZeroX(tx.EnvelopeData)).Error()})
continue
}
decrypterKind, err := env.DecrypterKind()
if err != nil {
messages = append(messages, getMessage{Status: errors.WithMessage(err, "failed to find decrypter type").Error()})
continue
}
decrypter, err := ks.GetDecrypter(req.addressBytes, req.Protocol, req.Network, decrypterKind, deriveKeyOptions)
if err != nil {
messages = append(messages, getMessage{Status: errors.WithMessage(err, "could not get `decrypter`").Error()})
continue
}
message, err := mailbox.ReadMessage(tx.EnvelopeData, decrypter, cache)
if err != nil {
messages = append(messages, getMessage{Status: errors.WithMessage(err, "could not read message").Error()})
continue
}
buf := make([]byte, binary.MaxVarintLen64)
n := binary.PutVarint(buf, tx.BlockNumber)
readStatus, _ := inbox.GetReadStatus(message.ID)
mailStore := &stores.Message{
Body: string(message.Body),
Headers: stores.Header{
To: message.Headers.To.String(),
From: message.Headers.From.String(),
Date: message.Headers.Date,
MessageID: message.ID.HexString(),
ContentType: message.Headers.ContentType,
},
Read: readStatus,
Subject: message.Headers.Subject,
Status: "ok",
BlockID: encoding.EncodeHexZeroX(buf[:n]),
BlockIDEncoding: encoding.KindHex0XPrefix,
TransactionHash: encoding.EncodeHexZeroX(tx.Hash),
TransactionHashEncoding: encoding.KindHex0XPrefix,
}
messages = append(messages, convertStoreMessageToGetMessage(mailStore))
}
if err := json.NewEncoder(w).Encode(getResponse{Messages: messages}); err != nil {
errs.JSONWriter(w, r, http.StatusInternalServerError, err)
return
}
w.Header().Set("Content-Type", "application/json")
}
}
// GetMessagesRequest get mailchain messages
// swagger:parameters GetMessages
type GetMessagesRequest struct {
// Address to use when looking for messages.
//
// in: query
// required: true
// example: 0xde0b295669a9fd93d5f28d9ec85e40f4cb697bae
// pattern: 0x[a-fA-F0-9]{40}
Address string `json:"address"`
// Network to use when looking for messages.
//
// enum: mainnet,goerli,ropsten,rinkeby,local
// in: query
// required: true
// example: goerli
Network string `json:"network"`
// Protocol to use when looking for messages.
//
// enum: ethereum
// in: query
// required: true
// example: ethereum
Protocol string `json:"protocol"`
addressBytes []byte
}
// ParseGetRequest get all the details for the get request.
func parseGetMessagesRequest(r *http.Request) (*GetMessagesRequest, error) {
protocol, err := params.QueryRequireProtocol(r)
if err != nil {
return nil, err
}
network, err := params.QueryRequireNetwork(r)
if err != nil {
return nil, err
}
addr, err := params.QueryRequireAddress(r)
if err != nil {
return nil, err
}
addressBytes, err := address.DecodeByProtocol(addr, protocol)
if err != nil {
return nil, err
}
return &GetMessagesRequest{
Address: addr,
addressBytes: addressBytes,
Network: network,
Protocol: protocol,
}, nil
}
func convertStoreMessageToGetMessage(message *stores.Message) getMessage {
return getMessage{
Body: message.Body,
Headers: &getHeaders{
To: message.Headers.To,
From: message.Headers.From,
Date: message.Headers.Date,
MessageID: message.Headers.MessageID,
ContentType: message.Headers.ContentType,
},
Read: message.Read,
Subject: message.Subject,
Status: message.Status,
BlockID: message.BlockID,
BlockIDEncoding: message.BlockIDEncoding,
TransactionHash: message.TransactionHash,
TransactionHashEncoding: message.TransactionHashEncoding,
}
}
// GetResponse Holds the response messages
//
// swagger:response GetMessagesResponse
type getResponse struct {
// in: body
Messages []getMessage `json:"messages"`
}
// swagger:model GetMessagesResponseMessage
type getMessage struct {
// Headers
// readOnly: true
Headers *getHeaders `json:"headers,omitempty"`
// Body of the mail message
// readOnly: true
// example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur maximus metus ante, sit amet ullamcorper dui hendrerit ac.
// Sed vestibulum dui lectus, quis eleifend urna mollis eu. Integer dictum metus ut sem rutrum aliquet.
Body string `json:"body,omitempty"`
// Subject of the mail message
// readOnly: true
// example: Hello world
Subject string `json:"subject,omitempty"`
// readOnly: true
Status string `json:"status"`
// readOnly: true
StatusCode string `json:"status-code"`
// Read status of the message
// readOnly: true
// example: true
Read bool `json:"read"`
// Transaction's block number
// readOnly: true
BlockID string `json:"block-id,omitempty"`
// Transaction's block number encoding type used by the specific protocol
// readOnly: true
BlockIDEncoding string `json:"block-id-encoding,omitempty"`
// Transaction's hash
// readOnly: true
TransactionHash string `json:"transaction-hash,omitempty"`
// Transaction's hash encoding type used by the specific protocol
// readOnly: true
TransactionHashEncoding string `json:"transaction-hash-encoding,omitempty"`
}
// swagger:model GetMessagesResponseHeaders
type getHeaders struct {
// When the message was created, this can be different to the transaction data of the message.
// readOnly: true
// example: 12 Mar 19 20:23 UTC
Date time.Time `json:"date"`
// The sender of the message
// readOnly: true
// example: Charlotte <5602ea95540bee46d03ba335eed6f49d117eab95c8ab8b71bae2cdd1e564a761@ropsten.ethereum>
From string `json:"from"`
// The recipient of the message
// readOnly: true
// To: <4cb0a77b76667dac586c40cc9523ace73b5d772bd503c63ed0ca596eae1658b2@ropsten.ethereum>
To string `json:"to"`
// Reply to if the reply address is different to the from address.
// readOnly: true
ReplyTo string `json:"reply-to,omitempty"`
// Unique identifier of the message
// example: 47eca011e32b52c71005ad8a8f75e1b44c92c99fd12e43bccfe571e3c2d13d2e9a826a550f5ff63b247af471@mailchain
// readOnly: true
MessageID string `json:"message-id"`
// The content type and the encoding of the message body
// readOnly: true
// example: text/plain; charset=\"UTF-8\",
// text/html; charset=\"UTF-8\"
ContentType string `json:"content-type"`
}