-
Notifications
You must be signed in to change notification settings - Fork 665
/
bootstrapper.go
513 lines (447 loc) · 16 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
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package bootstrap
import (
"errors"
"fmt"
"math"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/ava-labs/avalanchego/cache"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/consensus/avalanche"
"github.com/ava-labs/avalanchego/snow/engine/avalanche/vertex"
"github.com/ava-labs/avalanchego/snow/engine/common"
"github.com/ava-labs/avalanchego/snow/engine/common/queue"
"github.com/ava-labs/avalanchego/utils/formatting"
)
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
// Parameters for delaying bootstrapping to avoid potential CPU burns
bootstrappingDelay = 10 * time.Second
)
var errUnexpectedTimeout = errors.New("unexpected timeout fired")
// Config ...
type Config struct {
common.Config
// VtxBlocked tracks operations that are blocked on vertices
VtxBlocked *queue.JobsWithMissing
// TxBlocked tracks operations that are blocked on transactions
TxBlocked *queue.Jobs
Manager vertex.Manager
VM vertex.DAGVM
}
// Bootstrapper ...
type Bootstrapper struct {
common.Bootstrapper
common.Fetcher
metrics
// VtxBlocked tracks operations that are blocked on vertices
VtxBlocked *queue.JobsWithMissing
// TxBlocked tracks operations that are blocked on transactions
TxBlocked *queue.Jobs
Manager vertex.Manager
VM vertex.DAGVM
// IDs of vertices that we will send a GetAncestors request for once we are
// not at the max number of outstanding requests
needToFetch ids.Set
// Contains IDs of vertices that have recently been processed
processedCache *cache.LRU
// number of state transitions executed
executedStateTransitions int
awaitingTimeout bool
}
// Initialize this engine.
func (b *Bootstrapper) Initialize(
config Config,
onFinished func() error,
namespace string,
registerer prometheus.Registerer,
) error {
b.VtxBlocked = config.VtxBlocked
b.TxBlocked = config.TxBlocked
b.Manager = config.Manager
b.VM = config.VM
b.processedCache = &cache.LRU{Size: cacheSize}
b.OnFinished = onFinished
b.executedStateTransitions = math.MaxInt32
if err := b.metrics.Initialize(namespace, registerer); err != nil {
return err
}
if err := b.VtxBlocked.SetParser(&vtxParser{
log: config.Ctx.Log,
numAccepted: b.numAcceptedVts,
numDropped: b.numDroppedVts,
manager: b.Manager,
}); err != nil {
return err
}
if err := b.TxBlocked.SetParser(&txParser{
log: config.Ctx.Log,
numAccepted: b.numAcceptedTxs,
numDropped: b.numDroppedTxs,
vm: b.VM,
}); err != nil {
return err
}
config.Bootstrapable = b
return b.Bootstrapper.Initialize(config.Config)
}
// CurrentAcceptedFrontier returns the set of vertices that this node has accepted
// that have no accepted children
func (b *Bootstrapper) CurrentAcceptedFrontier() ([]ids.ID, error) {
return b.Manager.Edge(), nil
}
// FilterAccepted returns the IDs of vertices in [containerIDs] that this node has accepted
func (b *Bootstrapper) FilterAccepted(containerIDs []ids.ID) []ids.ID {
acceptedVtxIDs := make([]ids.ID, 0, len(containerIDs))
for _, vtxID := range containerIDs {
if vtx, err := b.Manager.GetVtx(vtxID); err == nil && vtx.Status() == choices.Accepted {
acceptedVtxIDs = append(acceptedVtxIDs, vtxID)
}
}
return acceptedVtxIDs
}
// 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(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(vtxID); err == nil {
continue
}
validators, err := b.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 := validators[0].ID()
b.RequestID++
b.OutstandingRequests.Add(validatorID, b.RequestID, vtxID)
b.Sender.GetAncestors(validatorID, b.RequestID, vtxID) // request vertex and ancestors
}
return b.checkFinish()
}
// Process the vertices in [vtxs].
func (b *Bootstrapper) process(vtxs ...avalanche.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 := ids.Set{}
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.
if pushed, err := b.VtxBlocked.Push(&vertexJob{
log: b.Ctx.Log,
numAccepted: b.numAcceptedVts,
numDropped: b.numDroppedVts,
vtx: vtx,
}); err != nil {
return err
} else 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()
if err != nil {
return err
}
for _, tx := range txs {
// Add to queue of txs to execute when bootstrapping finishes.
if pushed, err := b.TxBlocked.Push(&txJob{
log: b.Ctx.Log,
numAccepted: b.numAcceptedTxs,
numDropped: b.numDroppedTxs,
tx: tx,
}); err != nil {
return err
} else if pushed {
b.numFetchedTxs.Inc()
}
}
b.numFetchedVts.Inc()
b.NumFetched++ // Progress tracker
if b.NumFetched%common.StatusUpdateFrequency == 0 {
if !b.Restarted {
b.Ctx.Log.Info("fetched %d vertices", b.NumFetched)
} else {
b.Ctx.Log.Debug("fetched %d vertices", b.NumFetched)
}
}
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, nil)
}
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()
}
// MultiPut handles the receipt of multiple containers. Should be received in response to a GetAncestors message to [vdr]
// with request ID [requestID]. Expects vtxs[0] to be the vertex requested in the corresponding GetAncestors.
func (b *Bootstrapper) MultiPut(vdr ids.ShortID, requestID uint32, vtxs [][]byte) error {
lenVtxs := len(vtxs)
if lenVtxs == 0 {
b.Ctx.Log.Debug("MultiPut(%s, %d) contains no vertices", vdr, requestID)
return b.GetAncestorsFailed(vdr, requestID)
}
if lenVtxs > b.MultiputMaxContainersReceived {
vtxs = vtxs[:b.MultiputMaxContainersReceived]
b.Ctx.Log.Debug("ignoring %d containers in multiput(%s, %d)", lenVtxs-b.MultiputMaxContainersReceived, vdr, requestID)
}
requestedVtxID, requested := b.OutstandingRequests.Remove(vdr, requestID)
vtx, err := b.Manager.ParseVtx(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 from %s with requestID %d: %s", vdr, requestID, err)
return nil
}
b.Ctx.Log.Debug("failed to parse requested vertex %s: %s", requestedVtxID, err)
b.Ctx.Log.Verbo("vertex: %s", formatting.DumpBytes{Bytes: vtxs[0]})
return b.fetch(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 from %s with vertexID %s", vdr, vtxID)
return b.fetch(requestedVtxID)
}
if !requested && !b.OutstandingRequests.Contains(vtxID) && !b.needToFetch.Contains(vtxID) {
b.Ctx.Log.Debug("received un-needed vertex from %s with vertexID %s", vdr, 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 MultiPut 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([]avalanche.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 := ids.NewSet(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(vtxBytes) // Persists the vtx
if err != nil {
b.Ctx.Log.Debug("failed to parse vertex: %s", err)
b.Ctx.Log.Verbo("vertex: %s", formatting.DumpBytes{Bytes: vtxBytes})
break
}
vtxID := vtx.ID()
if !eligibleVertices.Contains(vtxID) {
b.Ctx.Log.Debug("received vertex that should not have been included in MultiPut from %s with vertexID %s", vdr, 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(processVertices...)
}
// GetAncestorsFailed is called when a GetAncestors message we sent fails
func (b *Bootstrapper) GetAncestorsFailed(vdr ids.ShortID, requestID uint32) error {
vtxID, ok := b.OutstandingRequests.Remove(vdr, requestID)
if !ok {
b.Ctx.Log.Debug("GetAncestorsFailed(%s, %d) called but there was no outstanding request to this validator with this ID", vdr, requestID)
return nil
}
// Send another request for the vertex
return b.fetch(vtxID)
}
func (b *Bootstrapper) Timeout() error {
if !b.awaitingTimeout {
return errUnexpectedTimeout
}
b.awaitingTimeout = false
if !b.Subnet.IsBootstrapped() {
return b.RestartBootstrap(true)
}
return b.finish()
}
// ForceAccepted starts bootstrapping. Process the vertices in [accepterContainerIDs].
func (b *Bootstrapper) ForceAccepted(acceptedContainerIDs []ids.ID) error {
if err := b.VM.Bootstrapping(); err != nil {
return fmt.Errorf("failed to notify VM that bootstrapping has started: %w",
err)
}
b.NumFetched = 0
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 with %d missing vertices and %d from the accepted frontier", len(pendingContainerIDs), len(acceptedContainerIDs))
toProcess := make([]avalanche.Vertex, 0, len(pendingContainerIDs))
for _, vtxID := range pendingContainerIDs {
if vtx, err := b.Manager.GetVtx(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(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() 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.Ctx.IsBootstrapped() || len(pendingJobs) > 0 || b.awaitingTimeout {
return nil
}
if !b.Restarted {
b.Ctx.Log.Info("bootstrapping fetched %d vertices. Executing transaction state transitions...", b.NumFetched)
} else {
b.Ctx.Log.Debug("bootstrapping fetched %d vertices. Executing transaction state transitions...", b.NumFetched)
}
_, err := b.TxBlocked.ExecuteAll(b.Ctx, b, b.Restarted, b.Ctx.DecisionDispatcher)
if err != nil || b.Halted() {
return err
}
if !b.Restarted {
b.Ctx.Log.Info("executing vertex state transitions...")
} else {
b.Ctx.Log.Debug("executing vertex state transitions...")
}
executedVts, err := b.VtxBlocked.ExecuteAll(b.Ctx, b, b.Restarted, b.Ctx.ConsensusDispatcher)
if err != nil || b.Halted() {
return err
}
previouslyExecuted := b.executedStateTransitions
b.executedStateTransitions = executedVts
// Not that executedVts < c*previouslyExecuted is enforced so that the
// bootstrapping process will terminate even as new vertices are being
// issued.
if executedVts > 0 && executedVts < previouslyExecuted/2 && b.RetryBootstrap {
b.Ctx.Log.Debug("checking for more vertices before finishing bootstrapping")
return b.RestartBootstrap(true)
}
// Notify the subnet that this chain is synced
b.Subnet.Bootstrapped(b.Ctx.ChainID)
b.processedCache.Flush()
// If the subnet hasn't finished bootstrapping, this chain should remain
// syncing.
if !b.Subnet.IsBootstrapped() {
if !b.Restarted {
b.Ctx.Log.Info("waiting for the remaining chains in this subnet to finish syncing")
} else {
b.Ctx.Log.Debug("waiting for the remaining chains in this subnet to finish syncing")
}
// Restart bootstrapping after [bootstrappingDelay] to keep up to date
// on the latest tip.
b.Timer.RegisterTimeout(bootstrappingDelay)
b.awaitingTimeout = true
return nil
}
return b.finish()
}
// Finish bootstrapping
func (b *Bootstrapper) finish() error {
if err := b.VM.Bootstrapped(); err != nil {
return fmt.Errorf("failed to notify VM that bootstrapping has finished: %w",
err)
}
// Start consensus
if err := b.OnFinished(); err != nil {
return err
}
b.Ctx.Bootstrapped()
return nil
}
// Connected implements the Engine interface.
func (b *Bootstrapper) Connected(validatorID ids.ShortID) error {
err := b.VM.Connected(validatorID)
if err != nil {
return err
}
return b.Bootstrapper.Connected(validatorID)
}
// Disconnected implements the Engine interface.
func (b *Bootstrapper) Disconnected(validatorID ids.ShortID) error {
err := b.VM.Disconnected(validatorID)
if err != nil {
return err
}
return b.Bootstrapper.Disconnected(validatorID)
}