forked from OffchainLabs/nitro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathl1_validator.go
566 lines (524 loc) · 17.8 KB
/
l1_validator.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
// Copyright 2021-2022, Offchain Labs, Inc.
// For license information, see https://github.com/nitro/blob/master/LICENSE
package staker
import (
"context"
"errors"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/accounts/abi/bind"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/log"
"github.com/offchainlabs/nitro/arbutil"
"github.com/offchainlabs/nitro/solgen/go/rollupgen"
"github.com/offchainlabs/nitro/staker/txbuilder"
"github.com/offchainlabs/nitro/util/arbmath"
"github.com/offchainlabs/nitro/util/headerreader"
"github.com/offchainlabs/nitro/validator"
)
type ConfirmType uint8
const (
CONFIRM_TYPE_NONE ConfirmType = iota
CONFIRM_TYPE_VALID
CONFIRM_TYPE_INVALID
)
type ConflictType uint8
const (
CONFLICT_TYPE_NONE ConflictType = iota
CONFLICT_TYPE_FOUND
CONFLICT_TYPE_INDETERMINATE
CONFLICT_TYPE_INCOMPLETE
)
type L1Validator struct {
rollup *RollupWatcher
rollupAddress common.Address
validatorUtils *rollupgen.ValidatorUtils
client *ethclient.Client
builder *txbuilder.Builder
wallet ValidatorWalletInterface
callOpts bind.CallOpts
inboxTracker InboxTrackerInterface
txStreamer TransactionStreamerInterface
blockValidator *BlockValidator
lastWasmModuleRoot common.Hash
}
func NewL1Validator(
client *ethclient.Client,
wallet ValidatorWalletInterface,
validatorUtilsAddress common.Address,
callOpts bind.CallOpts,
inboxTracker InboxTrackerInterface,
txStreamer TransactionStreamerInterface,
blockValidator *BlockValidator,
) (*L1Validator, error) {
builder, err := txbuilder.NewBuilder(wallet)
if err != nil {
return nil, err
}
rollup, err := NewRollupWatcher(wallet.RollupAddress(), builder, callOpts)
if err != nil {
return nil, err
}
validatorUtils, err := rollupgen.NewValidatorUtils(
validatorUtilsAddress,
client,
)
if err != nil {
return nil, err
}
return &L1Validator{
rollup: rollup,
rollupAddress: wallet.RollupAddress(),
validatorUtils: validatorUtils,
client: client,
builder: builder,
wallet: wallet,
callOpts: callOpts,
inboxTracker: inboxTracker,
txStreamer: txStreamer,
blockValidator: blockValidator,
}, nil
}
func (v *L1Validator) getCallOpts(ctx context.Context) *bind.CallOpts {
opts := v.callOpts
opts.Context = ctx
return &opts
}
func (v *L1Validator) Initialize(ctx context.Context) error {
err := v.rollup.Initialize(ctx)
if err != nil {
return err
}
return v.updateBlockValidatorModuleRoot(ctx)
}
func (v *L1Validator) updateBlockValidatorModuleRoot(ctx context.Context) error {
if v.blockValidator == nil {
return nil
}
moduleRoot, err := v.rollup.WasmModuleRoot(v.getCallOpts(ctx))
if err != nil {
return err
}
if moduleRoot != v.lastWasmModuleRoot {
err := v.blockValidator.SetCurrentWasmModuleRoot(moduleRoot)
if err != nil {
return err
}
v.lastWasmModuleRoot = moduleRoot
} else if (moduleRoot == common.Hash{}) {
return errors.New("wasmModuleRoot in rollup is zero")
}
return nil
}
func (v *L1Validator) resolveTimedOutChallenges(ctx context.Context) (*types.Transaction, error) {
challengesToEliminate, _, err := v.validatorUtils.TimedOutChallenges(v.getCallOpts(ctx), v.rollupAddress, 0, 10)
if err != nil {
return nil, err
}
if len(challengesToEliminate) == 0 {
return nil, nil
}
log.Info("timing out challenges", "count", len(challengesToEliminate))
return v.wallet.TimeoutChallenges(ctx, challengesToEliminate)
}
func (v *L1Validator) resolveNextNode(ctx context.Context, info *StakerInfo, latestConfirmedNode *uint64) (bool, error) {
callOpts := v.getCallOpts(ctx)
confirmType, err := v.validatorUtils.CheckDecidableNextNode(callOpts, v.rollupAddress)
if err != nil {
return false, err
}
unresolvedNodeIndex, err := v.rollup.FirstUnresolvedNode(callOpts)
if err != nil {
return false, err
}
switch ConfirmType(confirmType) {
case CONFIRM_TYPE_INVALID:
addr := v.wallet.Address()
if info == nil || addr == nil || info.LatestStakedNode <= unresolvedNodeIndex {
// We aren't an example of someone staked on a competitor
return false, nil
}
log.Warn("rejecting node", "node", unresolvedNodeIndex)
auth, err := v.builder.Auth(ctx)
if err != nil {
return false, err
}
_, err = v.rollup.RejectNextNode(auth, *addr)
return true, err
case CONFIRM_TYPE_VALID:
nodeInfo, err := v.rollup.LookupNode(ctx, unresolvedNodeIndex)
if err != nil {
return false, err
}
afterGs := nodeInfo.AfterState().GlobalState
log.Info("confirming node", "node", unresolvedNodeIndex)
auth, err := v.builder.Auth(ctx)
if err != nil {
return false, err
}
_, err = v.rollup.ConfirmNextNode(auth, afterGs.BlockHash, afterGs.SendRoot)
if err != nil {
return false, err
}
*latestConfirmedNode = unresolvedNodeIndex
return true, nil
default:
return false, nil
}
}
func (v *L1Validator) isRequiredStakeElevated(ctx context.Context) (bool, error) {
callOpts := v.getCallOpts(ctx)
baseStake, err := v.rollup.BaseStake(callOpts)
if err != nil {
return false, err
}
requiredStake, err := v.rollup.CurrentRequiredStake(callOpts)
if err != nil {
if headerreader.ExecutionRevertedRegexp.MatchString(err.Error()) {
log.Warn("execution reverted checking if required state is elevated; assuming elevated", "err", err)
return true, nil
}
return false, err
}
return requiredStake.Cmp(baseStake) > 0, nil
}
type createNodeAction struct {
assertion *Assertion
prevInboxMaxCount *big.Int
hash common.Hash
}
type existingNodeAction struct {
number uint64
hash [32]byte
}
type nodeAction interface{}
type OurStakerInfo struct {
LatestStakedNode uint64
LatestStakedNodeHash common.Hash
CanProgress bool
StakeExists bool
*StakerInfo
}
func (v *L1Validator) generateNodeAction(
ctx context.Context,
stakerInfo *OurStakerInfo,
strategy StakerStrategy,
stakerConfig *L1ValidatorConfig,
) (nodeAction, bool, error) {
startState, prevInboxMaxCount, startStateProposedL1, startStateProposedParentChain, err := lookupNodeStartState(
ctx, v.rollup, stakerInfo.LatestStakedNode, stakerInfo.LatestStakedNodeHash,
)
if err != nil {
return nil, false, fmt.Errorf(
"error looking up node %v (hash %v) start state: %w",
stakerInfo.LatestStakedNode, stakerInfo.LatestStakedNodeHash, err,
)
}
startStateProposedHeader, err := v.client.HeaderByNumber(ctx, arbmath.UintToBig(startStateProposedParentChain))
if err != nil {
return nil, false, fmt.Errorf(
"error looking up L1 header of block %v of node start state: %w",
startStateProposedParentChain, err,
)
}
// #nosec G115
startStateProposedTime := time.Unix(int64(startStateProposedHeader.Time), 0)
v.txStreamer.PauseReorgs()
defer v.txStreamer.ResumeReorgs()
localBatchCount, err := v.inboxTracker.GetBatchCount()
if err != nil {
return nil, false, fmt.Errorf("error getting batch count from inbox tracker: %w", err)
}
if localBatchCount < startState.RequiredBatches() || localBatchCount == 0 {
log.Info(
"catching up to chain batches", "localBatches", localBatchCount,
"target", startState.RequiredBatches(),
)
return nil, false, nil
}
caughtUp, startCount, err := GlobalStateToMsgCount(v.inboxTracker, v.txStreamer, startState.GlobalState)
if err != nil {
return nil, false, fmt.Errorf("start state not in chain: %w", err)
}
if !caughtUp {
target := GlobalStatePosition{
BatchNumber: startState.GlobalState.Batch,
PosInBatch: startState.GlobalState.PosInBatch,
}
var current GlobalStatePosition
head, err := v.txStreamer.GetProcessedMessageCount()
if err != nil {
_, current, err = v.blockValidator.GlobalStatePositionsAtCount(head)
}
if err != nil {
log.Info("catching up to chain messages", "target", target)
} else {
log.Info("catching up to chain blocks", "target", target, "current", current)
}
return nil, false, nil
}
var validatedCount arbutil.MessageIndex
var validatedGlobalState validator.GoGlobalState
if v.blockValidator != nil {
valInfo, err := v.blockValidator.ReadLastValidatedInfo()
if err != nil || valInfo == nil {
return nil, false, err
}
validatedGlobalState = valInfo.GlobalState
caughtUp, validatedCount, err = GlobalStateToMsgCount(
v.inboxTracker, v.txStreamer, valInfo.GlobalState,
)
if err != nil {
return nil, false, fmt.Errorf("%w: not found validated block in blockchain", err)
}
if !caughtUp {
log.Info("catching up to last validated block", "target", valInfo.GlobalState)
return nil, false, nil
}
if err := v.updateBlockValidatorModuleRoot(ctx); err != nil {
return nil, false, fmt.Errorf("error updating block validator module root: %w", err)
}
wasmRootValid := false
for _, root := range valInfo.WasmRoots {
if v.lastWasmModuleRoot == root {
wasmRootValid = true
break
}
}
if !wasmRootValid {
if !stakerConfig.Dangerous.IgnoreRollupWasmModuleRoot {
if len(valInfo.WasmRoots) == 0 {
return nil, false, fmt.Errorf("block validation is still pending")
}
return nil, false, fmt.Errorf(
"wasmroot doesn't match rollup : %v, valid: %v",
v.lastWasmModuleRoot, valInfo.WasmRoots,
)
}
log.Warn("wasmroot doesn't match rollup", "rollup", v.lastWasmModuleRoot, "blockValidator", valInfo.WasmRoots)
}
} else {
validatedCount, err = v.txStreamer.GetProcessedMessageCount()
if err != nil || validatedCount == 0 {
return nil, false, err
}
var batchNum uint64
messageCount, err := v.inboxTracker.GetBatchMessageCount(localBatchCount - 1)
if err != nil {
return nil, false, fmt.Errorf("error getting latest batch %v message count: %w", localBatchCount-1, err)
}
if validatedCount >= messageCount {
batchNum = localBatchCount - 1
validatedCount = messageCount
} else {
var found bool
batchNum, found, err = v.inboxTracker.FindInboxBatchContainingMessage(validatedCount - 1)
if err != nil {
return nil, false, err
}
if !found {
return nil, false, errors.New("batch not found on L1")
}
}
execResult, err := v.txStreamer.ResultAtCount(validatedCount)
if err != nil {
return nil, false, err
}
_, gsPos, err := GlobalStatePositionsAtCount(v.inboxTracker, validatedCount, batchNum)
if err != nil {
return nil, false, fmt.Errorf("%w: failed calculating GSposition for count %d", err, validatedCount)
}
validatedGlobalState = buildGlobalState(*execResult, gsPos)
}
currentL1BlockNum, err := v.client.BlockNumber(ctx)
if err != nil {
return nil, false, fmt.Errorf("error getting latest L1 block number: %w", err)
}
l1BlockNumber, err := arbutil.CorrespondingL1BlockNumber(ctx, v.client, currentL1BlockNum)
if err != nil {
return nil, false, err
}
minAssertionPeriod, err := v.rollup.MinimumAssertionPeriod(v.getCallOpts(ctx))
if err != nil {
return nil, false, fmt.Errorf("error getting rollup minimum assertion period: %w", err)
}
// #nosec G115
timeSinceProposed := big.NewInt(int64(l1BlockNumber) - int64(startStateProposedL1))
if timeSinceProposed.Cmp(minAssertionPeriod) < 0 {
// Too soon to assert
return nil, false, nil
}
successorNodes, err := v.rollup.LookupNodeChildren(ctx, stakerInfo.LatestStakedNode, stakerConfig.LogQueryBatchSize, stakerInfo.LatestStakedNodeHash)
if err != nil {
return nil, false, fmt.Errorf("error looking up node %v (hash %v) children: %w", stakerInfo.LatestStakedNode, stakerInfo.LatestStakedNodeHash, err)
}
var correctNode nodeAction
wrongNodesExist := false
if len(successorNodes) > 0 {
log.Info("examining existing potential successors", "count", len(successorNodes))
}
for _, nd := range successorNodes {
if correctNode != nil && wrongNodesExist {
// We've found everything we could hope to find
break
}
if correctNode != nil {
log.Error("found younger sibling to correct assertion (implicitly invalid)", "node", nd.NodeNum)
wrongNodesExist = true
continue
}
afterGS := nd.AfterState().GlobalState
requiredBatch := afterGS.Batch
if afterGS.PosInBatch == 0 && afterGS.Batch > 0 {
requiredBatch -= 1
}
if localBatchCount <= requiredBatch {
log.Info("staker: waiting for node to catch up to assertion batch", "current", localBatchCount, "target", requiredBatch-1)
return nil, false, nil
}
nodeBatchMsgCount, err := v.inboxTracker.GetBatchMessageCount(requiredBatch)
if err != nil {
return nil, false, err
}
if validatedCount < nodeBatchMsgCount {
log.Info("staker: waiting for validator to catch up to assertion batch messages", "current", validatedCount, "target", nodeBatchMsgCount)
return nil, false, nil
}
if nd.Assertion.AfterState.MachineStatus != validator.MachineStatusFinished {
wrongNodesExist = true
log.Error("Found incorrect assertion: Machine status not finished", "node", nd.NodeNum, "machineStatus", nd.Assertion.AfterState.MachineStatus)
continue
}
caughtUp, nodeMsgCount, err := GlobalStateToMsgCount(v.inboxTracker, v.txStreamer, afterGS)
if errors.Is(err, ErrGlobalStateNotInChain) {
wrongNodesExist = true
log.Error("Found incorrect assertion", "node", nd.NodeNum, "afterGS", afterGS, "err", err)
continue
}
if err != nil {
return nil, false, fmt.Errorf("error getting message number from global state: %w", err)
}
if !caughtUp {
return nil, false, fmt.Errorf("unexpected no-caught-up parsing assertion. Current: %d target: %v", validatedCount, afterGS)
}
log.Info(
"found correct assertion",
"node", nd.NodeNum,
"count", nodeMsgCount,
"blockHash", afterGS.BlockHash,
)
correctNode = existingNodeAction{
number: nd.NodeNum,
hash: nd.NodeHash,
}
}
if correctNode != nil || strategy == WatchtowerStrategy {
return correctNode, wrongNodesExist, nil
}
makeAssertionInterval := stakerConfig.MakeAssertionInterval
if wrongNodesExist || (strategy >= MakeNodesStrategy && time.Since(startStateProposedTime) >= makeAssertionInterval) {
// There's no correct node; create one.
var lastNodeHashIfExists *common.Hash
if len(successorNodes) > 0 {
lastNodeHashIfExists = &successorNodes[len(successorNodes)-1].NodeHash
}
action, err := v.createNewNodeAction(ctx, stakerInfo, prevInboxMaxCount, startCount, startState, validatedCount, validatedGlobalState, lastNodeHashIfExists)
if err != nil {
return nil, wrongNodesExist, fmt.Errorf("error generating create new node action (from pos %d to %d): %w", startCount, validatedCount, err)
}
return action, wrongNodesExist, nil
}
return nil, wrongNodesExist, nil
}
func (v *L1Validator) createNewNodeAction(
ctx context.Context,
stakerInfo *OurStakerInfo,
prevInboxMaxCount *big.Int,
startCount arbutil.MessageIndex,
startState *validator.ExecutionState,
validatedCount arbutil.MessageIndex,
validatedGS validator.GoGlobalState,
lastNodeHashIfExists *common.Hash,
) (nodeAction, error) {
if !prevInboxMaxCount.IsUint64() {
return nil, fmt.Errorf("inbox max count %v isn't a uint64", prevInboxMaxCount)
}
if validatedCount <= startCount {
// we haven't validated any new blocks
return nil, nil
}
if validatedGS.Batch < prevInboxMaxCount.Uint64() {
// didn't validate enough batches
log.Info("staker: not enough batches validated to create new assertion", "validated.Batch", validatedGS.Batch, "posInBatch", validatedGS.PosInBatch, "required batch", prevInboxMaxCount)
return nil, nil
}
batchValidated := validatedGS.Batch
if validatedGS.PosInBatch == 0 {
batchValidated--
}
validatedBatchAcc, err := v.inboxTracker.GetBatchAcc(batchValidated)
if err != nil {
return nil, fmt.Errorf("error getting batch %v accumulator: %w", batchValidated, err)
}
hasSiblingByte := [1]byte{0}
prevNum := stakerInfo.LatestStakedNode
lastHash := stakerInfo.LatestStakedNodeHash
if lastNodeHashIfExists != nil {
lastHash = *lastNodeHashIfExists
hasSiblingByte[0] = 1
}
assertionNumBlocks := uint64(validatedCount - startCount)
assertion := &Assertion{
BeforeState: startState,
AfterState: &validator.ExecutionState{
GlobalState: validatedGS,
MachineStatus: validator.MachineStatusFinished,
},
NumBlocks: assertionNumBlocks,
}
wasmModuleRoot := v.lastWasmModuleRoot
if v.blockValidator == nil {
wasmModuleRoot, err = v.rollup.WasmModuleRoot(v.getCallOpts(ctx))
if err != nil {
return nil, fmt.Errorf("error rollup wasm module root: %w", err)
}
}
executionHash := assertion.ExecutionHash()
newNodeHash := crypto.Keccak256Hash(hasSiblingByte[:], lastHash[:], executionHash[:], validatedBatchAcc[:], wasmModuleRoot[:])
action := createNodeAction{
assertion: assertion,
hash: newNodeHash,
prevInboxMaxCount: prevInboxMaxCount,
}
log.Info("creating node", "hash", newNodeHash, "lastNode", prevNum, "parentNode", stakerInfo.LatestStakedNode)
return action, nil
}
// Returns (execution state, inbox max count, L1 block proposed, parent chain block proposed, error)
func lookupNodeStartState(ctx context.Context, rollup *RollupWatcher, nodeNum uint64, nodeHash common.Hash) (*validator.ExecutionState, *big.Int, uint64, uint64, error) {
if nodeNum == 0 {
creationEvent, err := rollup.LookupCreation(ctx)
if err != nil {
return nil, nil, 0, 0, fmt.Errorf("error looking up rollup creation event: %w", err)
}
l1BlockNumber, err := arbutil.CorrespondingL1BlockNumber(ctx, rollup.client, creationEvent.Raw.BlockNumber)
if err != nil {
return nil, nil, 0, 0, err
}
return &validator.ExecutionState{
GlobalState: validator.GoGlobalState{},
MachineStatus: validator.MachineStatusFinished,
}, big.NewInt(1), l1BlockNumber, creationEvent.Raw.BlockNumber, nil
}
node, err := rollup.LookupNode(ctx, nodeNum)
if err != nil {
return nil, nil, 0, 0, err
}
if node.NodeHash != nodeHash {
return nil, nil, 0, 0, errors.New("looked up starting node but found wrong hash")
}
return node.AfterState(), node.InboxMaxCount, node.L1BlockProposed, node.ParentChainBlockProposed, nil
}