-
Notifications
You must be signed in to change notification settings - Fork 1
/
bootstrapper.go
628 lines (551 loc) · 18.2 KB
/
bootstrapper.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package bootstrap
import (
"context"
"fmt"
"go.uber.org/zap"
"github.com/DioneProtocol/odysseygo/cache"
"github.com/DioneProtocol/odysseygo/ids"
"github.com/DioneProtocol/odysseygo/proto/pb/p2p"
"github.com/DioneProtocol/odysseygo/snow"
"github.com/DioneProtocol/odysseygo/snow/choices"
"github.com/DioneProtocol/odysseygo/snow/consensus/odyssey"
"github.com/DioneProtocol/odysseygo/snow/engine/common"
"github.com/DioneProtocol/odysseygo/snow/engine/odyssey/vertex"
"github.com/DioneProtocol/odysseygo/utils/logging"
"github.com/DioneProtocol/odysseygo/utils/set"
"github.com/DioneProtocol/odysseygo/version"
)
const (
// We cache processed vertices where height = c * stripeDistance for c = {1,2,3...}
// This forms a "stripe" of cached DAG vertices at height stripeDistance, 2*stripeDistance, etc.
// This helps to limit the number of repeated DAG traversals performed
stripeDistance = 2000
stripeWidth = 5
cacheSize = 100000
)
var _ common.BootstrapableEngine = (*bootstrapper)(nil)
func New(
config Config,
onFinished func(ctx context.Context, lastReqID uint32) error,
) (common.BootstrapableEngine, error) {
b := &bootstrapper{
Config: config,
StateSummaryFrontierHandler: common.NewNoOpStateSummaryFrontierHandler(config.Ctx.Log),
AcceptedStateSummaryHandler: common.NewNoOpAcceptedStateSummaryHandler(config.Ctx.Log),
PutHandler: common.NewNoOpPutHandler(config.Ctx.Log),
QueryHandler: common.NewNoOpQueryHandler(config.Ctx.Log),
ChitsHandler: common.NewNoOpChitsHandler(config.Ctx.Log),
AppHandler: config.VM,
processedCache: &cache.LRU[ids.ID, struct{}]{Size: cacheSize},
Fetcher: common.Fetcher{
OnFinished: onFinished,
},
}
if err := b.metrics.Initialize("bs", config.Ctx.OdysseyRegisterer); err != nil {
return nil, err
}
config.Config.Bootstrapable = b
b.Bootstrapper = common.NewCommonBootstrapper(config.Config)
return b, nil
}
// Note: To align with the Snowman invariant, it should be guaranteed the VM is
// not used until after the bootstrapper has been Started.
type bootstrapper struct {
Config
// list of NoOpsHandler for messages dropped by bootstrapper
common.StateSummaryFrontierHandler
common.AcceptedStateSummaryHandler
common.PutHandler
common.QueryHandler
common.ChitsHandler
common.AppHandler
common.Bootstrapper
common.Fetcher
metrics
started bool
// IDs of vertices that we will send a GetAncestors request for once we are
// not at the max number of outstanding requests
needToFetch set.Set[ids.ID]
// Contains IDs of vertices that have recently been processed
processedCache *cache.LRU[ids.ID, struct{}]
}
func (b *bootstrapper) Clear() error {
if err := b.VtxBlocked.Clear(); err != nil {
return err
}
if err := b.TxBlocked.Clear(); err != nil {
return err
}
if err := b.VtxBlocked.Commit(); err != nil {
return err
}
return b.TxBlocked.Commit()
}
// Ancestors handles the receipt of multiple containers. Should be received in
// response to a GetAncestors message to [nodeID] with request ID [requestID].
// Expects vtxs[0] to be the vertex requested in the corresponding GetAncestors.
func (b *bootstrapper) Ancestors(ctx context.Context, nodeID ids.NodeID, requestID uint32, vtxs [][]byte) error {
lenVtxs := len(vtxs)
if lenVtxs == 0 {
b.Ctx.Log.Debug("Ancestors contains no vertices",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
)
return b.GetAncestorsFailed(ctx, nodeID, requestID)
}
if lenVtxs > b.Config.AncestorsMaxContainersReceived {
b.Ctx.Log.Debug("ignoring containers in Ancestors",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Int("numIgnored", lenVtxs-b.Config.AncestorsMaxContainersReceived),
)
vtxs = vtxs[:b.Config.AncestorsMaxContainersReceived]
}
requestedVtxID, requested := b.OutstandingRequests.Remove(nodeID, requestID)
vtx, err := b.Manager.ParseVtx(ctx, vtxs[0]) // first vertex should be the one we requested in GetAncestors request
if err != nil {
if !requested {
b.Ctx.Log.Debug("failed to parse unrequested vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Error(err),
)
return nil
}
if b.Ctx.Log.Enabled(logging.Verbo) {
b.Ctx.Log.Verbo("failed to parse requested vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Stringer("vtxID", requestedVtxID),
zap.Binary("vtxBytes", vtxs[0]),
zap.Error(err),
)
} else {
b.Ctx.Log.Debug("failed to parse requested vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Stringer("vtxID", requestedVtxID),
zap.Error(err),
)
}
return b.fetch(ctx, requestedVtxID)
}
vtxID := vtx.ID()
// If the vertex is neither the requested vertex nor a needed vertex, return early and re-fetch if necessary
if requested && requestedVtxID != vtxID {
b.Ctx.Log.Debug("received incorrect vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Stringer("vtxID", vtxID),
)
return b.fetch(ctx, requestedVtxID)
}
if !requested && !b.OutstandingRequests.Contains(vtxID) && !b.needToFetch.Contains(vtxID) {
b.Ctx.Log.Debug("received un-needed vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Stringer("vtxID", vtxID),
)
return nil
}
// Do not remove from outstanding requests if this did not answer a specific outstanding request
// to ensure that real responses are not dropped in favor of potentially byzantine Ancestors messages that
// could force the node to bootstrap 1 vertex at a time.
b.needToFetch.Remove(vtxID)
// All vertices added to [processVertices] have received transitive votes from the accepted frontier
processVertices := make([]odyssey.Vertex, 1, len(vtxs)) // Process all of the valid vertices in this message
processVertices[0] = vtx
parents, err := vtx.Parents()
if err != nil {
return err
}
eligibleVertices := set.NewSet[ids.ID](len(parents))
for _, parent := range parents {
eligibleVertices.Add(parent.ID())
}
for _, vtxBytes := range vtxs[1:] { // Parse/persist all the vertices
vtx, err := b.Manager.ParseVtx(ctx, vtxBytes) // Persists the vtx
if err != nil {
b.Ctx.Log.Debug("failed to parse vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Error(err),
)
b.Ctx.Log.Debug("failed to parse vertex",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Binary("vtxBytes", vtxBytes),
zap.Error(err),
)
break
}
vtxID := vtx.ID()
if !eligibleVertices.Contains(vtxID) {
b.Ctx.Log.Debug("received vertex that should not have been included",
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
zap.Stringer("vtxID", vtxID),
)
break
}
eligibleVertices.Remove(vtxID)
parents, err := vtx.Parents()
if err != nil {
return err
}
for _, parent := range parents {
eligibleVertices.Add(parent.ID())
}
processVertices = append(processVertices, vtx)
b.needToFetch.Remove(vtxID) // No need to fetch this vertex since we have it now
}
return b.process(ctx, processVertices...)
}
func (b *bootstrapper) GetAncestorsFailed(ctx context.Context, nodeID ids.NodeID, requestID uint32) error {
vtxID, ok := b.OutstandingRequests.Remove(nodeID, requestID)
if !ok {
b.Ctx.Log.Debug("skipping GetAncestorsFailed call",
zap.String("reason", "no matching outstanding request"),
zap.Stringer("nodeID", nodeID),
zap.Uint32("requestID", requestID),
)
return nil
}
// Send another request for the vertex
return b.fetch(ctx, vtxID)
}
func (b *bootstrapper) Connected(
ctx context.Context,
nodeID ids.NodeID,
nodeVersion *version.Application,
) error {
if err := b.VM.Connected(ctx, nodeID, nodeVersion); err != nil {
return err
}
if err := b.StartupTracker.Connected(ctx, nodeID, nodeVersion); err != nil {
return err
}
if b.started || !b.StartupTracker.ShouldStart() {
return nil
}
b.started = true
return b.Startup(ctx)
}
func (b *bootstrapper) Disconnected(ctx context.Context, nodeID ids.NodeID) error {
if err := b.VM.Disconnected(ctx, nodeID); err != nil {
return err
}
return b.StartupTracker.Disconnected(ctx, nodeID)
}
func (*bootstrapper) Timeout(context.Context) error {
return nil
}
func (*bootstrapper) Gossip(context.Context) error {
return nil
}
func (b *bootstrapper) Shutdown(ctx context.Context) error {
b.Ctx.Log.Info("shutting down bootstrapper")
return b.VM.Shutdown(ctx)
}
func (*bootstrapper) Notify(context.Context, common.Message) error {
return nil
}
func (b *bootstrapper) Start(ctx context.Context, startReqID uint32) error {
b.Ctx.Log.Info("starting bootstrap")
b.Ctx.State.Set(snow.EngineState{
Type: p2p.EngineType_ENGINE_TYPE_ODYSSEY,
State: snow.Bootstrapping,
})
if err := b.VM.SetState(ctx, snow.Bootstrapping); err != nil {
return fmt.Errorf("failed to notify VM that bootstrapping has started: %w",
err)
}
if err := b.VtxBlocked.SetParser(ctx, &vtxParser{
log: b.Ctx.Log,
numAccepted: b.numAcceptedVts,
numDropped: b.numDroppedVts,
manager: b.Manager,
}); err != nil {
return err
}
if err := b.TxBlocked.SetParser(&txParser{
log: b.Ctx.Log,
numAccepted: b.numAcceptedTxs,
numDropped: b.numDroppedTxs,
vm: b.VM,
}); err != nil {
return err
}
b.Config.SharedCfg.RequestID = startReqID
// If the network was already linearized, don't attempt to linearize it
// again.
linearized, err := b.Manager.StopVertexAccepted(ctx)
if err != nil {
return fmt.Errorf("failed to get linearization status: %w", err)
}
if linearized {
edge := b.Manager.Edge(ctx)
return b.ForceAccepted(ctx, edge)
}
// If requested, assume the currently accepted state is what was linearized.
//
// Note: This is used to linearize networks that were created after the
// linearization occurred.
if b.Config.LinearizeOnStartup {
edge := b.Manager.Edge(ctx)
stopVertex, err := b.Manager.BuildStopVtx(ctx, edge)
if err != nil {
return fmt.Errorf("failed to create stop vertex: %w", err)
}
if err := stopVertex.Accept(ctx); err != nil {
return fmt.Errorf("failed to accept stop vertex: %w", err)
}
stopVertexID := stopVertex.ID()
b.Ctx.Log.Info("accepted stop vertex",
zap.Stringer("vtxID", stopVertexID),
)
return b.ForceAccepted(ctx, []ids.ID{stopVertexID})
}
if !b.StartupTracker.ShouldStart() {
return nil
}
b.started = true
return b.Startup(ctx)
}
func (b *bootstrapper) HealthCheck(ctx context.Context) (interface{}, error) {
vmIntf, vmErr := b.VM.HealthCheck(ctx)
intf := map[string]interface{}{
"consensus": struct{}{},
"vm": vmIntf,
}
return intf, vmErr
}
func (b *bootstrapper) GetVM() common.VM {
return b.VM
}
// Add the vertices in [vtxIDs] to the set of vertices that we need to fetch,
// and then fetch vertices (and their ancestors) until either there are no more
// to fetch or we are at the maximum number of outstanding requests.
func (b *bootstrapper) fetch(ctx context.Context, vtxIDs ...ids.ID) error {
b.needToFetch.Add(vtxIDs...)
for b.needToFetch.Len() > 0 && b.OutstandingRequests.Len() < common.MaxOutstandingGetAncestorsRequests {
vtxID := b.needToFetch.CappedList(1)[0]
b.needToFetch.Remove(vtxID)
// Make sure we haven't already requested this vertex
if b.OutstandingRequests.Contains(vtxID) {
continue
}
// Make sure we don't already have this vertex
if _, err := b.Manager.GetVtx(ctx, vtxID); err == nil {
continue
}
validatorIDs, err := b.Config.Beacons.Sample(1) // validator to send request to
if err != nil {
return fmt.Errorf("dropping request for %s as there are no validators", vtxID)
}
validatorID := validatorIDs[0]
b.Config.SharedCfg.RequestID++
b.OutstandingRequests.Add(validatorID, b.Config.SharedCfg.RequestID, vtxID)
b.Config.Sender.SendGetAncestors(ctx, validatorID, b.Config.SharedCfg.RequestID, vtxID) // request vertex and ancestors
}
return b.checkFinish(ctx)
}
// Process the vertices in [vtxs].
func (b *bootstrapper) process(ctx context.Context, vtxs ...odyssey.Vertex) error {
// Vertices that we need to process. Store them in a heap for deduplication
// and so we always process vertices further down in the DAG first. This helps
// to reduce the number of repeated DAG traversals.
toProcess := vertex.NewHeap()
for _, vtx := range vtxs {
vtxID := vtx.ID()
if _, ok := b.processedCache.Get(vtxID); !ok { // only process a vertex if we haven't already
toProcess.Push(vtx)
} else {
b.VtxBlocked.RemoveMissingID(vtxID)
}
}
vtxHeightSet := set.Set[ids.ID]{}
prevHeight := uint64(0)
for toProcess.Len() > 0 { // While there are unprocessed vertices
if b.Halted() {
return nil
}
vtx := toProcess.Pop() // Get an unknown vertex or one furthest down the DAG
vtxID := vtx.ID()
switch vtx.Status() {
case choices.Unknown:
b.VtxBlocked.AddMissingID(vtxID)
b.needToFetch.Add(vtxID) // We don't have this vertex locally. Mark that we need to fetch it.
case choices.Rejected:
return fmt.Errorf("tried to accept %s even though it was previously rejected", vtxID)
case choices.Processing:
b.needToFetch.Remove(vtxID)
b.VtxBlocked.RemoveMissingID(vtxID)
// Add to queue of vertices to execute when bootstrapping finishes.
pushed, err := b.VtxBlocked.Push(ctx, &vertexJob{
log: b.Ctx.Log,
numAccepted: b.numAcceptedVts,
numDropped: b.numDroppedVts,
vtx: vtx,
})
if err != nil {
return err
}
if !pushed {
// If the vertex is already on the queue, then we have already
// pushed [vtx]'s transactions and traversed into its parents.
continue
}
txs, err := vtx.Txs(ctx)
if err != nil {
return err
}
for _, tx := range txs {
// Add to queue of txs to execute when bootstrapping finishes.
pushed, err := b.TxBlocked.Push(ctx, &txJob{
log: b.Ctx.Log,
numAccepted: b.numAcceptedTxs,
numDropped: b.numDroppedTxs,
tx: tx,
})
if err != nil {
return err
}
if pushed {
b.numFetchedTxs.Inc()
}
}
b.numFetchedVts.Inc()
verticesFetchedSoFar := b.VtxBlocked.Jobs.PendingJobs()
if verticesFetchedSoFar%common.StatusUpdateFrequency == 0 { // Periodically print progress
if !b.Config.SharedCfg.Restarted {
b.Ctx.Log.Info("fetched vertices",
zap.Uint64("numVerticesFetched", verticesFetchedSoFar),
)
} else {
b.Ctx.Log.Debug("fetched vertices",
zap.Uint64("numVerticesFetched", verticesFetchedSoFar),
)
}
}
parents, err := vtx.Parents()
if err != nil {
return err
}
for _, parent := range parents { // Process the parents of this vertex (traverse up the DAG)
parentID := parent.ID()
if _, ok := b.processedCache.Get(parentID); !ok { // But only if we haven't processed the parent
if !vtxHeightSet.Contains(parentID) {
toProcess.Push(parent)
}
}
}
height, err := vtx.Height()
if err != nil {
return err
}
if height%stripeDistance < stripeWidth { // See comment for stripeDistance
b.processedCache.Put(vtxID, struct{}{})
}
if height == prevHeight {
vtxHeightSet.Add(vtxID)
} else {
// Set new height and reset [vtxHeightSet]
prevHeight = height
vtxHeightSet.Clear()
vtxHeightSet.Add(vtxID)
}
}
}
if err := b.TxBlocked.Commit(); err != nil {
return err
}
if err := b.VtxBlocked.Commit(); err != nil {
return err
}
return b.fetch(ctx)
}
// ForceAccepted starts bootstrapping. Process the vertices in [accepterContainerIDs].
func (b *bootstrapper) ForceAccepted(ctx context.Context, acceptedContainerIDs []ids.ID) error {
pendingContainerIDs := b.VtxBlocked.MissingIDs()
// Append the list of accepted container IDs to pendingContainerIDs to ensure
// we iterate over every container that must be traversed.
pendingContainerIDs = append(pendingContainerIDs, acceptedContainerIDs...)
b.Ctx.Log.Debug("starting bootstrapping",
zap.Int("numMissingVertices", len(pendingContainerIDs)),
zap.Int("numAcceptedVertices", len(acceptedContainerIDs)),
)
toProcess := make([]odyssey.Vertex, 0, len(pendingContainerIDs))
for _, vtxID := range pendingContainerIDs {
if vtx, err := b.Manager.GetVtx(ctx, vtxID); err == nil {
if vtx.Status() == choices.Accepted {
b.VtxBlocked.RemoveMissingID(vtxID)
} else {
toProcess = append(toProcess, vtx) // Process this vertex.
}
} else {
b.VtxBlocked.AddMissingID(vtxID)
b.needToFetch.Add(vtxID) // We don't have this vertex. Mark that we have to fetch it.
}
}
return b.process(ctx, toProcess...)
}
// checkFinish repeatedly executes pending transactions and requests new frontier blocks until there aren't any new ones
// after which it finishes the bootstrap process
func (b *bootstrapper) checkFinish(ctx context.Context) error {
// If there are outstanding requests for vertices or we still need to fetch vertices, we can't finish
pendingJobs := b.VtxBlocked.MissingIDs()
if b.IsBootstrapped() || len(pendingJobs) > 0 {
return nil
}
if !b.Config.SharedCfg.Restarted {
b.Ctx.Log.Info("executing transactions")
} else {
b.Ctx.Log.Debug("executing transactions")
}
_, err := b.TxBlocked.ExecuteAll(
ctx,
b.Config.Ctx,
b,
b.Config.SharedCfg.Restarted,
b.Ctx.TxAcceptor,
)
if err != nil || b.Halted() {
return err
}
if !b.Config.SharedCfg.Restarted {
b.Ctx.Log.Info("executing vertices")
} else {
b.Ctx.Log.Debug("executing vertices")
}
_, err = b.VtxBlocked.ExecuteAll(
ctx,
b.Config.Ctx,
b,
b.Config.SharedCfg.Restarted,
b.Ctx.VertexAcceptor,
)
if err != nil || b.Halted() {
return err
}
// If the chain is linearized, we should immediately move on to start
// bootstrapping snowman.
linearized, err := b.Manager.StopVertexAccepted(ctx)
if err != nil {
return err
}
if !linearized {
b.Ctx.Log.Debug("checking for stop vertex before finishing bootstrapping")
return b.Restart(ctx, true)
}
// Invariant: edge will only be the stop vertex after its acceptance.
edge := b.Manager.Edge(ctx)
stopVertexID := edge[0]
if err := b.VM.Linearize(ctx, stopVertexID); err != nil {
return err
}
b.processedCache.Flush()
return b.OnFinished(ctx, b.Config.SharedCfg.RequestID)
}