-
Notifications
You must be signed in to change notification settings - Fork 244
/
api.go
406 lines (358 loc) · 10.7 KB
/
api.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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
package web3provider
import (
"encoding/json"
"errors"
"github.com/ethereum/go-ethereum/common/hexutil"
"github.com/ethereum/go-ethereum/log"
signercore "github.com/ethereum/go-ethereum/signer/core/apitypes"
"github.com/status-im/status-go/account"
"github.com/status-im/status-go/eth-node/types"
"github.com/status-im/status-go/services/typeddata"
"github.com/status-im/status-go/transactions"
)
const Web3SendAsyncReadOnly = "web3-send-async-read-only"
const RequestAPI = "api-request"
const Web3SendAsyncCallback = "web3-send-async-callback"
const ResponseAPI = "api-response"
const Web3ResponseError = "web3-response-error"
const PermissionWeb3 = "web3"
const PermissionContactCode = "contact-code"
const PermissionUnknown = "unknown"
const ethCoinbase = "eth_coinbase"
var ErrorInvalidAPIRequest = errors.New("invalid API request")
var ErrorUnknownPermission = errors.New("unknown permission")
var authMethods = []string{
"eth_accounts",
"eth_coinbase",
"eth_sendTransaction",
"eth_sign",
"keycard_signTypedData",
"eth_signTypedData",
"eth_signTypedData_v3",
"personal_sign",
}
var signMethods = []string{
"eth_sign",
"personal_sign",
"eth_signTypedData",
"eth_signTypedData_v3",
"eth_signTypedData_v4",
}
var accMethods = []string{
"eth_accounts",
"eth_coinbase",
}
func NewAPI(s *Service) *API {
return &API{
s: s,
}
}
// API is class with methods available over RPC.
type API struct {
s *Service
}
type ETHPayload struct {
ID interface{} `json:"id,omitempty"`
JSONRPC string `json:"jsonrpc"`
From string `json:"from"`
Method string `json:"method"`
Params []interface{} `json:"params"`
Password string `json:"password,omitempty"`
ChainID uint64 `json:"chainId,omitempty"`
}
type JSONRPCResponse struct {
ID interface{} `json:"id,omitempty"`
JSONRPC string `json:"jsonrpc"`
Result interface{} `json:"result"`
}
type Web3SendAsyncReadOnlyRequest struct {
Title string `json:"title,omitempty"`
MessageID interface{} `json:"messageId"`
Payload ETHPayload `json:"payload"`
Hostname string `json:"hostname"`
Address string `json:"address,omitempty"`
}
type Web3SendAsyncReadOnlyError struct {
Code uint `json:"code"`
Message string `json:"message,omitempty"`
}
type Web3SendAsyncReadOnlyResponse struct {
ProviderResponse
MessageID interface{} `json:"messageId"`
Error interface{} `json:"error,omitempty"`
Result interface{} `json:"result,omitempty"`
}
type APIRequest struct {
MessageID interface{} `json:"messageId,omitempty"`
Address string `json:"address,omitempty"`
Hostname string `json:"hostname"`
Permission string `json:"permission"`
}
type APIResponse struct {
ProviderResponse
MessageID interface{} `json:"messageId,omitempty"`
Permission string `json:"permission"`
Data interface{} `json:"data,omitempty"`
IsAllowed bool `json:"isAllowed"`
}
type ProviderResponse struct {
ResponseType string `json:"type"`
}
func (api *API) ProcessRequest(requestType string, payload json.RawMessage) (interface{}, error) {
switch requestType {
case RequestAPI:
var request APIRequest
if err := json.Unmarshal([]byte(payload), &request); err != nil {
return nil, err
}
return api.ProcessAPIRequest(request)
case Web3SendAsyncReadOnly:
var request Web3SendAsyncReadOnlyRequest
if err := json.Unmarshal(payload, &request); err != nil {
return nil, err
}
return api.ProcessWeb3ReadOnlyRequest(request)
default:
return nil, errors.New("invalid request type")
}
}
func contains(item string, elems []string) bool {
for _, x := range elems {
if x == item {
return true
}
}
return false
}
// web3Call returns a response from a read-only eth RPC method
func (api *API) web3Call(request Web3SendAsyncReadOnlyRequest) (*Web3SendAsyncReadOnlyResponse, error) {
var rpcResult interface{}
var errMsg interface{}
if request.Payload.Method == "personal_ecRecover" {
data, err := hexutil.Decode(request.Payload.Params[0].(string))
if err != nil {
return nil, err
}
sig, err := hexutil.Decode(request.Payload.Params[1].(string))
if err != nil {
return nil, err
}
addr, err := api.EcRecover(data, sig)
if err != nil {
return nil, err
}
rpcResult = JSONRPCResponse{
JSONRPC: "2.0",
ID: request.Payload.ID,
Result: addr.String(),
}
} else {
ethPayload, err := json.Marshal(request.Payload)
if err != nil {
return nil, err
}
response := api.s.rpcClient.CallRaw(string(ethPayload))
if response == "" {
errMsg = Web3ResponseError
}
rpcResult = json.RawMessage(response)
}
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Error: errMsg,
Result: rpcResult,
}, nil
}
func (api *API) web3NoPermission(request Web3SendAsyncReadOnlyRequest) (*Web3SendAsyncReadOnlyResponse, error) {
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Error: Web3SendAsyncReadOnlyError{
Code: 4100,
Message: "The requested method and/or account has not been authorized by the user.",
},
}, nil
}
func (api *API) web3AccResponse(request Web3SendAsyncReadOnlyRequest) (*Web3SendAsyncReadOnlyResponse, error) {
dappsAddress, err := api.s.accountsDB.GetDappsAddress()
if err != nil {
return nil, err
}
var result interface{}
if request.Payload.Method == ethCoinbase {
result = dappsAddress
} else {
result = []types.Address{dappsAddress}
}
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Result: JSONRPCResponse{
JSONRPC: "2.0",
ID: request.Payload.ID,
Result: result,
},
}, nil
}
func (api *API) getVerifiedWalletAccount(address, password string) (*account.SelectedExtKey, error) {
exists, err := api.s.accountsDB.AddressExists(types.HexToAddress(address))
if err != nil {
log.Error("failed to query db for a given address", "address", address, "error", err)
return nil, err
}
if !exists {
log.Error("failed to get a selected account", "err", transactions.ErrInvalidTxSender)
return nil, transactions.ErrAccountDoesntExist
}
key, err := api.s.accountsManager.VerifyAccountPassword(api.s.config.KeyStoreDir, address, password)
if err != nil {
log.Error("failed to verify account", "account", address, "error", err)
return nil, err
}
return &account.SelectedExtKey{
Address: key.Address,
AccountKey: key,
}, nil
}
func (api *API) web3SignatureResponse(request Web3SendAsyncReadOnlyRequest) (*Web3SendAsyncReadOnlyResponse, error) {
var err error
var signature types.HexBytes
if request.Payload.Method == "eth_signTypedData" || request.Payload.Method == "eth_signTypedData_v3" {
raw := json.RawMessage(request.Payload.Params[1].(string))
var data typeddata.TypedData
err = json.Unmarshal(raw, &data)
if err == nil {
signature, err = api.signTypedData(data, request.Payload.From, request.Payload.Password)
}
} else if request.Payload.Method == "eth_signTypedData_v4" {
signature, err = api.signTypedDataV4(request.Payload.Params[1].(signercore.TypedData), request.Payload.From, request.Payload.Password)
} else {
signature, err = api.signMessage(request.Payload.Params[0], request.Payload.From, request.Payload.Password)
}
if err != nil {
log.Error("could not sign message", "err", err)
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Error: Web3SendAsyncReadOnlyError{
Code: 4100,
Message: err.Error(),
},
}, nil
}
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Result: JSONRPCResponse{
JSONRPC: "2.0",
ID: request.Payload.ID,
Result: signature,
},
}, nil
}
func (api *API) ProcessWeb3ReadOnlyRequest(request Web3SendAsyncReadOnlyRequest) (*Web3SendAsyncReadOnlyResponse, error) {
hasPermission, err := api.s.permissionsDB.HasPermission(request.Hostname, request.Address, PermissionWeb3)
if err != nil {
return nil, err
}
if contains(request.Payload.Method, authMethods) && !hasPermission {
return api.web3NoPermission(request)
}
if contains(request.Payload.Method, accMethods) {
return api.web3AccResponse(request)
} else if contains(request.Payload.Method, signMethods) {
return api.web3SignatureResponse(request)
} else if request.Payload.Method == "eth_sendTransaction" {
jsonString, err := json.Marshal(request.Payload.Params[0])
if err != nil {
return nil, err
}
var trxArgs transactions.SendTxArgs
if err := json.Unmarshal(jsonString, &trxArgs); err != nil {
return nil, err
}
hash, err := api.sendTransaction(request.Payload.ChainID, trxArgs, request.Payload.Password, Web3SendAsyncReadOnly)
if err != nil {
log.Error("could not send transaction message", "err", err)
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Error: Web3ResponseError,
}, nil
}
return &Web3SendAsyncReadOnlyResponse{
ProviderResponse: ProviderResponse{
ResponseType: Web3SendAsyncCallback,
},
MessageID: request.MessageID,
Result: JSONRPCResponse{
JSONRPC: "2.0",
ID: request.Payload.ID,
Result: hash,
},
}, nil
} else {
return api.web3Call(request)
}
}
func (api *API) ProcessAPIRequest(request APIRequest) (*APIResponse, error) {
if request.Permission == "" {
return nil, ErrorInvalidAPIRequest
}
hasPermission, err := api.s.permissionsDB.HasPermission(request.Hostname, request.Address, request.Permission)
if err != nil {
return nil, err
}
if !hasPermission {
// Not allowed
return &APIResponse{
ProviderResponse: ProviderResponse{
ResponseType: ResponseAPI,
},
Permission: request.Permission,
MessageID: request.MessageID,
IsAllowed: false,
}, nil
}
var data interface{}
switch request.Permission {
case PermissionWeb3:
dappsAddress, err := api.s.accountsDB.GetDappsAddress()
if err != nil {
return nil, err
}
response := make([]interface{}, 1)
response[0] = dappsAddress
data = response
case PermissionContactCode:
pubKey, err := api.s.accountsDB.GetPublicKey()
if err != nil {
return nil, err
}
data = pubKey
default:
return nil, ErrorUnknownPermission
}
return &APIResponse{
ProviderResponse: ProviderResponse{
ResponseType: ResponseAPI,
},
Permission: request.Permission,
MessageID: request.MessageID,
Data: data,
IsAllowed: true,
}, nil
}