-
Notifications
You must be signed in to change notification settings - Fork 166
/
engine.go
283 lines (231 loc) · 8.02 KB
/
engine.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
package provider
import (
"context"
"errors"
"fmt"
"math/rand"
"time"
"github.com/rs/zerolog"
"github.com/onflow/flow-go/engine"
"github.com/onflow/flow-go/engine/execution/state"
"github.com/onflow/flow-go/model/flow"
"github.com/onflow/flow-go/model/flow/filter"
"github.com/onflow/flow-go/model/messages"
"github.com/onflow/flow-go/module"
"github.com/onflow/flow-go/module/trace"
"github.com/onflow/flow-go/network"
"github.com/onflow/flow-go/state/protocol"
"github.com/onflow/flow-go/storage"
"github.com/onflow/flow-go/utils/logging"
)
type ProviderEngine interface {
network.Engine
BroadcastExecutionReceipt(context.Context, *flow.ExecutionReceipt) error
}
// An Engine provides means of accessing data about execution state and broadcasts execution receipts to nodes in the network.
// Also generates and saves execution receipts
type Engine struct {
unit *engine.Unit
log zerolog.Logger
tracer module.Tracer
receiptCon network.Conduit
state protocol.State
execState state.ReadOnlyExecutionState
me module.Local
chunksConduit network.Conduit
metrics module.ExecutionMetrics
checkStakedAtBlock func(blockID flow.Identifier) (bool, error)
}
func New(
logger zerolog.Logger,
tracer module.Tracer,
net module.Network,
state protocol.State,
me module.Local,
execState state.ReadOnlyExecutionState,
metrics module.ExecutionMetrics,
checkStakedAtBlock func(blockID flow.Identifier) (bool, error),
) (*Engine, error) {
log := logger.With().Str("engine", "receipts").Logger()
eng := Engine{
unit: engine.NewUnit(),
log: log,
tracer: tracer,
state: state,
me: me,
execState: execState,
metrics: metrics,
checkStakedAtBlock: checkStakedAtBlock,
}
var err error
eng.receiptCon, err = net.Register(engine.PushReceipts, &eng)
if err != nil {
return nil, fmt.Errorf("could not register receipt provider engine: %w", err)
}
chunksConduit, err := net.Register(engine.ProvideChunks, &eng)
if err != nil {
return nil, fmt.Errorf("could not register chunk data pack provider engine: %w", err)
}
eng.chunksConduit = chunksConduit
return &eng, nil
}
func (e *Engine) SubmitLocal(event interface{}) {
e.Submit(e.me.NodeID(), event)
}
func (e *Engine) Submit(originID flow.Identifier, event interface{}) {
e.unit.Launch(func() {
err := e.Process(originID, event)
if err != nil {
engine.LogError(e.log, err)
}
})
}
func (e *Engine) ProcessLocal(event interface{}) error {
return e.Process(e.me.NodeID(), event)
}
// Ready returns a channel that will close when the engine has
// successfully started.
func (e *Engine) Ready() <-chan struct{} {
return e.unit.Ready()
}
// Done returns a channel that will close when the engine has
// successfully stopped.
func (e *Engine) Done() <-chan struct{} {
return e.unit.Done()
}
func (e *Engine) Process(originID flow.Identifier, event interface{}) error {
return e.unit.Do(func() error {
return e.process(originID, event)
})
}
func (e *Engine) process(originID flow.Identifier, event interface{}) error {
ctx := context.Background()
switch v := event.(type) {
case *messages.ChunkDataRequest:
err := e.onChunkDataRequest(ctx, originID, v)
if err != nil {
return fmt.Errorf("could not answer chunk data request: %w", err)
}
return err
default:
return fmt.Errorf("invalid event type (%T)", event)
}
}
// onChunkDataRequest receives a request for the chunk data pack associated with chunkID from the
// requester `originID`. If such a chunk data pack is available in the execution state, it is sent to the
// requester.
func (e *Engine) onChunkDataRequest(
ctx context.Context,
originID flow.Identifier,
req *messages.ChunkDataRequest,
) error {
processStart := time.Now()
// extracts list of verifier nodes id
chunkID := req.ChunkID
log := e.log.With().
Hex("origin_id", logging.ID(originID)).
Hex("chunk_id", logging.ID(chunkID)).
Logger()
log.Debug().Msg("received chunk data pack request")
// increases collector metric
e.metrics.ChunkDataPackRequested()
cdp, err := e.execState.ChunkDataPackByChunkID(ctx, chunkID)
// we might be behind when we don't have the requested chunk.
// if this happen, log it and return nil
if errors.Is(err, storage.ErrNotFound) {
log.Warn().Msg("chunk not found")
return nil
}
if err != nil {
return fmt.Errorf("could not retrieve chunk ID (%s): %w", originID, err)
}
origin, err := e.ensureStaked(cdp.ChunkID, originID)
if err != nil {
return err
}
var collection flow.Collection
if cdp.CollectionID != flow.ZeroID {
// retrieves collection of non-zero chunks
coll, err := e.execState.GetCollection(cdp.CollectionID)
if err != nil {
return fmt.Errorf("cannot retrieve collection %x for chunk %x: %w", cdp.CollectionID, cdp.ChunkID, err)
}
collection = *coll
}
response := &messages.ChunkDataResponse{
ChunkDataPack: *cdp,
Nonce: rand.Uint64(),
Collection: collection,
}
sinceProcess := time.Since(processStart)
log = log.With().Dur("sinceProcess", sinceProcess).Logger()
if sinceProcess > time.Second*10 {
log.Warn().Msg("chunk data pack query takes longer than 10 secs")
}
// sends requested chunk data pack to the requester
e.unit.Launch(func() {
deliveryStart := time.Now()
err := e.chunksConduit.Unicast(response, originID)
sinceDeliver := time.Since(deliveryStart)
log = log.With().Dur("since_deliver", sinceDeliver).Logger()
if sinceDeliver > time.Second*10 {
log.Warn().Msg("chunk data pack response delivery takes longer than 10 secs")
}
if err != nil {
log.Error().Err(err).Str("origin", origin.String()).Msg("could not send requested chunk data pack to")
return
}
log.Debug().
Hex("collection_id", logging.ID(response.Collection.ID())).
Msg("chunk data pack request successfully replied")
})
return nil
}
func (e *Engine) ensureStaked(chunkID flow.Identifier, originID flow.Identifier) (*flow.Identity, error) {
blockID, err := e.execState.GetBlockIDByChunkID(chunkID)
if err != nil {
return nil, engine.NewInvalidInputErrorf("cannot find blockID corresponding to chunk data pack: %w", err)
}
stakedAt, err := e.checkStakedAtBlock(blockID)
if err != nil {
return nil, engine.NewInvalidInputErrorf("cannot check block staking status: %w", err)
}
if !stakedAt {
return nil, engine.NewInvalidInputErrorf("this node is not staked at the block (%s) corresponding to chunk data pack (%s)", blockID.String(), chunkID.String())
}
origin, err := e.state.AtBlockID(blockID).Identity(originID)
if err != nil {
return nil, engine.NewInvalidInputErrorf("invalid origin id (%s): %w", origin, err)
}
// only verifier nodes are allowed to request chunk data packs
if origin.Role != flow.RoleVerification {
return nil, engine.NewInvalidInputErrorf("invalid role for receiving collection: %s", origin.Role)
}
if origin.Stake == 0 {
return nil, engine.NewInvalidInputErrorf("node %s is not staked at the block (%s) corresponding to chunk data pack (%s)", originID, blockID.String(), chunkID.String())
}
return origin, nil
}
func (e *Engine) BroadcastExecutionReceipt(ctx context.Context, receipt *flow.ExecutionReceipt) error {
finalState, err := receipt.ExecutionResult.FinalStateCommitment()
if err != nil {
return fmt.Errorf("could not get final state: %w", err)
}
span, _ := e.tracer.StartSpanFromContext(ctx, trace.EXEBroadcastExecutionReceipt)
defer span.Finish()
e.log.Debug().
Hex("block_id", logging.ID(receipt.ExecutionResult.BlockID)).
Hex("receipt_id", logging.Entity(receipt)).
Hex("final_state", finalState[:]).
Msg("broadcasting execution receipt")
identities, err := e.state.Final().Identities(filter.HasRole(flow.RoleAccess, flow.RoleConsensus,
flow.RoleVerification))
if err != nil {
return fmt.Errorf("could not get consensus and verification identities: %w", err)
}
err = e.receiptCon.Publish(receipt, identities.NodeIDs()...)
if err != nil {
return fmt.Errorf("could not submit execution receipts: %w", err)
}
return nil
}