-
Notifications
You must be signed in to change notification settings - Fork 175
/
backend_accounts.go
357 lines (297 loc) · 10.1 KB
/
backend_accounts.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
package backend
import (
"bytes"
"context"
"errors"
"time"
"github.com/rs/zerolog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
execproto "github.com/onflow/flow/protobuf/go/flow/execution"
"github.com/onflow/flow-go/engine/access/rpc/connection"
"github.com/onflow/flow-go/engine/common/rpc"
"github.com/onflow/flow-go/engine/common/rpc/convert"
fvmerrors "github.com/onflow/flow-go/fvm/errors"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/module/execution"
"github.com/onflow/flow-go/module/irrecoverable"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/storage"
)
type backendAccounts struct {
log zerolog.Logger
state protocol.State
headers storage.Headers
executionReceipts storage.ExecutionReceipts
connFactory connection.ConnectionFactory
nodeCommunicator Communicator
scriptExecutor execution.ScriptExecutor
scriptExecMode IndexQueryMode
}
// GetAccount returns the account details at the latest sealed block.
// Alias for GetAccountAtLatestBlock
func (b *backendAccounts) GetAccount(ctx context.Context, address flow.Address) (*flow.Account, error) {
return b.GetAccountAtLatestBlock(ctx, address)
}
// GetAccountAtLatestBlock returns the account details at the latest sealed block.
func (b *backendAccounts) GetAccountAtLatestBlock(ctx context.Context, address flow.Address) (*flow.Account, error) {
sealed, err := b.state.Sealed().Head()
if err != nil {
err := irrecoverable.NewExceptionf("failed to lookup sealed header: %w", err)
irrecoverable.Throw(ctx, err)
return nil, err
}
sealedBlockID := sealed.ID()
account, err := b.getAccountAtBlock(ctx, address, sealedBlockID, sealed.Height)
if err != nil {
b.log.Debug().Err(err).Msgf("failed to get account at blockID: %v", sealedBlockID)
return nil, err
}
return account, nil
}
// GetAccountAtBlockHeight returns the account details at the given block height
func (b *backendAccounts) GetAccountAtBlockHeight(
ctx context.Context,
address flow.Address,
height uint64,
) (*flow.Account, error) {
blockID, err := b.headers.BlockIDByHeight(height)
if err != nil {
return nil, rpc.ConvertStorageError(err)
}
account, err := b.getAccountAtBlock(ctx, address, blockID, height)
if err != nil {
b.log.Debug().Err(err).Msgf("failed to get account at height: %d", height)
return nil, err
}
return account, nil
}
// getAccountAtBlock returns the account details at the given block
//
// The data may be sourced from the local storage or from an execution node depending on the nodes's
// configuration and the availability of the data.
func (b *backendAccounts) getAccountAtBlock(
ctx context.Context,
address flow.Address,
blockID flow.Identifier,
height uint64,
) (*flow.Account, error) {
switch b.scriptExecMode {
case IndexQueryModeExecutionNodesOnly:
return b.getAccountFromAnyExeNode(ctx, address, blockID)
case IndexQueryModeLocalOnly:
return b.getAccountFromLocalStorage(ctx, address, height)
case IndexQueryModeFailover:
localResult, localErr := b.getAccountFromLocalStorage(ctx, address, height)
if localErr == nil {
return localResult, nil
}
execResult, execErr := b.getAccountFromAnyExeNode(ctx, address, blockID)
b.compareAccountResults(execResult, execErr, localResult, localErr, blockID, address)
return execResult, execErr
case IndexQueryModeCompare:
execResult, execErr := b.getAccountFromAnyExeNode(ctx, address, blockID)
// Only compare actual get account errors from the EN, not system errors
if execErr != nil && !isInvalidArgumentError(execErr) {
return nil, execErr
}
localResult, localErr := b.getAccountFromLocalStorage(ctx, address, height)
b.compareAccountResults(execResult, execErr, localResult, localErr, blockID, address)
// always return EN results
return execResult, execErr
default:
return nil, status.Errorf(codes.Internal, "unknown execution mode: %v", b.scriptExecMode)
}
}
// getAccountFromLocalStorage retrieves the given account from the local storage.
func (b *backendAccounts) getAccountFromLocalStorage(
ctx context.Context,
address flow.Address,
height uint64,
) (*flow.Account, error) {
// make sure data is available for the requested block
account, err := b.scriptExecutor.GetAccountAtBlockHeight(ctx, address, height)
if err != nil {
return nil, convertAccountError(err, address, height)
}
return account, nil
}
// getAccountFromAnyExeNode retrieves the given account from any EN in `execNodes`.
// We attempt querying each EN in sequence. If any EN returns a valid response, then errors from
// other ENs are logged and swallowed. If all ENs fail to return a valid response, then an
// error aggregating all failures is returned.
func (b *backendAccounts) getAccountFromAnyExeNode(
ctx context.Context,
address flow.Address,
blockID flow.Identifier,
) (*flow.Account, error) {
req := &execproto.GetAccountAtBlockIDRequest{
Address: address.Bytes(),
BlockId: blockID[:],
}
execNodes, err := executionNodesForBlockID(ctx, blockID, b.executionReceipts, b.state, b.log)
if err != nil {
return nil, rpc.ConvertError(err, "failed to find execution node to query", codes.Internal)
}
var resp *execproto.GetAccountAtBlockIDResponse
errToReturn := b.nodeCommunicator.CallAvailableNode(
execNodes,
func(node *flow.Identity) error {
var err error
start := time.Now()
resp, err = b.tryGetAccount(ctx, node, req)
duration := time.Since(start)
lg := b.log.With().
Str("execution_node", node.String()).
Hex("block_id", req.GetBlockId()).
Hex("address", req.GetAddress()).
Int64("rtt_ms", duration.Milliseconds()).
Logger()
if err != nil {
lg.Err(err).Msg("failed to execute GetAccount")
return err
}
// return if any execution node replied successfully
lg.Debug().Msg("Successfully got account info")
return nil
},
nil,
)
if errToReturn != nil {
return nil, rpc.ConvertError(errToReturn, "failed to get account from the execution node", codes.Internal)
}
account, err := convert.MessageToAccount(resp.GetAccount())
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to convert account message: %v", err)
}
return account, nil
}
// tryGetAccount attempts to get the account from the given execution node.
func (b *backendAccounts) tryGetAccount(
ctx context.Context,
execNode *flow.Identity,
req *execproto.GetAccountAtBlockIDRequest,
) (*execproto.GetAccountAtBlockIDResponse, error) {
execRPCClient, closer, err := b.connFactory.GetExecutionAPIClient(execNode.Address)
if err != nil {
return nil, err
}
defer closer.Close()
return execRPCClient.GetAccountAtBlockID(ctx, req)
}
// compareAccountResults compares the result and error returned from local and remote getAccount calls
// and logs the results if they are different
func (b *backendAccounts) compareAccountResults(
execNodeResult *flow.Account,
execErr error,
localResult *flow.Account,
localErr error,
blockID flow.Identifier,
address flow.Address,
) {
if b.log.GetLevel() > zerolog.DebugLevel {
return
}
lgCtx := b.log.With().
Hex("block_id", blockID[:]).
Str("address", address.String())
// errors are different
if execErr != localErr {
lgCtx = lgCtx.
AnErr("execution_node_error", execErr).
AnErr("local_error", localErr)
lg := lgCtx.Logger()
lg.Debug().Msg("errors from getting account on local and EN do not match")
return
}
// both errors are nil, compare the accounts
if execErr == nil {
lgCtx, ok := compareAccountsLogger(execNodeResult, localResult, lgCtx)
if !ok {
lg := lgCtx.Logger()
lg.Debug().Msg("accounts from local and EN do not match")
}
}
}
// compareAccountsLogger compares accounts produced by the execution node and local storage and
// return a logger configured to log the differences
func compareAccountsLogger(exec, local *flow.Account, lgCtx zerolog.Context) (zerolog.Context, bool) {
different := false
if exec.Address != local.Address {
lgCtx = lgCtx.
Str("exec_node_address", exec.Address.String()).
Str("local_address", local.Address.String())
different = true
}
if exec.Balance != local.Balance {
lgCtx = lgCtx.
Uint64("exec_node_balance", exec.Balance).
Uint64("local_balance", local.Balance)
different = true
}
contractListMatches := true
if len(exec.Contracts) != len(local.Contracts) {
lgCtx = lgCtx.
Int("exec_node_contract_count", len(exec.Contracts)).
Int("local_contract_count", len(local.Contracts))
contractListMatches = false
different = true
}
missingContracts := zerolog.Arr()
mismatchContracts := zerolog.Arr()
for name, execContract := range exec.Contracts {
localContract, ok := local.Contracts[name]
if !ok {
missingContracts.Str(name)
contractListMatches = false
different = true
}
if !bytes.Equal(execContract, localContract) {
mismatchContracts.Str(name)
different = true
}
}
lgCtx = lgCtx.
Array("missing_contracts", missingContracts).
Array("mismatch_contracts", mismatchContracts)
// only check if there were any missing
if !contractListMatches {
extraContracts := zerolog.Arr()
for name := range local.Contracts {
if _, ok := exec.Contracts[name]; !ok {
extraContracts.Str(name)
different = true
}
}
lgCtx = lgCtx.Array("extra_contracts", extraContracts)
}
if len(exec.Keys) != len(local.Keys) {
lgCtx = lgCtx.
Int("exec_node_key_count", len(exec.Keys)).
Int("local_key_count", len(local.Keys))
different = true
}
mismatchKeys := zerolog.Arr()
for i, execKey := range exec.Keys {
localKey := local.Keys[i]
if !execKey.PublicKey.Equals(localKey.PublicKey) {
mismatchKeys.Int(execKey.Index)
different = true
}
}
lgCtx = lgCtx.Array("mismatch_keys", mismatchKeys)
return lgCtx, !different
}
// convertAccountError converts the script execution error to a gRPC error
func convertAccountError(err error, address flow.Address, height uint64) error {
if err == nil {
return nil
}
if errors.Is(err, storage.ErrNotFound) {
return status.Errorf(codes.NotFound, "account with address %s not found: %v", address, err)
}
if fvmerrors.IsAccountNotFoundError(err) {
return status.Errorf(codes.NotFound, "account not found")
}
return rpc.ConvertIndexError(err, height, "failed to get account")
}