-
Notifications
You must be signed in to change notification settings - Fork 175
/
backend.go
437 lines (378 loc) · 15.3 KB
/
backend.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
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package backend
import (
"context"
"fmt"
"time"
lru "github.com/hashicorp/golang-lru"
accessproto "github.com/onflow/flow/protobuf/go/flow/access"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/access"
"github.com/onflow/flow-go/engine/common/rpc"
"github.com/onflow/flow-go/engine/common/rpc/convert"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/flow/filter"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/storage"
)
// maxExecutionNodesCnt is the max number of execution nodes that will be contacted to complete an execution api request
const maxExecutionNodesCnt = 3
// minExecutionNodesCnt is the minimum number of execution nodes expected to have sent the execution receipt for a block
const minExecutionNodesCnt = 2
// maxAttemptsForExecutionReceipt is the maximum number of attempts to find execution receipts for a given block ID
const maxAttemptsForExecutionReceipt = 3
// DefaultMaxHeightRange is the default maximum size of range requests.
const DefaultMaxHeightRange = 250
// DefaultSnapshotHistoryLimit the amount of blocks to look back in state
// when recursively searching for a valid snapshot
const DefaultSnapshotHistoryLimit = 50
// DefaultLoggedScriptsCacheSize is the default size of the lookup cache used to dedupe logs of scripts sent to ENs
// limiting cache size to 16MB and does not affect script execution, only for keeping logs tidy
const DefaultLoggedScriptsCacheSize = 1_000_000
// DefaultConnectionPoolSize is the default size for the connection pool to collection and execution nodes
const DefaultConnectionPoolSize = 250
var preferredENIdentifiers flow.IdentifierList
var fixedENIdentifiers flow.IdentifierList
// Backend implements the Access API.
//
// It is composed of several sub-backends that implement part of the Access API.
//
// Script related calls are handled by backendScripts.
// Transaction related calls are handled by backendTransactions.
// Block Header related calls are handled by backendBlockHeaders.
// Block details related calls are handled by backendBlockDetails.
// Event related calls are handled by backendEvents.
// Account related calls are handled by backendAccounts.
//
// All remaining calls are handled by the base Backend in this file.
type Backend struct {
backendScripts
backendTransactions
backendEvents
backendBlockHeaders
backendBlockDetails
backendAccounts
backendExecutionResults
backendNetwork
state protocol.State
chainID flow.ChainID
collections storage.Collections
executionReceipts storage.ExecutionReceipts
connFactory ConnectionFactory
}
func New(
state protocol.State,
collectionRPC accessproto.AccessAPIClient,
historicalAccessNodes []accessproto.AccessAPIClient,
blocks storage.Blocks,
headers storage.Headers,
collections storage.Collections,
transactions storage.Transactions,
executionReceipts storage.ExecutionReceipts,
executionResults storage.ExecutionResults,
chainID flow.ChainID,
transactionMetrics module.TransactionMetrics,
connFactory ConnectionFactory,
retryEnabled bool,
maxHeightRange uint,
preferredExecutionNodeIDs []string,
fixedExecutionNodeIDs []string,
log zerolog.Logger,
snapshotHistoryLimit int,
) *Backend {
retry := newRetry()
if retryEnabled {
retry.Activate()
}
loggedScripts, err := lru.New(DefaultLoggedScriptsCacheSize)
if err != nil {
log.Fatal().Err(err).Msg("failed to initialize script logging cache")
}
b := &Backend{
state: state,
// create the sub-backends
backendScripts: backendScripts{
headers: headers,
executionReceipts: executionReceipts,
connFactory: connFactory,
state: state,
log: log,
metrics: transactionMetrics,
loggedScripts: loggedScripts,
},
backendTransactions: backendTransactions{
staticCollectionRPC: collectionRPC,
state: state,
chainID: chainID,
collections: collections,
blocks: blocks,
transactions: transactions,
executionReceipts: executionReceipts,
transactionValidator: configureTransactionValidator(state, chainID),
transactionMetrics: transactionMetrics,
retry: retry,
connFactory: connFactory,
previousAccessNodes: historicalAccessNodes,
log: log,
},
backendEvents: backendEvents{
state: state,
headers: headers,
executionReceipts: executionReceipts,
connFactory: connFactory,
log: log,
maxHeightRange: maxHeightRange,
},
backendBlockHeaders: backendBlockHeaders{
headers: headers,
state: state,
},
backendBlockDetails: backendBlockDetails{
blocks: blocks,
state: state,
},
backendAccounts: backendAccounts{
state: state,
headers: headers,
executionReceipts: executionReceipts,
connFactory: connFactory,
log: log,
},
backendExecutionResults: backendExecutionResults{
executionResults: executionResults,
},
backendNetwork: backendNetwork{
state: state,
chainID: chainID,
snapshotHistoryLimit: snapshotHistoryLimit,
},
collections: collections,
executionReceipts: executionReceipts,
connFactory: connFactory,
chainID: chainID,
}
retry.SetBackend(b)
preferredENIdentifiers, err = identifierList(preferredExecutionNodeIDs)
if err != nil {
log.Fatal().Err(err).Msg("failed to convert node id string to Flow Identifier for preferred EN map")
}
fixedENIdentifiers, err = identifierList(fixedExecutionNodeIDs)
if err != nil {
log.Fatal().Err(err).Msg("failed to convert node id string to Flow Identifier for fixed EN map")
}
return b
}
func identifierList(ids []string) (flow.IdentifierList, error) {
idList := make(flow.IdentifierList, len(ids))
for i, idStr := range ids {
id, err := flow.HexStringToIdentifier(idStr)
if err != nil {
return nil, fmt.Errorf("failed to convert node id string %s to Flow Identifier: %v", id, err)
}
idList[i] = id
}
return idList, nil
}
func configureTransactionValidator(state protocol.State, chainID flow.ChainID) *access.TransactionValidator {
return access.NewTransactionValidator(
access.NewProtocolStateBlocks(state),
chainID.Chain(),
access.TransactionValidationOptions{
Expiry: flow.DefaultTransactionExpiry,
ExpiryBuffer: flow.DefaultTransactionExpiryBuffer,
AllowEmptyReferenceBlockID: false,
AllowUnknownReferenceBlockID: false,
CheckScriptsParse: false,
MaxGasLimit: flow.DefaultMaxTransactionGasLimit,
MaxTransactionByteSize: flow.DefaultMaxTransactionByteSize,
MaxCollectionByteSize: flow.DefaultMaxCollectionByteSize,
},
)
}
// Ping responds to requests when the server is up.
func (b *Backend) Ping(ctx context.Context) error {
// staticCollectionRPC is only set if a collection node address was provided at startup
if b.staticCollectionRPC != nil {
_, err := b.staticCollectionRPC.Ping(ctx, &accessproto.PingRequest{})
if err != nil {
return fmt.Errorf("could not ping collection node: %w", err)
}
}
return nil
}
func (b *Backend) GetCollectionByID(_ context.Context, colID flow.Identifier) (*flow.LightCollection, error) {
// retrieve the collection from the collection storage
col, err := b.collections.LightByID(colID)
if err != nil {
// Collections are retrieved asynchronously as we finalize blocks, so
// it is possible for a client to request a finalized block from us
// containing some collection, then get a not found error when requesting
// that collection. These clients should retry.
err = rpc.ConvertStorageError(fmt.Errorf("please retry for collection in finalized block: %w", err))
return nil, err
}
return col, nil
}
func (b *Backend) GetNetworkParameters(_ context.Context) access.NetworkParameters {
return access.NetworkParameters{
ChainID: b.chainID,
}
}
// GetLatestProtocolStateSnapshot returns the latest finalized snapshot
func (b *Backend) GetLatestProtocolStateSnapshot(_ context.Context) ([]byte, error) {
snapshot := b.state.Final()
validSnapshot, err := b.getValidSnapshot(snapshot, 0)
if err != nil {
return nil, err
}
return convert.SnapshotToBytes(validSnapshot)
}
// executionNodesForBlockID returns upto maxExecutionNodesCnt number of randomly chosen execution node identities
// which have executed the given block ID.
// If no such execution node is found, an InsufficientExecutionReceipts error is returned.
func executionNodesForBlockID(
ctx context.Context,
blockID flow.Identifier,
executionReceipts storage.ExecutionReceipts,
state protocol.State,
log zerolog.Logger) (flow.IdentityList, error) {
var executorIDs flow.IdentifierList
// check if the block ID is of the root block. If it is then don't look for execution receipts since they
// will not be present for the root block.
rootBlock, err := state.Params().Root()
if err != nil {
return nil, fmt.Errorf("failed to retreive execution IDs for block ID %v: %w", blockID, err)
}
if rootBlock.ID() == blockID {
executorIdentities, err := state.Final().Identities(filter.HasRole(flow.RoleExecution))
if err != nil {
return nil, fmt.Errorf("failed to retreive execution IDs for block ID %v: %w", blockID, err)
}
executorIDs = executorIdentities.NodeIDs()
} else {
// try to find atleast minExecutionNodesCnt execution node ids from the execution receipts for the given blockID
for attempt := 0; attempt < maxAttemptsForExecutionReceipt; attempt++ {
executorIDs, err = findAllExecutionNodes(blockID, executionReceipts, log)
if err != nil {
return nil, err
}
if len(executorIDs) >= minExecutionNodesCnt {
break
}
// log the attempt
log.Debug().Int("attempt", attempt).Int("max_attempt", maxAttemptsForExecutionReceipt).
Int("execution_receipts_found", len(executorIDs)).
Str("block_id", blockID.String()).
Msg("insufficient execution receipts")
// if one or less execution receipts may have been received then re-query
// in the hope that more might have been received by now
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(100 * time.Millisecond << time.Duration(attempt)):
//retry after an exponential backoff
}
}
receiptCnt := len(executorIDs)
// if less than minExecutionNodesCnt execution receipts have been received so far, then return random ENs
if receiptCnt < minExecutionNodesCnt {
newExecutorIDs, err := state.AtBlockID(blockID).Identities(filter.HasRole(flow.RoleExecution))
if err != nil {
return nil, fmt.Errorf("failed to retreive execution IDs for block ID %v: %w", blockID, err)
}
executorIDs = newExecutorIDs.NodeIDs()
}
}
// choose from the preferred or fixed execution nodes
subsetENs, err := chooseExecutionNodes(state, executorIDs)
if err != nil {
return nil, fmt.Errorf("failed to retreive execution IDs for block ID %v: %w", blockID, err)
}
// randomly choose upto maxExecutionNodesCnt identities
executionIdentitiesRandom := subsetENs.Sample(maxExecutionNodesCnt)
if len(executionIdentitiesRandom) == 0 {
return nil, fmt.Errorf("no matching execution node found for block ID %v", blockID)
}
return executionIdentitiesRandom, nil
}
// findAllExecutionNodes find all the execution nodes ids from the execution receipts that have been received for the
// given blockID
func findAllExecutionNodes(
blockID flow.Identifier,
executionReceipts storage.ExecutionReceipts,
log zerolog.Logger) (flow.IdentifierList, error) {
// lookup the receipt's storage with the block ID
allReceipts, err := executionReceipts.ByBlockID(blockID)
if err != nil {
return nil, fmt.Errorf("failed to retreive execution receipts for block ID %v: %w", blockID, err)
}
executionResultMetaList := make(flow.ExecutionReceiptMetaList, 0, len(allReceipts))
for _, r := range allReceipts {
executionResultMetaList = append(executionResultMetaList, r.Meta())
}
executionResultGroupedMetaList := executionResultMetaList.GroupByResultID()
// maximum number of matching receipts found so far for any execution result id
maxMatchedReceiptCnt := 0
// execution result id key for the highest number of matching receipts in the identicalReceipts map
var maxMatchedReceiptResultID flow.Identifier
// find the largest list of receipts which have the same result ID
for resultID, executionReceiptList := range executionResultGroupedMetaList {
currentMatchedReceiptCnt := executionReceiptList.Size()
if currentMatchedReceiptCnt > maxMatchedReceiptCnt {
maxMatchedReceiptCnt = currentMatchedReceiptCnt
maxMatchedReceiptResultID = resultID
}
}
// if there are more than one execution result for the same block ID, log as error
if executionResultGroupedMetaList.NumberGroups() > 1 {
identicalReceiptsStr := fmt.Sprintf("%v", flow.GetIDs(allReceipts))
log.Error().
Str("block_id", blockID.String()).
Str("execution_receipts", identicalReceiptsStr).
Msg("execution receipt mismatch")
}
// pick the largest list of matching receipts
matchingReceiptMetaList := executionResultGroupedMetaList.GetGroup(maxMatchedReceiptResultID)
metaReceiptGroupedByExecutorID := matchingReceiptMetaList.GroupByExecutorID()
// collect all unique execution node ids from the receipts
var executorIDs flow.IdentifierList
for executorID := range metaReceiptGroupedByExecutorID {
executorIDs = append(executorIDs, executorID)
}
return executorIDs, nil
}
// chooseExecutionNodes finds the subset of execution nodes defined in the identity table by first
// choosing the preferred execution nodes which have executed the transaction. If no such preferred
// execution nodes are found, then the fixed execution nodes defined in the identity table are returned
// If neither preferred nor fixed nodes are defined, then all execution node matching the executor IDs are returned.
// e.g. If execution nodes in identity table are {1,2,3,4}, preferred ENs are defined as {2,3,4}
// and the executor IDs is {1,2,3}, then {2, 3} is returned as the chosen subset of ENs
func chooseExecutionNodes(state protocol.State, executorIDs flow.IdentifierList) (flow.IdentityList, error) {
allENs, err := state.Final().Identities(filter.HasRole(flow.RoleExecution))
if err != nil {
return nil, fmt.Errorf("failed to retreive all execution IDs: %w", err)
}
// first try and choose from the preferred EN IDs
var chosenIDs flow.IdentityList
if len(preferredENIdentifiers) > 0 {
// find the preferred execution node IDs which have executed the transaction
chosenIDs = allENs.Filter(filter.And(filter.HasNodeID(preferredENIdentifiers...),
filter.HasNodeID(executorIDs...)))
if len(chosenIDs) > 0 {
return chosenIDs, nil
}
}
// if no preferred EN ID is found, then choose from the fixed EN IDs
if len(fixedENIdentifiers) > 0 {
// choose fixed ENs which have executed the transaction
chosenIDs = allENs.Filter(filter.And(filter.HasNodeID(fixedENIdentifiers...), filter.HasNodeID(executorIDs...)))
if len(chosenIDs) > 0 {
return chosenIDs, nil
}
// if no such ENs are found then just choose all fixed ENs
chosenIDs = allENs.Filter(filter.HasNodeID(fixedENIdentifiers...))
return chosenIDs, nil
}
// If no preferred or fixed ENs have been specified, then return all executor IDs i.e. no preference at all
return allENs.Filter(filter.HasNodeID(executorIDs...)), nil
}