diff --git a/node/db/keys.go b/node/db/keys.go index 6bb7494bf..4bb1fcfa0 100644 --- a/node/db/keys.go +++ b/node/db/keys.go @@ -9,6 +9,10 @@ var ( derivationL1HeightKey = []byte("LastDerivationL1Height") derivationL1BlockPrefix = []byte("derivL1Block") + // derivationBatchesKey holds the RLP list of recently derived batches + // (see DerivationBatch). A single key, not a prefix: the list only spans + // --derivation.batch-retention-blocks L2 blocks, i.e. a handful of entries. + derivationBatchesKey = []byte("DerivationBatches") ) // encodeBlockNumber encodes an L1 enqueue index as big endian uint64 diff --git a/node/db/store.go b/node/db/store.go index 3ff1a32b4..7295b662a 100644 --- a/node/db/store.go +++ b/node/db/store.go @@ -224,6 +224,59 @@ func (s *Store) DeleteDerivationL1BlocksFrom(height uint64) { } } +// DerivationBatch records where a derived batch sits on L1 and which L2 blocks +// it covers. Derivation keeps the most recent ones so that, when the L2 +// execution client comes back with a head below what was already derived (it +// acknowledges blocks before they are durable, so an unclean stop drops its +// in-memory tail), the L1 cursor can be rewound to the batch holding the first +// missing block and that batch derived again. +type DerivationBatch struct { + L1BlockNumber uint64 + BatchIndex uint64 + FirstBlockNumber uint64 + LastBlockNumber uint64 +} + +// ReadDerivationBatches returns the retained batch records, oldest first. +func (s *Store) ReadDerivationBatches() []*DerivationBatch { + data, err := s.db.Get(derivationBatchesKey) + if err != nil && !isNotFoundErr(err) { + panic(fmt.Sprintf("failed to read derivation batches, err: %v", err)) + } + if len(data) == 0 { + return nil + } + var batches []*DerivationBatch + if err := rlp.DecodeBytes(data, &batches); err != nil { + panic(fmt.Sprintf("invalid derivation batches RLP, err: %v", err)) + } + return batches +} + +// WriteDerivationProgress atomically replaces the retained batch records and +// moves the derivation L1 cursor. The two must never be observed apart: a +// cursor that passed a batch whose record is missing leaves nothing to rewind +// to when the execution client loses that batch's blocks. +func (s *Store) WriteDerivationProgress(l1Height uint64, batches []*DerivationBatch) { + if batches == nil { + batches = []*DerivationBatch{} + } + data, err := rlp.EncodeToBytes(batches) + if err != nil { + panic(fmt.Sprintf("failed to RLP encode derivation batches, err: %v", err)) + } + batch := s.db.NewBatch() + if err := batch.Put(derivationBatchesKey, data); err != nil { + panic(fmt.Sprintf("failed to store derivation batches, err: %v", err)) + } + if err := batch.Put(derivationL1HeightKey, new(big.Int).SetUint64(l1Height).Bytes()); err != nil { + panic(fmt.Sprintf("failed to update derivation synced L1 height, err: %v", err)) + } + if err := batch.Write(); err != nil { + panic(fmt.Sprintf("failed to write derivation progress, err: %v", err)) + } +} + func isNotFoundErr(err error) bool { return err.Error() == leveldb.ErrNotFound.Error() || err.Error() == types.ErrMemoryDBNotFound.Error() } diff --git a/node/db/store_test.go b/node/db/store_test.go index 5dd84e0c1..b2cd559d7 100644 --- a/node/db/store_test.go +++ b/node/db/store_test.go @@ -54,3 +54,26 @@ func TestSyncedL1Messages(t *testing.T) { msg = db.ReadL1MessageByIndex(200) require.Nil(t, msg) } + +func TestDerivationProgress(t *testing.T) { + db := NewMemoryStore() + require.Nil(t, db.ReadDerivationBatches()) + + batches := []*DerivationBatch{ + {L1BlockNumber: 10, BatchIndex: 1, FirstBlockNumber: 1, LastBlockNumber: 50}, + {L1BlockNumber: 20, BatchIndex: 2, FirstBlockNumber: 51, LastBlockNumber: 100}, + } + db.WriteDerivationProgress(25, batches) + require.EqualValues(t, 25, *db.ReadLatestDerivationL1Height()) + require.Equal(t, batches, db.ReadDerivationBatches()) + + // The records are replaced, not appended, and an empty list round-trips. + db.WriteDerivationProgress(9, nil) + require.EqualValues(t, 9, *db.ReadLatestDerivationL1Height()) + require.Empty(t, db.ReadDerivationBatches()) + + // Moving the cursor alone leaves the records in place. + db.WriteDerivationProgress(25, batches[:1]) + db.WriteLatestDerivationL1Height(30) + require.Equal(t, batches[:1], db.ReadDerivationBatches()) +} diff --git a/node/derivation/config.go b/node/derivation/config.go index a3f194ba8..6e9ebaa67 100644 --- a/node/derivation/config.go +++ b/node/derivation/config.go @@ -48,6 +48,16 @@ const ( // configured below finalized. DefaultReorgCheckDepth = uint64(64) + // DefaultBatchRetentionBlocks is how many of the most recently derived L2 + // blocks stay covered by retained batch records (see l2_block_loss.go). + // It has to exceed what the execution client can lose on an unclean stop. + // morph-reth acknowledges a block before persisting it and, with its + // default engine settings (memory-block-buffer-target 5, + // persistence-backpressure-threshold 16), holds at most ~21 blocks in + // memory only; 128 leaves ample margin. Deployments that raise those reth + // settings must raise --derivation.batch-retention-blocks with them. + DefaultBatchRetentionBlocks = uint64(128) + // DefaultConfirmations: rationale lives on the L1.Confirmations field // in DefaultConfig() — fixed-depth (latest-N) paired with the SPEC-005 // §4.7.6 reorg detector, not a chain tag. @@ -81,7 +91,11 @@ type Config struct { FetchBlockRange uint64 `json:"fetch_block_range"` VerifyMode string `json:"verify_mode"` ReorgCheckDepth uint64 `json:"reorg_check_depth"` - MetricsPort uint64 `json:"metrics_port"` + BatchRetentionBlocks uint64 `json:"batch_retention_blocks"` + // ResetL1Height, when non-zero, overwrites the persisted derivation L1 + // cursor at startup (--derivation.reset-l1-height). Zero leaves it alone. + ResetL1Height uint64 `json:"reset_l1_height,omitempty"` + MetricsPort uint64 `json:"metrics_port"` } // BeaconRpcList splits the configured beacon RPC endpoint(s) on commas and @@ -115,12 +129,13 @@ func DefaultConfig() *Config { // --derivation.confirmations=-4 (safe) or -3 (finalized) explicitly. Confirmations: DefaultConfirmations, }, - PollInterval: DefaultPollInterval, - LogProgressInterval: DefaultLogProgressInterval, - FetchBlockRange: DefaultFetchBlockRange, - VerifyMode: DefaultVerifyMode, - ReorgCheckDepth: DefaultReorgCheckDepth, - L2: new(types.L2Config), + PollInterval: DefaultPollInterval, + LogProgressInterval: DefaultLogProgressInterval, + FetchBlockRange: DefaultFetchBlockRange, + VerifyMode: DefaultVerifyMode, + ReorgCheckDepth: DefaultReorgCheckDepth, + BatchRetentionBlocks: DefaultBatchRetentionBlocks, + L2: new(types.L2Config), } } @@ -211,6 +226,17 @@ func (c *Config) SetCliContext(ctx *cli.Context) error { c.ReorgCheckDepth = DefaultReorgCheckDepth } + if ctx.GlobalIsSet(flags.DerivationBatchRetentionBlocks.Name) { + c.BatchRetentionBlocks = ctx.GlobalUint64(flags.DerivationBatchRetentionBlocks.Name) + } + if c.BatchRetentionBlocks == 0 { + c.BatchRetentionBlocks = DefaultBatchRetentionBlocks + } + + if ctx.GlobalIsSet(flags.DerivationResetL1Height.Name) { + c.ResetL1Height = ctx.GlobalUint64(flags.DerivationResetL1Height.Name) + } + l2EthAddr := ctx.GlobalString(flags.L2EthAddr.Name) l2EngineAddr := ctx.GlobalString(flags.L2EngineAddr.Name) fileName := ctx.GlobalString(flags.L2EngineJWTSecret.Name) diff --git a/node/derivation/config_test.go b/node/derivation/config_test.go index 4148c0c96..850fbc608 100644 --- a/node/derivation/config_test.go +++ b/node/derivation/config_test.go @@ -116,6 +116,50 @@ func TestMetricsPort_RejectsOutOfRange(t *testing.T) { } } +func TestBatchRetentionBlocks(t *testing.T) { + for _, test := range []struct { + name string + values map[string]string + want uint64 + }{ + {name: "unset uses the default", want: DefaultBatchRetentionBlocks}, + {name: "explicit value", values: map[string]string{flags.DerivationBatchRetentionBlocks.Name: "600"}, want: 600}, + {name: "zero falls back to the default", values: map[string]string{flags.DerivationBatchRetentionBlocks.Name: "0"}, want: DefaultBatchRetentionBlocks}, + } { + t.Run(test.name, func(t *testing.T) { + cfg := DefaultConfig() + if err := cfg.SetCliContext(newVerifyModeTestContext(t, test.values)); err != nil { + t.Fatalf("SetCliContext: %v", err) + } + if cfg.BatchRetentionBlocks != test.want { + t.Fatalf("BatchRetentionBlocks = %d, want %d", cfg.BatchRetentionBlocks, test.want) + } + }) + } +} + +func TestResetL1Height(t *testing.T) { + for _, test := range []struct { + name string + values map[string]string + want uint64 + }{ + {name: "unset", want: 0}, + {name: "zero is the same as unset", values: map[string]string{flags.DerivationResetL1Height.Name: "0"}, want: 0}, + {name: "explicit height", values: map[string]string{flags.DerivationResetL1Height.Name: "4078920"}, want: 4078920}, + } { + t.Run(test.name, func(t *testing.T) { + cfg := DefaultConfig() + if err := cfg.SetCliContext(newVerifyModeTestContext(t, test.values)); err != nil { + t.Fatalf("SetCliContext: %v", err) + } + if cfg.ResetL1Height != test.want { + t.Fatalf("ResetL1Height = %d, want %d", cfg.ResetL1Height, test.want) + } + }) + } +} + func TestBeaconRpcList(t *testing.T) { for _, tc := range []struct { name string @@ -153,6 +197,8 @@ func newVerifyModeTestContext(t *testing.T, values map[string]string) *cli.Conte flags.LegacyValidatorMode, flags.DerivationVerifyMode, flags.MetricsPort, + flags.DerivationBatchRetentionBlocks, + flags.DerivationResetL1Height, flags.L1BeaconAddr, flags.L2EngineJWTSecret, } { diff --git a/node/derivation/database.go b/node/derivation/database.go index 134c83890..78961b81b 100644 --- a/node/derivation/database.go +++ b/node/derivation/database.go @@ -16,6 +16,9 @@ type Reader interface { // ReadDerivationL1BlockRange returns saved L1 block records in [from, to] // inclusive. Used by SPEC-005 §4.7.6 reorg detection. ReadDerivationL1BlockRange(from, to uint64) []*db.DerivationL1Block + // ReadDerivationBatches returns the retained records of recently derived + // batches, oldest first. Used to recover from L2 block loss. + ReadDerivationBatches() []*db.DerivationBatch } type Writer interface { @@ -26,4 +29,7 @@ type Writer interface { // DeleteDerivationL1BlocksFrom drops saved L1 block records at height >= // height; used after a reorg is detected to clear stale hashes. DeleteDerivationL1BlocksFrom(height uint64) + // WriteDerivationProgress atomically replaces the retained batch records + // and moves the derivation L1 cursor. + WriteDerivationProgress(l1Height uint64, batches []*db.DerivationBatch) } diff --git a/node/derivation/derivation.go b/node/derivation/derivation.go index 00d9972aa..df54fc76e 100644 --- a/node/derivation/derivation.go +++ b/node/derivation/derivation.go @@ -25,6 +25,7 @@ import ( "morph-l2/bindings/bindings" "morph-l2/bindings/predeploys" nodecommon "morph-l2/node/common" + "morph-l2/node/db" "morph-l2/node/sync" "morph-l2/node/types" ) @@ -64,6 +65,9 @@ type Derivation struct { logProgressInterval time.Duration verifyMode string // SPEC-005 section 4.2: "layer1" or "local" (default); bound at startup, never switches. reorgCheckDepth uint64 // SPEC-005 section 4.7.6: how far back to scan for L1 hash divergence each poll. + // batchRetentionBlocks is how many of the most recently derived L2 blocks + // stay covered by retained batch records; see l2_block_loss.go. + batchRetentionBlocks uint64 // lastObservedL2Latest caches the L2 head observed at the previous // derivationBlock pull, used by the Path B entry-point dispatcher @@ -156,12 +160,15 @@ func NewDerivationClient(ctx context.Context, cfg *Config, syncer *sync.Syncer, logProgressInterval: cfg.LogProgressInterval, verifyMode: cfg.VerifyMode, reorgCheckDepth: cfg.ReorgCheckDepth, + batchRetentionBlocks: cfg.BatchRetentionBlocks, tagAdvancer: tagAdv, metrics: metrics, l1BeaconClient: l1BeaconClient, L2ToL1MessagePasser: msgPasser, } + resetDerivationCursor(db, logger, cfg.ResetL1Height) + // First-run startHeight default: when DB has no derivation cursor and no // startHeight was configured (CLI/env or network preset), pin to the // latest L1 confirmed block via the same path derivationBlock uses, so @@ -191,6 +198,26 @@ func NewDerivationClient(ctx context.Context, cfg *Config, syncer *sync.Syncer, return d, nil } +// resetDerivationCursor applies --derivation.reset-l1-height: it overwrites +// the persisted L1 cursor before derivation starts, so the first poll scans +// from resetTo+1. This is the manual way out when the execution client is +// behind the cursor by more than the retained batch records cover. Nothing +// else is touched; re-derivation skips the blocks the execution client has. +// Zero means the flag is not set. +func resetDerivationCursor(db Database, logger tmlog.Logger, resetTo uint64) { + if resetTo == 0 { + return + } + var previous any = "unset" + if cursor := db.ReadLatestDerivationL1Height(); cursor != nil { + previous = *cursor + } + db.WriteLatestDerivationL1Height(resetTo) + logger.Error("derivation L1 cursor reset by --derivation.reset-l1-height; "+ + "remove the flag now, otherwise every restart resets the cursor again", + "previous", previous, "cursor", resetTo) +} + func (d *Derivation) Start() { // Single-goroutine design: the SPEC-005 finalizer step runs at the end // of each derivationBlock iteration (see finalizer.go::finalizerTick). @@ -300,6 +327,16 @@ func (d *Derivation) derivationBlock(ctx context.Context) { l2Grew := currentL2Latest > d.lastObservedL2Latest d.lastObservedL2Latest = currentL2Latest + // Layer1 mode has no second block source, so an execution client that + // came back below the derived head must be caught here, before the next + // batch fails to connect. Local mode backfills missing blocks over P2P. + if d.verifyMode == VerifyModeLayer1 && d.recoverL2BlockLoss(currentL2Latest) { + return + } + + // Batches derived in this poll, recorded together with the cursor advance. + var derivedBatches []*db.DerivationBatch + for _, lg := range logs { var ( batchInfo *BatchInfo @@ -469,6 +506,12 @@ func (d *Derivation) derivationBlock(ctx context.Context) { return } d.logger.Info("batch derivation complete", "batch_index", batchInfo.batchIndex, "currentBatchEndBlock", lastHeader.Number.Uint64()) + derivedBatches = append(derivedBatches, &db.DerivationBatch{ + L1BlockNumber: batchInfo.l1BlockNumber, + BatchIndex: batchInfo.batchIndex, + FirstBlockNumber: batchInfo.firstBlockNumber, + LastBlockNumber: batchInfo.lastBlockNumber, + }) d.metrics.SetL2DeriveHeight(lastHeader.Number.Uint64()) d.metrics.SetSyncedBatchIndex(batchInfo.batchIndex) default: @@ -518,7 +561,7 @@ func (d *Derivation) derivationBlock(ctx context.Context) { return } - d.db.WriteLatestDerivationL1Height(end) + d.commitProgress(end, derivedBatches) d.metrics.SetL1SyncHeight(end) d.logger.Info("write latest derivation l1 height success", "l1BlockNumber", end) } diff --git a/node/derivation/l2_block_loss.go b/node/derivation/l2_block_loss.go new file mode 100644 index 000000000..2e77f71f4 --- /dev/null +++ b/node/derivation/l2_block_loss.go @@ -0,0 +1,131 @@ +package derivation + +import ( + "morph-l2/node/db" +) + +// The L2 execution client acknowledges NewSafeL2Block before the block is +// durable: morph-reth keeps the newest blocks in memory and only flushes them +// on a threshold or a graceful shutdown. After an unclean stop it comes back +// with a head below what derivation already applied, while the L1 cursor in +// node-data has moved past the batch holding the lost blocks. In layer1 mode +// L1 is the only block source, so the next batch can never connect. +// +// To recover, derivation keeps a record of the most recently derived batches +// (committed atomically with the cursor) and, at the start of each poll, +// compares the execution client's head against them. A head below the newest +// recorded batch means blocks were lost: the cursor is rewound to the batch +// holding the first missing block, and the normal path derives it again +// (derive() skips the blocks that survived). +// +// The records are a best-effort backup, not a source of truth: they only ever +// trigger a rewind they can fully carry out. When they cannot (the loss is +// older than the retained records, or the batch lies below startHeight), the +// check logs and steps aside, and the poll proceeds exactly as it would +// without it, so an operator rewinding the L1 cursor by hand works as before. + +// mergeDerivationBatches appends the batches derived in this poll to the +// retained records and trims the result to the retention window. +// +// An added batch replaces every existing record that reaches into its L2 +// range, so re-deriving a batch (after a rewind, or an L1 reorg that moved its +// commit tx to another L1 block) never leaves two records for the same blocks. +// Trimming walks back from the newest record and stops at the first one that +// brings the covered block count above retentionBlocks; older ones are dropped. +func mergeDerivationBatches(existing, added []*db.DerivationBatch, retentionBlocks uint64) []*db.DerivationBatch { + merged := existing + for _, batch := range added { + keep := len(merged) + for keep > 0 && merged[keep-1].LastBlockNumber >= batch.FirstBlockNumber { + keep-- + } + merged = append(merged[:keep:keep], batch) + } + + var covered uint64 + for i := len(merged) - 1; i >= 0; i-- { + covered += merged[i].LastBlockNumber - merged[i].FirstBlockNumber + 1 + if covered > retentionBlocks { + return merged[i:] + } + } + return merged +} + +// findDerivationBatch returns the record whose L2 range contains blockNumber, +// or nil when no retained record covers it. +func findDerivationBatch(batches []*db.DerivationBatch, blockNumber uint64) *db.DerivationBatch { + for _, batch := range batches { + if batch.FirstBlockNumber <= blockNumber && blockNumber <= batch.LastBlockNumber { + return batch + } + } + return nil +} + +// commitProgress advances the L1 cursor to l1Height, recording the batches +// derived in this poll in the same write. +func (d *Derivation) commitProgress(l1Height uint64, derived []*db.DerivationBatch) { + if len(derived) == 0 { + d.db.WriteLatestDerivationL1Height(l1Height) + return + } + batches := mergeDerivationBatches(d.db.ReadDerivationBatches(), derived, d.batchRetentionBlocks) + d.db.WriteDerivationProgress(l1Height, batches) +} + +// recoverL2BlockLoss checks whether the execution client's head fell below the +// blocks derivation already applied and, if so, rewinds the L1 cursor so the +// missing blocks are derived again. It returns true only when it rewound the +// cursor, so the current poll must stop and the next one re-derives from the +// new cursor. In every other case it returns false and leaves the poll alone. +func (d *Derivation) recoverL2BlockLoss(l2Latest uint64) bool { + batches := d.db.ReadDerivationBatches() + if len(batches) == 0 { + return false + } + derivedHead := batches[len(batches)-1].LastBlockNumber + if l2Latest >= derivedHead { + return false + } + + firstMissing := l2Latest + 1 + batch := findDerivationBatch(batches, firstMissing) + if batch == nil { + d.logger.Error("L2 execution client lost more blocks than the retained batch records cover; "+ + "automatic recovery skipped. Restart once with --derivation.reset-l1-height set below the L1 block of the batch "+ + "holding block l2Latest+1", + "l2Latest", l2Latest, + "derivedHead", derivedHead, + "oldestRecoverableBlock", batches[0].FirstBlockNumber, + "batchRetentionBlocks", d.batchRetentionBlocks) + return false + } + + // rewindAndReset never goes below startHeight, so a batch under it cannot + // be re-derived this way; rewinding would only repeat on every poll. + if batch.L1BlockNumber < d.startHeight { + d.logger.Error("batch holding the first missing L2 block lies below derivation startHeight; "+ + "automatic recovery skipped", + "l2Latest", l2Latest, + "batchIndex", batch.BatchIndex, + "batchL1Height", batch.L1BlockNumber, + "startHeight", d.startHeight) + return false + } + + // The cursor is already at or before this batch (e.g. an operator moved it + // back by hand): the poll re-fetches the batch without any rewind. + if cursor := d.db.ReadLatestDerivationL1Height(); cursor == nil || *cursor < batch.L1BlockNumber { + return false + } + + d.logger.Error("L2 execution client head is behind the derived batches; rewinding the L1 cursor to derive the missing blocks again", + "l2Latest", l2Latest, + "derivedHead", derivedHead, + "missingBlocks", derivedHead-l2Latest, + "batchIndex", batch.BatchIndex, + "rewindToL1Height", batch.L1BlockNumber) + d.rewindAndReset(batch.L1BlockNumber) + return true +} diff --git a/node/derivation/l2_block_loss_test.go b/node/derivation/l2_block_loss_test.go new file mode 100644 index 000000000..5a123f743 --- /dev/null +++ b/node/derivation/l2_block_loss_test.go @@ -0,0 +1,231 @@ +package derivation + +import ( + "context" + "testing" + + "github.com/stretchr/testify/require" + tmlog "github.com/tendermint/tendermint/libs/log" + + nodedb "morph-l2/node/db" +) + +func testBatch(l1Block, index, first, last uint64) *nodedb.DerivationBatch { + return &nodedb.DerivationBatch{L1BlockNumber: l1Block, BatchIndex: index, FirstBlockNumber: first, LastBlockNumber: last} +} + +func TestMergeDerivationBatches(t *testing.T) { + t.Run("keeps batches until the covered blocks exceed retention", func(t *testing.T) { + existing := []*nodedb.DerivationBatch{ + testBatch(10, 1, 1, 50), + testBatch(20, 2, 51, 100), + testBatch(30, 3, 101, 150), + } + added := []*nodedb.DerivationBatch{testBatch(40, 4, 151, 200)} + + // 50 (batch 4) + 50 (batch 3) = 100 is not above 128; batch 2 brings it + // to 150 and is the last one kept. + got := mergeDerivationBatches(existing, added, 128) + require.Equal(t, []*nodedb.DerivationBatch{existing[1], existing[2], added[0]}, got) + }) + + t.Run("a single batch larger than retention is kept alone", func(t *testing.T) { + existing := []*nodedb.DerivationBatch{testBatch(10, 1, 1, 100)} + added := []*nodedb.DerivationBatch{testBatch(20, 2, 101, 413)} + + got := mergeDerivationBatches(existing, added, 128) + require.Equal(t, added, got) + }) + + t.Run("a re-derived batch replaces the records reaching into its range", func(t *testing.T) { + existing := []*nodedb.DerivationBatch{ + testBatch(10, 1, 1, 50), + testBatch(20, 2, 51, 100), + testBatch(30, 3, 101, 150), + } + // Batch 2 re-included at another L1 block after an L1 reorg. + added := []*nodedb.DerivationBatch{testBatch(25, 2, 51, 100)} + + got := mergeDerivationBatches(existing, added, 1000) + require.Equal(t, []*nodedb.DerivationBatch{existing[0], added[0]}, got) + }) + + t.Run("does not modify the existing slice", func(t *testing.T) { + existing := []*nodedb.DerivationBatch{testBatch(10, 1, 1, 50), testBatch(20, 2, 51, 100)} + snapshot := append([]*nodedb.DerivationBatch(nil), existing...) + + mergeDerivationBatches(existing, []*nodedb.DerivationBatch{testBatch(25, 2, 51, 90)}, 1000) + require.Equal(t, snapshot, existing) + }) +} + +func newBlockLossTestDerivation(db *selectorCursorTestDB) *Derivation { + return &Derivation{ + db: db, + logger: tmlog.NewNopLogger(), + metrics: newDiscardMetrics(), + batchRetentionBlocks: DefaultBatchRetentionBlocks, + } +} + +// Numbers from morph-l2/morph#1097: the batch at L1 4,078,921 covers L2 +// 183,891..184,203, the cursor moved on to 4,078,941, and the execution client +// restarted at 184,198. +func TestRecoverL2BlockLoss(t *testing.T) { + const ( + batchL1Block = uint64(4_078_921) + cursor = uint64(4_078_941) + derivedHead = uint64(184_203) + ) + newDB := func() *selectorCursorTestDB { + db := newSelectorCursorTestDB() + db.WriteDerivationProgress(cursor, []*nodedb.DerivationBatch{ + testBatch(4_078_800, 99, 183_578, 183_890), + testBatch(batchL1Block, 100, 183_891, derivedHead), + }) + for h := batchL1Block - 2; h <= cursor; h++ { + db.WriteDerivationL1Block(&nodedb.DerivationL1Block{Number: h}) + } + return db + } + + t.Run("no records", func(t *testing.T) { + db := newSelectorCursorTestDB() + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(0)) + require.Nil(t, db.ReadLatestDerivationL1Height()) + }) + + t.Run("head at or above the derived head", func(t *testing.T) { + for _, head := range []uint64{derivedHead, derivedHead + 7} { + db := newDB() + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(head)) + require.Equal(t, cursor, *db.ReadLatestDerivationL1Height()) + require.Len(t, db.batches, 2) + } + }) + + t.Run("lost tail rewinds the cursor to the batch holding the first missing block", func(t *testing.T) { + db := newDB() + require.True(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(184_198)) + + require.Equal(t, batchL1Block-1, *db.ReadLatestDerivationL1Height()) + require.Equal(t, []*nodedb.DerivationBatch{testBatch(4_078_800, 99, 183_578, 183_890)}, db.batches, + "the rewound batch's record is dropped until it is derived again") + require.Contains(t, db.derivationBlocks, batchL1Block-1) + require.NotContains(t, db.derivationBlocks, batchL1Block) + + // The rewound state is consistent: nothing further to recover. + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(184_198)) + }) + + t.Run("loss spanning several batches rewinds to the earliest affected one", func(t *testing.T) { + db := newDB() + require.True(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(183_800)) + + require.Equal(t, uint64(4_078_799), *db.ReadLatestDerivationL1Height()) + require.Empty(t, db.batches) + }) + + t.Run("loss beyond the retained records leaves the poll and the cursor alone", func(t *testing.T) { + db := newDB() + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(183_000)) + + require.Equal(t, cursor, *db.ReadLatestDerivationL1Height()) + require.Len(t, db.batches, 2) + }) + + t.Run("manual cursor rewind after a loss beyond the records is not blocked", func(t *testing.T) { + db := newDB() + db.WriteLatestDerivationL1Height(4_000_000) + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(183_000)) + + require.Equal(t, uint64(4_000_000), *db.ReadLatestDerivationL1Height()) + }) + + t.Run("batch below startHeight is not rewound", func(t *testing.T) { + db := newDB() + d := newBlockLossTestDerivation(db) + d.startHeight = batchL1Block + 1 + for i := 0; i < 2; i++ { + require.False(t, d.recoverL2BlockLoss(184_198)) + require.Equal(t, cursor, *db.ReadLatestDerivationL1Height()) + require.Len(t, db.batches, 2) + } + }) + + t.Run("cursor already before the batch is left alone", func(t *testing.T) { + db := newDB() + db.WriteLatestDerivationL1Height(4_000_000) + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(184_198)) + + require.Equal(t, uint64(4_000_000), *db.ReadLatestDerivationL1Height()) + }) +} + +func TestResetDerivationCursor(t *testing.T) { + db := newSelectorCursorTestDB() + records := []*nodedb.DerivationBatch{testBatch(4_078_921, 100, 183_891, 184_203)} + db.WriteDerivationProgress(4_078_941, records) + + // Zero means the flag is not set: nothing is written. + resetDerivationCursor(db, tmlog.NewNopLogger(), 0) + require.Equal(t, uint64(4_078_941), *db.ReadLatestDerivationL1Height()) + + // Only the cursor moves; the batch records are left as they are. + resetTo := uint64(4_000_000) + resetDerivationCursor(db, tmlog.NewNopLogger(), resetTo) + require.Equal(t, resetTo, *db.ReadLatestDerivationL1Height()) + require.Equal(t, records, db.batches) + + // With the cursor reset, a loss older than the records does not hold up the poll. + require.False(t, newBlockLossTestDerivation(db).recoverL2BlockLoss(183_000)) + require.Equal(t, resetTo, *db.ReadLatestDerivationL1Height()) +} + +func TestCommitProgress(t *testing.T) { + db := newSelectorCursorTestDB() + d := newBlockLossTestDerivation(db) + + d.commitProgress(100, nil) + require.Equal(t, uint64(100), *db.ReadLatestDerivationL1Height()) + require.Empty(t, db.batches) + + d.commitProgress(200, []*nodedb.DerivationBatch{testBatch(150, 1, 1, 100)}) + d.commitProgress(300, []*nodedb.DerivationBatch{testBatch(250, 2, 101, 300)}) + require.Equal(t, uint64(300), *db.ReadLatestDerivationL1Height()) + require.Equal(t, []*nodedb.DerivationBatch{testBatch(250, 2, 101, 300)}, db.batches, + "batch 2 alone covers more than the retention window") + + // A poll without batches moves the cursor and keeps the records. + d.commitProgress(400, nil) + require.Equal(t, uint64(400), *db.ReadLatestDerivationL1Height()) + require.Len(t, db.batches, 1) +} + +// derivationBlock must run the loss check in layer1 mode only: local mode has +// P2P backfill for missing blocks and keeps scanning L1. +func TestDerivationBlockRecoversL2BlockLossInLayer1Only(t *testing.T) { + // The fixture's L2 head is selectorCursorTestL1Height (42); the retained + // batch says blocks up to 100 were already derived. + const batchL1Block = uint64(30) + cursor := selectorCursorTestL1Height - 1 + + for _, test := range []struct { + verifyMode string + wantCursor uint64 + }{ + {verifyMode: VerifyModeLayer1, wantCursor: batchL1Block - 1}, + {verifyMode: VerifyModeLocal, wantCursor: selectorCursorTestL1Height}, + } { + t.Run(test.verifyMode, func(t *testing.T) { + d, db := newSelectorCursorTestDerivation(t, test.verifyMode, []byte{0xde, 0xad, 0xbe, 0xef}) + d.startHeight = 1 + d.batchRetentionBlocks = DefaultBatchRetentionBlocks + db.WriteDerivationProgress(cursor, []*nodedb.DerivationBatch{testBatch(batchL1Block, 7, 1, 100)}) + + d.derivationBlock(context.Background()) + + require.Equal(t, test.wantCursor, *db.ReadLatestDerivationL1Height()) + }) + } +} diff --git a/node/derivation/reorg.go b/node/derivation/reorg.go index 1090cf908..6c2d165fe 100644 --- a/node/derivation/reorg.go +++ b/node/derivation/reorg.go @@ -127,10 +127,23 @@ func (d *Derivation) rewindAndReset(rewindToL1Height uint64) { d.db.DeleteDerivationL1BlocksFrom(rewindToL1Height) + var cursor uint64 if rewindToL1Height > 0 { - d.db.WriteLatestDerivationL1Height(rewindToL1Height - 1) + cursor = rewindToL1Height - 1 + } + // Batch records describe batches the cursor has passed, so the ones at or + // above the rewind point go with it; re-derivation records them again. + // Dropped in the same write as the cursor: a crash in between must not + // leave the cursor ahead of a batch that has no record. + batches := d.db.ReadDerivationBatches() + kept := len(batches) + for kept > 0 && batches[kept-1].L1BlockNumber >= rewindToL1Height { + kept-- + } + if kept < len(batches) { + d.db.WriteDerivationProgress(cursor, batches[:kept]) } else { - d.db.WriteLatestDerivationL1Height(0) + d.db.WriteLatestDerivationL1Height(cursor) } if d.tagAdvancer != nil { diff --git a/node/derivation/selector_cursor_test.go b/node/derivation/selector_cursor_test.go index 3bb16a501..c144c08da 100644 --- a/node/derivation/selector_cursor_test.go +++ b/node/derivation/selector_cursor_test.go @@ -28,6 +28,7 @@ const selectorCursorTestL1Height = uint64(42) type selectorCursorTestDB struct { latestDerivation *uint64 derivationBlocks map[uint64]*nodedb.DerivationL1Block + batches []*nodedb.DerivationBatch } func newSelectorCursorTestDB() *selectorCursorTestDB { @@ -74,6 +75,15 @@ func (db *selectorCursorTestDB) DeleteDerivationL1BlocksFrom(height uint64) { } } +func (db *selectorCursorTestDB) ReadDerivationBatches() []*nodedb.DerivationBatch { + return append([]*nodedb.DerivationBatch(nil), db.batches...) +} + +func (db *selectorCursorTestDB) WriteDerivationProgress(l1Height uint64, batches []*nodedb.DerivationBatch) { + db.batches = append([]*nodedb.DerivationBatch(nil), batches...) + db.WriteLatestDerivationL1Height(l1Height) +} + func (*selectorCursorTestDB) ReadLatestSyncedL1Height() *uint64 { return nil } func (*selectorCursorTestDB) ReadL1MessagesInRange(uint64, uint64) []nodetypes.L1Message { diff --git a/node/flags/flags.go b/node/flags/flags.go index 0685b4a11..9e28a0d27 100644 --- a/node/flags/flags.go +++ b/node/flags/flags.go @@ -328,6 +328,19 @@ var ( EnvVar: prefixEnvVar("DERIVATION_REORG_CHECK_DEPTH"), Value: 64, } + + DerivationBatchRetentionBlocks = cli.Uint64Flag{ + Name: "derivation.batch-retention-blocks", + Usage: "Keep records of the most recently derived batches covering at least this many L2 blocks (layer1 verify mode). When the L2 execution client restarts with a head below what was already derived, derivation rewinds its L1 cursor to the recorded batch holding the first missing block and derives it again. Should exceed the number of blocks the execution client can lose on an unclean stop; a larger loss is not recovered automatically and needs --derivation.reset-l1-height. Default 128.", + EnvVar: prefixEnvVar("DERIVATION_BATCH_RETENTION_BLOCKS"), + Value: 128, + } + + DerivationResetL1Height = cli.Uint64Flag{ + Name: "derivation.reset-l1-height", + Usage: "One-off manual recovery: at startup, overwrite the persisted derivation L1 cursor with this height, so derivation scans L1 again from the next block. Blocks the execution client already has are skipped. Remove the flag after the node has started with it; while it stays set, every restart resets the cursor again. 0 (the default) does nothing.", + EnvVar: prefixEnvVar("DERIVATION_RESET_L1_HEIGHT"), + } // Logger LogLevel = &cli.StringFlag{ Name: "log.level", @@ -420,6 +433,8 @@ var Flags = []cli.Flag{ DerivationConfirmations, DerivationVerifyMode, DerivationReorgCheckDepth, + DerivationBatchRetentionBlocks, + DerivationResetL1Height, L1BeaconAddr, // L1 Sequencer options