Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions node/db/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 53 additions & 0 deletions node/db/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
23 changes: 23 additions & 0 deletions node/db/store_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
40 changes: 33 additions & 7 deletions node/derivation/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
}
}

Expand Down Expand Up @@ -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)
Expand Down
46 changes: 46 additions & 0 deletions node/derivation/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
} {
Expand Down
6 changes: 6 additions & 0 deletions node/derivation/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)
}
45 changes: 44 additions & 1 deletion node/derivation/derivation.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return
}

// Batches derived in this poll, recorded together with the cursor advance.
var derivedBatches []*db.DerivationBatch

for _, lg := range logs {
var (
batchInfo *BatchInfo
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading