-
Notifications
You must be signed in to change notification settings - Fork 671
/
block.go
514 lines (460 loc) · 14.8 KB
/
block.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
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package proposervm
import (
"context"
"errors"
"fmt"
"time"
"go.uber.org/zap"
"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/snow/choices"
"github.com/ava-labs/avalanchego/snow/consensus/snowman"
"github.com/ava-labs/avalanchego/vms/proposervm/block"
"github.com/ava-labs/avalanchego/vms/proposervm/proposer"
smblock "github.com/ava-labs/avalanchego/snow/engine/snowman/block"
)
const (
// allowable block issuance in the future
maxSkew = 10 * time.Second
)
var (
errUnsignedChild = errors.New("expected child to be signed")
errUnexpectedBlockType = errors.New("unexpected proposer block type")
errInnerParentMismatch = errors.New("inner parentID didn't match expected parent")
errTimeNotMonotonic = errors.New("time must monotonically increase")
errPChainHeightNotMonotonic = errors.New("non monotonically increasing P-chain height")
errPChainHeightNotReached = errors.New("block P-chain height larger than current P-chain height")
errTimeTooAdvanced = errors.New("time is too far advanced")
errProposerWindowNotStarted = errors.New("proposer window hasn't started")
errUnexpectedProposer = errors.New("unexpected proposer for current window")
errProposerMismatch = errors.New("proposer mismatch")
errProposersNotActivated = errors.New("proposers haven't been activated yet")
errPChainHeightTooLow = errors.New("block P-chain height is too low")
)
type Block interface {
snowman.Block
getInnerBlk() snowman.Block
// After a state sync, we may need to update last accepted block data
// without propagating any changes to the innerVM.
// acceptOuterBlk and acceptInnerBlk allow controlling acceptance of outer
// and inner blocks.
acceptOuterBlk() error
acceptInnerBlk(context.Context) error
verifyPreForkChild(ctx context.Context, child *preForkBlock) error
verifyPostForkChild(ctx context.Context, child *postForkBlock) error
verifyPostForkOption(ctx context.Context, child *postForkOption) error
buildChild(context.Context) (Block, error)
pChainHeight(context.Context) (uint64, error)
}
type PostForkBlock interface {
Block
setStatus(choices.Status)
getStatelessBlk() block.Block
setInnerBlk(snowman.Block)
}
// field of postForkBlock and postForkOption
type postForkCommonComponents struct {
vm *VM
innerBlk snowman.Block
status choices.Status
}
// Return the inner block's height
func (p *postForkCommonComponents) Height() uint64 {
return p.innerBlk.Height()
}
// Verify returns nil if:
// 1) [p]'s inner block is not an oracle block
// 2) [child]'s P-Chain height >= [parentPChainHeight]
// 3) [p]'s inner block is the parent of [c]'s inner block
// 4) [child]'s timestamp isn't before [p]'s timestamp
// 5) [child]'s timestamp is within the skew bound
// 6) [childPChainHeight] <= the current P-Chain height
// 7) [child]'s timestamp is within its proposer's window
// 8) [child] has a valid signature from its proposer
// 9) [child]'s inner block is valid
func (p *postForkCommonComponents) Verify(
ctx context.Context,
parentTimestamp time.Time,
parentPChainHeight uint64,
child *postForkBlock,
) error {
if err := verifyIsNotOracleBlock(ctx, p.innerBlk); err != nil {
return err
}
childPChainHeight := child.PChainHeight()
if childPChainHeight < parentPChainHeight {
return errPChainHeightNotMonotonic
}
expectedInnerParentID := p.innerBlk.ID()
innerParentID := child.innerBlk.Parent()
if innerParentID != expectedInnerParentID {
return errInnerParentMismatch
}
childTimestamp := child.Timestamp()
if childTimestamp.Before(parentTimestamp) {
return errTimeNotMonotonic
}
maxTimestamp := p.vm.Time().Add(maxSkew)
if childTimestamp.After(maxTimestamp) {
return errTimeTooAdvanced
}
// If the node is currently syncing - we don't assume that the P-chain has
// been synced up to this point yet.
if p.vm.consensusState == snow.NormalOp {
currentPChainHeight, err := p.vm.ctx.ValidatorState.GetCurrentHeight(ctx)
if err != nil {
p.vm.ctx.Log.Error("block verification failed",
zap.String("reason", "failed to get current P-Chain height"),
zap.Stringer("blkID", child.ID()),
zap.Error(err),
)
return err
}
if childPChainHeight > currentPChainHeight {
return fmt.Errorf("%w: %d > %d",
errPChainHeightNotReached,
childPChainHeight,
currentPChainHeight,
)
}
var shouldHaveProposer bool
if p.vm.IsDurangoActivated(parentTimestamp) {
shouldHaveProposer, err = p.verifyPostDurangoBlockDelay(ctx, parentTimestamp, parentPChainHeight, child)
} else {
shouldHaveProposer, err = p.verifyPreDurangoBlockDelay(ctx, parentTimestamp, parentPChainHeight, child)
}
if err != nil {
return err
}
hasProposer := child.SignedBlock.Proposer() != ids.EmptyNodeID
if shouldHaveProposer != hasProposer {
return fmt.Errorf("%w: shouldHaveProposer (%v) != hasProposer (%v)", errProposerMismatch, shouldHaveProposer, hasProposer)
}
p.vm.ctx.Log.Debug("verified post-fork block",
zap.Stringer("blkID", child.ID()),
zap.Time("parentTimestamp", parentTimestamp),
zap.Time("blockTimestamp", childTimestamp),
)
}
return p.vm.verifyAndRecordInnerBlk(
ctx,
&smblock.Context{
PChainHeight: parentPChainHeight,
},
child,
)
}
// Return the child (a *postForkBlock) of this block
func (p *postForkCommonComponents) buildChild(
ctx context.Context,
parentID ids.ID,
parentTimestamp time.Time,
parentPChainHeight uint64,
) (Block, error) {
// Child's timestamp is the later of now and this block's timestamp
newTimestamp := p.vm.Time().Truncate(time.Second)
if newTimestamp.Before(parentTimestamp) {
newTimestamp = parentTimestamp
}
// The child's P-Chain height is proposed as the optimal P-Chain height that
// is at least the parent's P-Chain height
pChainHeight, err := p.vm.optimalPChainHeight(ctx, parentPChainHeight)
if err != nil {
p.vm.ctx.Log.Error("unexpected build block failure",
zap.String("reason", "failed to calculate optimal P-chain height"),
zap.Stringer("parentID", parentID),
zap.Error(err),
)
return nil, err
}
var shouldBuildSignedBlock bool
if p.vm.IsDurangoActivated(parentTimestamp) {
shouldBuildSignedBlock, err = p.shouldBuildSignedBlockPostDurango(
ctx,
parentID,
parentTimestamp,
parentPChainHeight,
newTimestamp,
)
} else {
shouldBuildSignedBlock, err = p.shouldBuildSignedBlockPreDurango(
ctx,
parentID,
parentTimestamp,
parentPChainHeight,
newTimestamp,
)
}
if err != nil {
return nil, err
}
var innerBlock snowman.Block
if p.vm.blockBuilderVM != nil {
innerBlock, err = p.vm.blockBuilderVM.BuildBlockWithContext(ctx, &smblock.Context{
PChainHeight: parentPChainHeight,
})
} else {
innerBlock, err = p.vm.ChainVM.BuildBlock(ctx)
}
if err != nil {
return nil, err
}
// Build the child
var statelessChild block.SignedBlock
if shouldBuildSignedBlock {
statelessChild, err = block.Build(
parentID,
newTimestamp,
pChainHeight,
p.vm.StakingCertLeaf,
innerBlock.Bytes(),
p.vm.ctx.ChainID,
p.vm.StakingLeafSigner,
)
} else {
statelessChild, err = block.BuildUnsigned(
parentID,
newTimestamp,
pChainHeight,
innerBlock.Bytes(),
)
}
if err != nil {
p.vm.ctx.Log.Error("unexpected build block failure",
zap.String("reason", "failed to generate proposervm block header"),
zap.Stringer("parentID", parentID),
zap.Stringer("blkID", innerBlock.ID()),
zap.Error(err),
)
return nil, err
}
child := &postForkBlock{
SignedBlock: statelessChild,
postForkCommonComponents: postForkCommonComponents{
vm: p.vm,
innerBlk: innerBlock,
status: choices.Processing,
},
}
p.vm.ctx.Log.Info("built block",
zap.Stringer("blkID", child.ID()),
zap.Stringer("innerBlkID", innerBlock.ID()),
zap.Uint64("height", child.Height()),
zap.Uint64("pChainHeight", pChainHeight),
zap.Time("parentTimestamp", parentTimestamp),
zap.Time("blockTimestamp", newTimestamp),
)
return child, nil
}
func (p *postForkCommonComponents) getInnerBlk() snowman.Block {
return p.innerBlk
}
func (p *postForkCommonComponents) setInnerBlk(innerBlk snowman.Block) {
p.innerBlk = innerBlk
}
func verifyIsOracleBlock(ctx context.Context, b snowman.Block) error {
oracle, ok := b.(snowman.OracleBlock)
if !ok {
return fmt.Errorf(
"%w: expected block %s to be a snowman.OracleBlock but it's a %T",
errUnexpectedBlockType, b.ID(), b,
)
}
_, err := oracle.Options(ctx)
return err
}
func verifyIsNotOracleBlock(ctx context.Context, b snowman.Block) error {
oracle, ok := b.(snowman.OracleBlock)
if !ok {
return nil
}
_, err := oracle.Options(ctx)
switch err {
case nil:
return fmt.Errorf(
"%w: expected block %s not to be an oracle block but it's a %T",
errUnexpectedBlockType, b.ID(), b,
)
case snowman.ErrNotOracle:
return nil
default:
return err
}
}
func (p *postForkCommonComponents) verifyPreDurangoBlockDelay(
ctx context.Context,
parentTimestamp time.Time,
parentPChainHeight uint64,
blk *postForkBlock,
) (bool, error) {
var (
blkTimestamp = blk.Timestamp()
childHeight = blk.Height()
proposerID = blk.Proposer()
)
minDelay, err := p.vm.Windower.Delay(
ctx,
childHeight,
parentPChainHeight,
proposerID,
proposer.MaxVerifyWindows,
)
if err != nil {
p.vm.ctx.Log.Error("unexpected block verification failure",
zap.String("reason", "failed to calculate required timestamp delay"),
zap.Stringer("blkID", blk.ID()),
zap.Error(err),
)
return false, err
}
delay := blkTimestamp.Sub(parentTimestamp)
if delay < minDelay {
return false, fmt.Errorf("%w: delay %s < minDelay %s", errProposerWindowNotStarted, delay, minDelay)
}
return delay < proposer.MaxVerifyDelay, nil
}
func (p *postForkCommonComponents) verifyPostDurangoBlockDelay(
ctx context.Context,
parentTimestamp time.Time,
parentPChainHeight uint64,
blk *postForkBlock,
) (bool, error) {
var (
blkTimestamp = blk.Timestamp()
blkHeight = blk.Height()
currentSlot = proposer.TimeToSlot(parentTimestamp, blkTimestamp)
proposerID = blk.Proposer()
)
// populate the slot for the block.
blk.slot = ¤tSlot
// find the expected proposer
expectedProposerID, err := p.vm.Windower.ExpectedProposer(
ctx,
blkHeight,
parentPChainHeight,
currentSlot,
)
switch {
case errors.Is(err, proposer.ErrAnyoneCanPropose):
return false, nil // block should be unsigned
case err != nil:
p.vm.ctx.Log.Error("unexpected block verification failure",
zap.String("reason", "failed to calculate expected proposer"),
zap.Stringer("blkID", blk.ID()),
zap.Error(err),
)
return false, err
case expectedProposerID == proposerID:
return true, nil // block should be signed
default:
return false, fmt.Errorf("%w: slot %d expects %s", errUnexpectedProposer, currentSlot, expectedProposerID)
}
}
func (p *postForkCommonComponents) shouldBuildSignedBlockPostDurango(
ctx context.Context,
parentID ids.ID,
parentTimestamp time.Time,
parentPChainHeight uint64,
newTimestamp time.Time,
) (bool, error) {
parentHeight := p.innerBlk.Height()
currentSlot := proposer.TimeToSlot(parentTimestamp, newTimestamp)
expectedProposerID, err := p.vm.Windower.ExpectedProposer(
ctx,
parentHeight+1,
parentPChainHeight,
currentSlot,
)
switch {
case errors.Is(err, proposer.ErrAnyoneCanPropose):
return false, nil // build an unsigned block
case err != nil:
p.vm.ctx.Log.Error("unexpected build block failure",
zap.String("reason", "failed to calculate expected proposer"),
zap.Stringer("parentID", parentID),
zap.Error(err),
)
return false, err
case expectedProposerID == p.vm.ctx.NodeID:
return true, nil // build a signed block
}
// It's not our turn to propose a block yet. This is likely caused by having
// previously notified the consensus engine to attempt to build a block on
// top of a block that is no longer the preferred block.
p.vm.ctx.Log.Debug("build block dropped",
zap.Time("parentTimestamp", parentTimestamp),
zap.Time("blockTimestamp", newTimestamp),
zap.Uint64("slot", currentSlot),
zap.Stringer("expectedProposer", expectedProposerID),
)
// We need to reschedule the block builder to the next time we can try to
// build a block.
//
// TODO: After Durango activates, restructure this logic to separate
// updating the scheduler from verifying the proposerID.
nextStartTime, err := p.vm.getPostDurangoSlotTime(
ctx,
parentHeight+1,
parentPChainHeight,
currentSlot+1, // We know we aren't the proposer for the current slot
parentTimestamp,
)
if err != nil {
p.vm.ctx.Log.Error("failed to reset block builder scheduler",
zap.String("reason", "failed to calculate expected proposer"),
zap.Stringer("parentID", parentID),
zap.Error(err),
)
return false, err
}
// report the build slot to the metrics.
p.vm.proposerBuildSlotGauge.Set(float64(proposer.TimeToSlot(parentTimestamp, nextStartTime)))
// set the scheduler to let us know when the next block need to be built.
p.vm.Scheduler.SetBuildBlockTime(nextStartTime)
// In case the inner VM only issued one pendingTxs message, we should
// attempt to re-handle that once it is our turn to build the block.
p.vm.notifyInnerBlockReady()
return false, fmt.Errorf("%w: slot %d expects %s", errUnexpectedProposer, currentSlot, expectedProposerID)
}
func (p *postForkCommonComponents) shouldBuildSignedBlockPreDurango(
ctx context.Context,
parentID ids.ID,
parentTimestamp time.Time,
parentPChainHeight uint64,
newTimestamp time.Time,
) (bool, error) {
delay := newTimestamp.Sub(parentTimestamp)
if delay >= proposer.MaxBuildDelay {
return false, nil // time for any node to build an unsigned block
}
parentHeight := p.innerBlk.Height()
proposerID := p.vm.ctx.NodeID
minDelay, err := p.vm.Windower.Delay(ctx, parentHeight+1, parentPChainHeight, proposerID, proposer.MaxBuildWindows)
if err != nil {
p.vm.ctx.Log.Error("unexpected build block failure",
zap.String("reason", "failed to calculate required timestamp delay"),
zap.Stringer("parentID", parentID),
zap.Error(err),
)
return false, err
}
if delay >= minDelay {
// it's time for this node to propose a block. It'll be signed or
// unsigned depending on the delay
return delay < proposer.MaxVerifyDelay, nil
}
// It's not our turn to propose a block yet. This is likely caused by having
// previously notified the consensus engine to attempt to build a block on
// top of a block that is no longer the preferred block.
p.vm.ctx.Log.Debug("build block dropped",
zap.Time("parentTimestamp", parentTimestamp),
zap.Duration("minDelay", minDelay),
zap.Time("blockTimestamp", newTimestamp),
)
// In case the inner VM only issued one pendingTxs message, we should
// attempt to re-handle that once it is our turn to build the block.
p.vm.notifyInnerBlockReady()
return false, fmt.Errorf("%w: delay %s < minDelay %s", errProposerWindowNotStarted, delay, minDelay)
}