-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcall_service.go
More file actions
386 lines (373 loc) · 9.96 KB
/
Copy pathcall_service.go
File metadata and controls
386 lines (373 loc) · 9.96 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
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
package api
import (
"context"
"encoding/hex"
"strconv"
"strings"
"github.com/coinbase/rosetta-sdk-go/types"
"github.com/onflow/cadence"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/rosetta/crypto"
"github.com/onflow/rosetta/log"
)
// Call implements the /call endpoint.
func (s *Server) Call(ctx context.Context, r *types.CallRequest) (*types.CallResponse, *types.Error) {
switch r.Method {
case callAccountBalances:
return s.accountBalances(ctx, r.Parameters)
case callAccountPublicKeys:
return s.accountPublicKeys(ctx, r.Parameters)
case callBalanceValidationStatus:
return s.balanceValidationStatus(ctx)
case callEcho:
return s.echo(r.Parameters)
case callFeeValidationStatus:
return s.feeReceiverValidationStatus()
case callLatestBlock:
return s.latestBlock(ctx, r.Parameters)
case callListAccounts:
return s.listAccounts(ctx)
case callVerifyAddress:
return s.verifyAddress(ctx, r.Parameters)
default:
return nil, errNotImplemented
}
}
func (s *Server) accountBalances(ctx context.Context, params map[string]interface{}) (*types.CallResponse, *types.Error) {
if s.Offline {
return nil, errOfflineMode
}
addr, xerr := s.getAccountParam(params)
if xerr != nil {
return nil, xerr
}
var (
err error
hash []byte
)
idempotent := false
if param, ok := params["block_hash"]; ok {
idempotent = true
raw, ok := param.(string)
if !ok {
return nil, wrapErrorf(
errInvalidBlockHash, "block_hash param is not a string: %v", param,
)
}
hash, err = hex.DecodeString(raw)
if err != nil {
return nil, wrapErrorf(
errInvalidBlockHash, "invalid block_hash value: %s", err,
)
}
} else {
client := s.DataAccessNodes.Client()
latest, err := client.LatestBlockHeader(ctx)
if err != nil {
return nil, wrapErr(errInternal, err)
}
hash = latest.Id
}
onchain, xerr := s.getOnchainData(ctx, addr, hash)
if xerr != nil {
return nil, xerr
}
return &types.CallResponse{
Idempotent: idempotent,
Result: map[string]interface{}{
"default_balance": strconv.FormatUint(onchain.DefaultBalance, 10),
"is_proxy": onchain.IsProxy,
"proxy_balance": strconv.FormatUint(onchain.ProxyBalance, 10),
},
}, nil
}
func (s *Server) accountPublicKeys(ctx context.Context, params map[string]interface{}) (*types.CallResponse, *types.Error) {
if s.Offline {
return nil, errOfflineMode
}
addr, xerr := s.getAccountParam(params)
if xerr != nil {
return nil, xerr
}
client := s.DataAccessNodes.Client()
acct, err := client.Account(ctx, addr)
if err != nil {
return nil, wrapErr(errInternal, err)
}
keys := []accountKey{}
for _, key := range acct.Keys {
if key.Revoked {
continue
}
pub := key.PublicKey
// NOTE(tav): We only convert the format of secp256k1 keys. Otherwise,
// we just pass along the key in whatever format Flow uses.
switch key.SignAlgo {
case 3: // ECDSA_secp256k1
pub, err = crypto.ConvertFlowPublicKey(pub)
if err != nil {
return nil, wrapErr(errInternal, err)
}
}
keys = append(keys, accountKey{
HashAlgorithm: key.HashAlgo,
KeyIndex: key.Index,
PublicKey: hex.EncodeToString(pub),
SequenceNumber: key.SequenceNumber,
SignatureAlgorithm: key.SignAlgo,
})
}
if s.Chain.IsProxyContractDeployed() {
latest, err := client.LatestBlockHeader(ctx)
if err != nil {
return nil, wrapErr(errInternal, err)
}
resp, err := client.Execute(
ctx, latest.Id, s.scriptGetProxyPublicKey,
[]cadence.Value{cadence.BytesToAddress(addr)},
)
if err != nil {
return nil, handleExecutionErr(err, "execute get_proxy_public_key")
}
rawKey, ok := resp.(cadence.String)
if !ok {
return nil, wrapErrorf(
errInternal, "failed to convert get_proxy_public_key result to string",
)
}
if rawKey != "" {
if len(keys) > 0 {
return nil, wrapErrorf(
errInternal,
"found proxy key and %d unexpected account keys",
len(keys),
)
}
pub, err := hex.DecodeString(string(rawKey))
if err != nil {
return nil, wrapErrorf(
errInternal,
"failed to hex-decode the get_proxy_public_key result: %s",
err,
)
}
pub, err = crypto.ConvertFlowPublicKey(pub)
if err != nil {
return nil, wrapErr(errInternal, err)
}
// NOTE(tav): For proxy accounts, we only return the public key and none
// of the other fields.
keys = append(keys, accountKey{
PublicKey: hex.EncodeToString(pub),
})
}
}
return &types.CallResponse{
Idempotent: false,
Result: map[string]interface{}{
"keys": keys,
},
}, nil
}
func (s *Server) balanceValidationStatus(ctx context.Context) (*types.CallResponse, *types.Error) {
v := s.getValidationStatus()
switch v.status {
case validationFailure:
return &types.CallResponse{
Result: map[string]interface{}{
"error": v.err,
"status": v.status.String(),
},
}, nil
case validationInProgress:
return &types.CallResponse{
Result: map[string]interface{}{
"accounts": v.accounts,
"checked": v.checked,
"status": v.status.String(),
},
}, nil
case validationNotStarted:
return &types.CallResponse{
Result: map[string]interface{}{
"status": v.status.String(),
},
}, nil
case validationSuccess:
return &types.CallResponse{
Result: map[string]interface{}{
"accounts": v.accounts,
"status": v.status.String(),
},
}, nil
default:
log.Fatalf("Unsupported validation status %d", int(v.status))
panic("unreachable code")
}
}
func (s *Server) feeReceiverValidationStatus() (*types.CallResponse, *types.Error) {
v := s.getFeeValidationStatus()
result := map[string]interface{}{
"status": v.status.String(),
}
if v.err != "" {
result["error"] = v.err
}
if v.onchain != nil {
result["fee_receivers"] = v.onchain
}
if v.missing != nil {
result["missing"] = v.missing
}
return &types.CallResponse{Result: result}, nil
}
func (s *Server) echo(params map[string]interface{}) (*types.CallResponse, *types.Error) {
return &types.CallResponse{
Idempotent: true,
Result: params,
}, nil
}
func (s *Server) getAccountParam(params map[string]interface{}) ([]byte, *types.Error) {
param, ok := params["account"]
if !ok {
return nil, wrapErrorf(errInvalidAccountAddress, "account param is missing")
}
raw, ok := param.(string)
if !ok {
return nil, wrapErrorf(
errInvalidAccountAddress, "account param is not a string: %v", param,
)
}
return s.getAccount(raw)
}
func (s *Server) getOnchainData(ctx context.Context, addr []byte, block []byte) (*onchainData, *types.Error) {
client := s.DataAccessNodes.Client()
script := s.scriptGetBalancesBasic
scriptName := "get_balances_basic"
if s.Chain.IsProxyContractDeployed() {
script = s.scriptGetBalances
scriptName = "get_balances"
}
resp, err := client.Execute(
ctx, block, script,
[]cadence.Value{cadence.BytesToAddress(addr)},
)
if err != nil {
return nil, handleExecutionErr(err, "execute "+scriptName)
}
structValue, ok := resp.(cadence.Struct)
if !ok {
return nil, wrapErrorf(
errInternal,
"failed to convert %s result to array",
scriptName,
)
}
fields := cadence.FieldsMappedByName(structValue)
if len(fields) != 3 {
return nil, wrapErrorf(
errInternal,
"expected 3 fields for the %s result: got %d",
scriptName, len(fields),
)
}
onchain := &onchainData{}
defaultBalance, ok := fields["default_balance"].(cadence.UFix64)
if !ok {
return nil, wrapErrorf(
errInternal,
"expected first field of the %s result to be uint64: got %T",
scriptName, fields["default_balance"],
)
}
onchain.DefaultBalance = uint64(defaultBalance)
isProxy, ok := fields["is_proxy"].(cadence.Bool)
if !ok {
return nil, wrapErrorf(
errInternal,
"expected second field of the %s result to be bool: got %T",
scriptName, fields["is_proxy"],
)
}
onchain.IsProxy = bool(isProxy)
proxyBalance, ok := fields["proxy_balance"].(cadence.UFix64)
if !ok {
return nil, wrapErrorf(
errInternal,
"expected third field of the %s result to be uint64: got %T",
scriptName, fields["proxy_balance"],
)
}
onchain.ProxyBalance = uint64(proxyBalance)
return onchain, nil
}
func (s *Server) latestBlock(ctx context.Context, params map[string]interface{}) (*types.CallResponse, *types.Error) {
client := s.DataAccessNodes.Client()
block, err := client.LatestBlockHeader(ctx)
if err != nil {
return nil, wrapErr(errInternal, err)
}
return &types.CallResponse{
Idempotent: false,
Result: map[string]interface{}{
"block_hash": hex.EncodeToString(block.Id),
"block_height": strconv.FormatUint(block.Height, 10),
"block_timestamp": strconv.FormatInt(block.Timestamp.AsTime().UnixNano(), 10),
},
}, nil
}
func (s *Server) listAccounts(ctx context.Context) (*types.CallResponse, *types.Error) {
accts, err := s.Index.AccountsInfo()
if err != nil {
return nil, wrapErr(errInternal, err)
}
return &types.CallResponse{
Idempotent: false,
Result: map[string]interface{}{
"accounts": accts,
},
}, nil
}
func (s *Server) verifyAddress(ctx context.Context, params map[string]interface{}) (*types.CallResponse, *types.Error) {
if s.Offline {
return nil, errOfflineMode
}
acct, xerr := s.getAccountParam(params)
if xerr != nil {
return &types.CallResponse{
Result: map[string]interface{}{
"error": "invalid Flow address format",
"valid": false,
},
}, nil
}
addr := flow.Address{}
copy(addr[:], acct)
chainID := flow.ChainID("flow-" + s.Chain.Network)
if !chainID.Chain().IsValid(addr) {
return &types.CallResponse{
Result: map[string]interface{}{
"error": "invalid address for Flow " + s.Chain.Network,
"valid": false,
},
}, nil
}
client := s.DataAccessNodes.Client()
_, err := client.Account(ctx, acct)
if err != nil {
if strings.Contains(err.Error(), "account not found") {
return &types.CallResponse{
Result: map[string]interface{}{
"error": "account not found on Flow " + s.Chain.Network,
"valid": false,
},
}, nil
}
return nil, wrapErr(errInternal, err)
}
return &types.CallResponse{
Result: map[string]interface{}{
"valid": true,
},
}, nil
}