From bf4aa0335ac761dc5d86cb1bca2e8cc087cd4024 Mon Sep 17 00:00:00 2001 From: Alonso Rodriguez Date: Tue, 9 Apr 2024 09:23:24 +0200 Subject: [PATCH] Cherrypick/#3544 (#3550) * Feature/#3544 sync block protection (#3545) * SyncBlockProtection parameter * linter * config * Fix unit test * safe mode by default (#3547) * safe mode by default * doc --- config/default.go | 1 + .../environments/local/local.node.config.toml | 1 + docs/config-file/node-config-doc.html | 2 +- docs/config-file/node-config-doc.md | 55 ++++++++++++------- docs/config-file/node-config-schema.json | 5 ++ etherman/etherman.go | 1 - synchronizer/config.go | 2 + synchronizer/synchronizer.go | 30 +++++++++- synchronizer/synchronizer_test.go | 16 ++++-- test/config/test.node.config.toml | 1 + 10 files changed, 87 insertions(+), 27 deletions(-) diff --git a/config/default.go b/config/default.go index 9c57ed62de..a32c1e6f0e 100644 --- a/config/default.go +++ b/config/default.go @@ -102,6 +102,7 @@ EnableHttpLog = true SyncInterval = "1s" SyncChunkSize = 100 TrustedSequencerURL = "" # If it is empty or not specified, then the value is read from the smc +SyncBlockProtection = "safe" # latest, finalized, safe L1SynchronizationMode = "sequential" L1SyncCheckL2BlockHash = true L1SyncCheckL2BlockNumberhModulus = 30 diff --git a/config/environments/local/local.node.config.toml b/config/environments/local/local.node.config.toml index c637c12997..7fdad2a456 100644 --- a/config/environments/local/local.node.config.toml +++ b/config/environments/local/local.node.config.toml @@ -82,6 +82,7 @@ EnableL2SuggestedGasPricePolling = true SyncInterval = "1s" SyncChunkSize = 100 TrustedSequencerURL = "" # If it is empty or not specified, then the value is read from the smc +SyncBlockProtection = "latest" # latest, finalized, safe [Sequencer] DeletePoolTxsL1BlockConfirmations = 100 diff --git a/docs/config-file/node-config-doc.html b/docs/config-file/node-config-doc.html index 9e14733860..e8bd33cba5 100644 --- a/docs/config-file/node-config-doc.html +++ b/docs/config-file/node-config-doc.html @@ -16,7 +16,7 @@
"300ms"
 

Default: 500Type: number

MaxRequestsPerIPAndSecond defines how much requests a single IP can
send within a single second


Default: ""Type: string

SequencerNodeURI is used allow Non-Sequencer nodes
to relay transactions to the Sequencer node


Default: 0Type: integer

MaxCumulativeGasUsed is the max gas allowed per batch


WebSockets configuration
Default: trueType: boolean

Enabled defines if the WebSocket requests are enabled or disabled


Default: "0.0.0.0"Type: string

Host defines the network adapter that will be used to serve the WS requests


Default: 8546Type: integer

Port defines the port to serve the endpoints via WS


Default: 104857600Type: integer

ReadLimit defines the maximum size of a message read from the client (in bytes)


Default: trueType: boolean

EnableL2SuggestedGasPricePolling enables polling of the L2 gas price to block tx in the RPC with lower gas price.


Default: falseType: boolean

BatchRequestsEnabled defines if the Batch requests are enabled or disabled


Default: 20Type: integer

BatchRequestsLimit defines the limit of requests that can be incorporated into each batch request


Type: array of integer

L2Coinbase defines which address is going to receive the fees

Must contain a minimum of 20 items

Must contain a maximum of 20 items

Each item of this array must be:


Default: 10000Type: integer

MaxLogsCount is a configuration to set the max number of logs that can be returned
in a single call to the state, if zero it means no limit


Default: 10000Type: integer

MaxLogsBlockRange is a configuration to set the max range for block number when querying TXs
logs in a single call to the state, if zero it means no limit


Default: 60000Type: integer

MaxNativeBlockHashBlockRange is a configuration to set the max range for block number when querying
native block hashes in a single call to the state, if zero it means no limit


Default: trueType: boolean

EnableHttpLog allows the user to enable or disable the logs related to the HTTP
requests to be captured by the server.


ZKCountersLimits defines the ZK Counter limits
Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Default: 0Type: integer

Configuration of service `Syncrhonizer`. For this service is also really important the value of `IsTrustedSequencer` because depending of this values is going to ask to a trusted node for trusted transactions or not
Default: "1s"Type: string

SyncInterval is the delay interval between reading new rollup information


Examples:

"1m"
 
"300ms"
-

Default: 100Type: integer

SyncChunkSize is the number of blocks to sync on each chunk


Default: ""Type: string

TrustedSequencerURL is the rpc url to connect and sync the trusted state


Default: trueType: boolean

L1SyncCheckL2BlockHash if is true when a batch is closed is force to check L2Block hash against trustedNode (only apply for permissionless)


Default: 30Type: integer

L1SyncCheckL2BlockNumberhModulus is the modulus used to choose the l2block to check
a modules 5, for instance, means check all l2block multiples of 5 (10,15,20,...)


Default: "sequential"Type: enum (of string)

L1SynchronizationMode define how to synchronize with L1:
- parallel: Request data to L1 in parallel, and process sequentially. The advantage is that executor is not blocked waiting for L1 data
- sequential: Request data to L1 and execute

Must be one of:

  • "sequential"
  • "parallel"

L1ParallelSynchronization Configuration for parallel mode (if L1SynchronizationMode equal to 'parallel')
Default: 10Type: integer

MaxClients Number of clients used to synchronize with L1


Default: 25Type: integer

MaxPendingNoProcessedBlocks Size of the buffer used to store rollup information from L1, must be >= to NumberOfEthereumClientsToSync
sugested twice of NumberOfParallelOfEthereumClients


Default: "5s"Type: string

RequestLastBlockPeriod is the time to wait to request the
last block to L1 to known if we need to retrieve more data.
This value only apply when the system is synchronized


Examples:

"1m"
+

Default: 100Type: integer

SyncChunkSize is the number of blocks to sync on each chunk


Default: ""Type: string

TrustedSequencerURL is the rpc url to connect and sync the trusted state


Default: "safe"Type: string

SyncBlockProtection specify the state to sync (lastest, finalized or safe)


Default: trueType: boolean

L1SyncCheckL2BlockHash if is true when a batch is closed is force to check L2Block hash against trustedNode (only apply for permissionless)


Default: 30Type: integer

L1SyncCheckL2BlockNumberhModulus is the modulus used to choose the l2block to check
a modules 5, for instance, means check all l2block multiples of 5 (10,15,20,...)


Default: "sequential"Type: enum (of string)

L1SynchronizationMode define how to synchronize with L1:
- parallel: Request data to L1 in parallel, and process sequentially. The advantage is that executor is not blocked waiting for L1 data
- sequential: Request data to L1 and execute

Must be one of:

  • "sequential"
  • "parallel"

L1ParallelSynchronization Configuration for parallel mode (if L1SynchronizationMode equal to 'parallel')
Default: 10Type: integer

MaxClients Number of clients used to synchronize with L1


Default: 25Type: integer

MaxPendingNoProcessedBlocks Size of the buffer used to store rollup information from L1, must be >= to NumberOfEthereumClientsToSync
sugested twice of NumberOfParallelOfEthereumClients


Default: "5s"Type: string

RequestLastBlockPeriod is the time to wait to request the
last block to L1 to known if we need to retrieve more data.
This value only apply when the system is synchronized


Examples:

"1m"
 
"300ms"
 

Consumer Configuration for the consumer of rollup information from L1
Default: "5s"Type: string

AceptableInacctivityTime is the expected maximum time that the consumer
could wait until new data is produced. If the time is greater it emmit a log to warn about
that. The idea is keep working the consumer as much as possible, so if the producer is not
fast enought then you could increse the number of parallel clients to sync with L1


Examples:

"1m"
 
"300ms"
diff --git a/docs/config-file/node-config-doc.md b/docs/config-file/node-config-doc.md
index 59cba70107..5e746eab55 100644
--- a/docs/config-file/node-config-doc.md
+++ b/docs/config-file/node-config-doc.md
@@ -1339,6 +1339,7 @@ because depending of this values is going to ask to a trusted node for trusted t
 | - [SyncInterval](#Synchronizer_SyncInterval )                                         | No      | string           | No         | -          | Duration                                                                                                                                                                                                                                                |
 | - [SyncChunkSize](#Synchronizer_SyncChunkSize )                                       | No      | integer          | No         | -          | SyncChunkSize is the number of blocks to sync on each chunk                                                                                                                                                                                             |
 | - [TrustedSequencerURL](#Synchronizer_TrustedSequencerURL )                           | No      | string           | No         | -          | TrustedSequencerURL is the rpc url to connect and sync the trusted state                                                                                                                                                                                |
+| - [SyncBlockProtection](#Synchronizer_SyncBlockProtection )                           | No      | string           | No         | -          | SyncBlockProtection specify the state to sync (lastest, finalized or safe)                                                                                                                                                                              |
 | - [L1SyncCheckL2BlockHash](#Synchronizer_L1SyncCheckL2BlockHash )                     | No      | boolean          | No         | -          | L1SyncCheckL2BlockHash if is true when a batch is closed is force to check  L2Block hash against trustedNode (only apply for permissionless)                                                                                                            |
 | - [L1SyncCheckL2BlockNumberhModulus](#Synchronizer_L1SyncCheckL2BlockNumberhModulus ) | No      | integer          | No         | -          | L1SyncCheckL2BlockNumberhModulus is the modulus used to choose the l2block to check
a modules 5, for instance, means check all l2block multiples of 5 (10,15,20,...) | | - [L1SynchronizationMode](#Synchronizer_L1SynchronizationMode ) | No | enum (of string) | No | - | L1SynchronizationMode define how to synchronize with L1:
- parallel: Request data to L1 in parallel, and process sequentially. The advantage is that executor is not blocked waiting for L1 data
- sequential: Request data to L1 and execute | @@ -1399,7 +1400,21 @@ SyncChunkSize=100 TrustedSequencerURL="" ``` -### 9.4. `Synchronizer.L1SyncCheckL2BlockHash` +### 9.4. `Synchronizer.SyncBlockProtection` + +**Type:** : `string` + +**Default:** `"safe"` + +**Description:** SyncBlockProtection specify the state to sync (lastest, finalized or safe) + +**Example setting the default value** ("safe"): +``` +[Synchronizer] +SyncBlockProtection="safe" +``` + +### 9.5. `Synchronizer.L1SyncCheckL2BlockHash` **Type:** : `boolean` @@ -1413,7 +1428,7 @@ TrustedSequencerURL="" L1SyncCheckL2BlockHash=true ``` -### 9.5. `Synchronizer.L1SyncCheckL2BlockNumberhModulus` +### 9.6. `Synchronizer.L1SyncCheckL2BlockNumberhModulus` **Type:** : `integer` @@ -1428,7 +1443,7 @@ a modules 5, for instance, means check all l2block multiples of 5 (10,15,20,...) L1SyncCheckL2BlockNumberhModulus=30 ``` -### 9.6. `Synchronizer.L1SynchronizationMode` +### 9.7. `Synchronizer.L1SynchronizationMode` **Type:** : `enum (of string)` @@ -1448,7 +1463,7 @@ Must be one of: * "sequential" * "parallel" -### 9.7. `[Synchronizer.L1ParallelSynchronization]` +### 9.8. `[Synchronizer.L1ParallelSynchronization]` **Type:** : `object` **Description:** L1ParallelSynchronization Configuration for parallel mode (if L1SynchronizationMode equal to 'parallel') @@ -1466,7 +1481,7 @@ Must be one of: | - [RollupInfoRetriesSpacing](#Synchronizer_L1ParallelSynchronization_RollupInfoRetriesSpacing ) | No | string | No | - | Duration | | - [FallbackToSequentialModeOnSynchronized](#Synchronizer_L1ParallelSynchronization_FallbackToSequentialModeOnSynchronized ) | No | boolean | No | - | FallbackToSequentialModeOnSynchronized if true switch to sequential mode if the system is synchronized | -#### 9.7.1. `Synchronizer.L1ParallelSynchronization.MaxClients` +#### 9.8.1. `Synchronizer.L1ParallelSynchronization.MaxClients` **Type:** : `integer` @@ -1480,7 +1495,7 @@ Must be one of: MaxClients=10 ``` -#### 9.7.2. `Synchronizer.L1ParallelSynchronization.MaxPendingNoProcessedBlocks` +#### 9.8.2. `Synchronizer.L1ParallelSynchronization.MaxPendingNoProcessedBlocks` **Type:** : `integer` @@ -1495,7 +1510,7 @@ sugested twice of NumberOfParallelOfEthereumClients MaxPendingNoProcessedBlocks=25 ``` -#### 9.7.3. `Synchronizer.L1ParallelSynchronization.RequestLastBlockPeriod` +#### 9.8.3. `Synchronizer.L1ParallelSynchronization.RequestLastBlockPeriod` **Title:** Duration @@ -1523,7 +1538,7 @@ This value only apply when the system is synchronized RequestLastBlockPeriod="5s" ``` -#### 9.7.4. `[Synchronizer.L1ParallelSynchronization.PerformanceWarning]` +#### 9.8.4. `[Synchronizer.L1ParallelSynchronization.PerformanceWarning]` **Type:** : `object` **Description:** Consumer Configuration for the consumer of rollup information from L1 @@ -1533,7 +1548,7 @@ RequestLastBlockPeriod="5s" | - [AceptableInacctivityTime](#Synchronizer_L1ParallelSynchronization_PerformanceWarning_AceptableInacctivityTime ) | No | string | No | - | Duration | | - [ApplyAfterNumRollupReceived](#Synchronizer_L1ParallelSynchronization_PerformanceWarning_ApplyAfterNumRollupReceived ) | No | integer | No | - | ApplyAfterNumRollupReceived is the number of iterations to
start checking the time waiting for new rollup info data | -##### 9.7.4.1. `Synchronizer.L1ParallelSynchronization.PerformanceWarning.AceptableInacctivityTime` +##### 9.8.4.1. `Synchronizer.L1ParallelSynchronization.PerformanceWarning.AceptableInacctivityTime` **Title:** Duration @@ -1562,7 +1577,7 @@ fast enought then you could increse the number of parallel clients to sync with AceptableInacctivityTime="5s" ``` -##### 9.7.4.2. `Synchronizer.L1ParallelSynchronization.PerformanceWarning.ApplyAfterNumRollupReceived` +##### 9.8.4.2. `Synchronizer.L1ParallelSynchronization.PerformanceWarning.ApplyAfterNumRollupReceived` **Type:** : `integer` @@ -1577,7 +1592,7 @@ start checking the time waiting for new rollup info data ApplyAfterNumRollupReceived=10 ``` -#### 9.7.5. `Synchronizer.L1ParallelSynchronization.RequestLastBlockTimeout` +#### 9.8.5. `Synchronizer.L1ParallelSynchronization.RequestLastBlockTimeout` **Title:** Duration @@ -1603,7 +1618,7 @@ ApplyAfterNumRollupReceived=10 RequestLastBlockTimeout="5s" ``` -#### 9.7.6. `Synchronizer.L1ParallelSynchronization.RequestLastBlockMaxRetries` +#### 9.8.6. `Synchronizer.L1ParallelSynchronization.RequestLastBlockMaxRetries` **Type:** : `integer` @@ -1617,7 +1632,7 @@ RequestLastBlockTimeout="5s" RequestLastBlockMaxRetries=3 ``` -#### 9.7.7. `Synchronizer.L1ParallelSynchronization.StatisticsPeriod` +#### 9.8.7. `Synchronizer.L1ParallelSynchronization.StatisticsPeriod` **Title:** Duration @@ -1643,7 +1658,7 @@ RequestLastBlockMaxRetries=3 StatisticsPeriod="5m0s" ``` -#### 9.7.8. `Synchronizer.L1ParallelSynchronization.TimeOutMainLoop` +#### 9.8.8. `Synchronizer.L1ParallelSynchronization.TimeOutMainLoop` **Title:** Duration @@ -1669,7 +1684,7 @@ StatisticsPeriod="5m0s" TimeOutMainLoop="5m0s" ``` -#### 9.7.9. `Synchronizer.L1ParallelSynchronization.RollupInfoRetriesSpacing` +#### 9.8.9. `Synchronizer.L1ParallelSynchronization.RollupInfoRetriesSpacing` **Title:** Duration @@ -1695,7 +1710,7 @@ TimeOutMainLoop="5m0s" RollupInfoRetriesSpacing="5s" ``` -#### 9.7.10. `Synchronizer.L1ParallelSynchronization.FallbackToSequentialModeOnSynchronized` +#### 9.8.10. `Synchronizer.L1ParallelSynchronization.FallbackToSequentialModeOnSynchronized` **Type:** : `boolean` @@ -1709,7 +1724,7 @@ RollupInfoRetriesSpacing="5s" FallbackToSequentialModeOnSynchronized=false ``` -### 9.8. `[Synchronizer.L2Synchronization]` +### 9.9. `[Synchronizer.L2Synchronization]` **Type:** : `object` **Description:** L2Synchronization Configuration for L2 synchronization @@ -1720,7 +1735,7 @@ FallbackToSequentialModeOnSynchronized=false | - [ReprocessFullBatchOnClose](#Synchronizer_L2Synchronization_ReprocessFullBatchOnClose ) | No | boolean | No | - | ReprocessFullBatchOnClose if is true when a batch is closed is force to reprocess again | | - [CheckLastL2BlockHashOnCloseBatch](#Synchronizer_L2Synchronization_CheckLastL2BlockHashOnCloseBatch ) | No | boolean | No | - | CheckLastL2BlockHashOnCloseBatch if is true when a batch is closed is force to check the last L2Block hash | -#### 9.8.1. `Synchronizer.L2Synchronization.AcceptEmptyClosedBatches` +#### 9.9.1. `Synchronizer.L2Synchronization.AcceptEmptyClosedBatches` **Type:** : `boolean` @@ -1735,7 +1750,7 @@ if true, the synchronizer will accept empty batches and process them. AcceptEmptyClosedBatches=false ``` -#### 9.8.2. `Synchronizer.L2Synchronization.ReprocessFullBatchOnClose` +#### 9.9.2. `Synchronizer.L2Synchronization.ReprocessFullBatchOnClose` **Type:** : `boolean` @@ -1749,7 +1764,7 @@ AcceptEmptyClosedBatches=false ReprocessFullBatchOnClose=true ``` -#### 9.8.3. `Synchronizer.L2Synchronization.CheckLastL2BlockHashOnCloseBatch` +#### 9.9.3. `Synchronizer.L2Synchronization.CheckLastL2BlockHashOnCloseBatch` **Type:** : `boolean` diff --git a/docs/config-file/node-config-schema.json b/docs/config-file/node-config-schema.json index ec1713372c..cddda1720a 100644 --- a/docs/config-file/node-config-schema.json +++ b/docs/config-file/node-config-schema.json @@ -517,6 +517,11 @@ "description": "TrustedSequencerURL is the rpc url to connect and sync the trusted state", "default": "" }, + "SyncBlockProtection": { + "type": "string", + "description": "SyncBlockProtection specify the state to sync (lastest, finalized or safe)", + "default": "safe" + }, "L1SyncCheckL2BlockHash": { "type": "boolean", "description": "L1SyncCheckL2BlockHash if is true when a batch is closed is force to check L2Block hash against trustedNode (only apply for permissionless)", diff --git a/etherman/etherman.go b/etherman/etherman.go index 97918647a4..c88043a0fc 100644 --- a/etherman/etherman.go +++ b/etherman/etherman.go @@ -1237,7 +1237,6 @@ func (etherMan *Client) forcedBatchEvent(ctx context.Context, vLog types.Log, bl func (etherMan *Client) sequencedBatchesEvent(ctx context.Context, vLog types.Log, blocks *[]Block, blocksOrder *map[common.Hash][]Order) error { log.Debugf("SequenceBatches event detected: txHash: %s", common.Bytes2Hex(vLog.TxHash[:])) - //tx,isPending, err:=etherMan.EthClient.TransactionByHash(ctx, vLog.TxHash) sb, err := etherMan.EtrogZkEVM.ParseSequenceBatches(vLog) if err != nil { diff --git a/synchronizer/config.go b/synchronizer/config.go index 55bc29d3e7..0f7d822a60 100644 --- a/synchronizer/config.go +++ b/synchronizer/config.go @@ -13,6 +13,8 @@ type Config struct { SyncChunkSize uint64 `mapstructure:"SyncChunkSize"` // TrustedSequencerURL is the rpc url to connect and sync the trusted state TrustedSequencerURL string `mapstructure:"TrustedSequencerURL"` + // SyncBlockProtection specify the state to sync (lastest, finalized or safe) + SyncBlockProtection string `mapstructure:"SyncBlockProtection"` // L1SyncCheckL2BlockHash if is true when a batch is closed is force to check L2Block hash against trustedNode (only apply for permissionless) L1SyncCheckL2BlockHash bool `mapstructure:"L1SyncCheckL2BlockHash"` diff --git a/synchronizer/synchronizer.go b/synchronizer/synchronizer.go index 02c43db796..c4e76eaecd 100644 --- a/synchronizer/synchronizer.go +++ b/synchronizer/synchronizer.go @@ -22,6 +22,7 @@ import ( "github.com/0xPolygonHermez/zkevm-node/synchronizer/l2_sync/l2_sync_etrog" "github.com/0xPolygonHermez/zkevm-node/synchronizer/metrics" "github.com/ethereum/go-ethereum/common" + "github.com/ethereum/go-ethereum/rpc" "github.com/jackc/pgx/v4" ) @@ -53,6 +54,7 @@ type ClientSynchronizer struct { latestFlushID uint64 // If true the lastFlushID is stored in DB and we don't need to check again latestFlushIDIsFulfilled bool + syncBlockProtection rpc.BlockNumber etherManForL1 []syncinterfaces.EthermanFullInterface state syncinterfaces.StateFullInterface pool syncinterfaces.PoolInterface @@ -95,6 +97,13 @@ func NewSynchronizer( runInDevelopmentMode bool) (Synchronizer, error) { ctx, cancel := context.WithCancel(context.Background()) metrics.Register() + syncBlockProtection, err := decodeSyncBlockProtection(cfg.SyncBlockProtection) + if err != nil { + log.Errorf("error decoding syncBlockProtection. Error: %v", err) + cancel() + return nil, err + } + log.Info("syncBlockProtection: ", syncBlockProtection) res := &ClientSynchronizer{ isTrustedSequencer: isTrustedSequencer, state: st, @@ -113,6 +122,7 @@ func NewSynchronizer( previousExecutorFlushID: 0, l1SyncOrchestration: nil, l1EventProcessors: nil, + syncBlockProtection: syncBlockProtection, halter: syncCommon.NewCriticalErrorHalt(eventLog, 5*time.Second), //nolint:gomnd } if !isTrustedSequencer { @@ -169,6 +179,19 @@ func NewSynchronizer( return res, nil } +func decodeSyncBlockProtection(sBP string) (rpc.BlockNumber, error) { + switch sBP { + case "latest": + return rpc.LatestBlockNumber, nil + case "finalized": + return rpc.FinalizedBlockNumber, nil + case "safe": + return rpc.SafeBlockNumber, nil + default: + return 0, fmt.Errorf("error decoding SyncBlockProtection. Unknown value") + } +} + var waitDuration = time.Duration(0) func newL1SyncParallel(ctx context.Context, cfg Config, etherManForL1 []syncinterfaces.EthermanFullInterface, sync *ClientSynchronizer, runExternalControl bool) *l1_parallel_sync.L1SyncOrchestration { @@ -539,7 +562,7 @@ func (s *ClientSynchronizer) syncBlocksParallel(lastEthBlockSynced *state.Block) // This function syncs the node from a specific block to the latest func (s *ClientSynchronizer) syncBlocksSequential(lastEthBlockSynced *state.Block) (*state.Block, error) { // Call the blockchain to retrieve data - header, err := s.etherMan.HeaderByNumber(s.ctx, nil) + header, err := s.etherMan.HeaderByNumber(s.ctx, big.NewInt(s.syncBlockProtection.Int64())) if err != nil { log.Error("error getting header of the latest block in L1. Error: ", err) return lastEthBlockSynced, err @@ -568,6 +591,9 @@ func (s *ClientSynchronizer) syncBlocksSequential(lastEthBlockSynced *state.Bloc for { toBlock := fromBlock + s.cfg.SyncChunkSize + if toBlock > lastKnownBlock.Uint64() { + toBlock = lastKnownBlock.Uint64() + } log.Infof("Syncing block %d of %d", fromBlock, lastKnownBlock.Uint64()) log.Infof("Getting rollup info from block %d to block %d", fromBlock, toBlock) // This function returns the rollup information contained in the ethereum blocks and an extra param called order. @@ -721,6 +747,8 @@ func (s *ClientSynchronizer) checkReorg(latestBlock *state.Block) (*state.Block, log.Errorf("error getting latest block synced from blockchain. Block: %d, error: %v", reorgedBlock.BlockNumber, err) return nil, err } + log.Infof("[checkReorg function] BlockNumber: %d BlockHash got from L1 provider: %s", block.Number().Uint64(), block.Hash().String()) + log.Infof("[checkReorg function] latestBlockNumber: %d latestBlockHash already synced: %s", latestBlock.BlockNumber, latestBlock.BlockHash.String()) if block.NumberU64() != reorgedBlock.BlockNumber { err = fmt.Errorf("wrong ethereum block retrieved from blockchain. Block numbers don't match. BlockNumber stored: %d. BlockNumber retrieved: %d", reorgedBlock.BlockNumber, block.NumberU64()) diff --git a/synchronizer/synchronizer_test.go b/synchronizer/synchronizer_test.go index b96ece6e06..20494ba5a5 100644 --- a/synchronizer/synchronizer_test.go +++ b/synchronizer/synchronizer_test.go @@ -18,6 +18,7 @@ import ( syncMocks "github.com/0xPolygonHermez/zkevm-node/synchronizer/mocks" "github.com/ethereum/go-ethereum/common" ethTypes "github.com/ethereum/go-ethereum/core/types" + "github.com/ethereum/go-ethereum/rpc" "github.com/jackc/pgx/v4" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" @@ -127,6 +128,7 @@ func TestForcedBatchEtrog(t *testing.T) { SyncInterval: cfgTypes.Duration{Duration: 1 * time.Second}, SyncChunkSize: 10, L1SynchronizationMode: SequentialMode, + SyncBlockProtection: "latest", } m := mocks{ @@ -208,7 +210,7 @@ func TestForcedBatchEtrog(t *testing.T) { Return(ethBlock, nil). Once() - var n *big.Int + n := big.NewInt(rpc.LatestBlockNumber.Int64()) m.Etherman. On("HeaderByNumber", mock.Anything, n). Return(ethHeader, nil). @@ -261,7 +263,9 @@ func TestForcedBatchEtrog(t *testing.T) { fromBlock := ethBlock.NumberU64() + 1 toBlock := fromBlock + cfg.SyncChunkSize - + if toBlock > ethHeader.Number.Uint64() { + toBlock = ethHeader.Number.Uint64() + } m.Etherman. On("GetRollupInfoByBlockRange", mock.Anything, fromBlock, &toBlock). Return(blocks, order, nil). @@ -390,6 +394,7 @@ func TestSequenceForcedBatchIncaberry(t *testing.T) { SyncInterval: cfgTypes.Duration{Duration: 1 * time.Second}, SyncChunkSize: 10, L1SynchronizationMode: SequentialMode, + SyncBlockProtection: "latest", } m := mocks{ @@ -471,7 +476,7 @@ func TestSequenceForcedBatchIncaberry(t *testing.T) { Return(ethBlock, nil). Once() - var n *big.Int + n := big.NewInt(rpc.LatestBlockNumber.Int64()) m.Etherman. On("HeaderByNumber", ctx, n). Return(ethHeader, nil). @@ -519,7 +524,9 @@ func TestSequenceForcedBatchIncaberry(t *testing.T) { fromBlock := ethBlock.NumberU64() + 1 toBlock := fromBlock + cfg.SyncChunkSize - + if toBlock > ethHeader.Number.Uint64() { + toBlock = ethHeader.Number.Uint64() + } m.Etherman. On("GetRollupInfoByBlockRange", ctx, fromBlock, &toBlock). Return(blocks, order, nil). @@ -638,6 +645,7 @@ func setupGenericTest(t *testing.T) (*state.Genesis, *Config, *mocks) { SyncInterval: cfgTypes.Duration{Duration: 1 * time.Second}, SyncChunkSize: 10, L1SynchronizationMode: SequentialMode, + SyncBlockProtection: "latest", L1ParallelSynchronization: L1ParallelSynchronizationConfig{ MaxClients: 2, MaxPendingNoProcessedBlocks: 2, diff --git a/test/config/test.node.config.toml b/test/config/test.node.config.toml index 5b2f8a2ed4..0665c104a3 100644 --- a/test/config/test.node.config.toml +++ b/test/config/test.node.config.toml @@ -82,6 +82,7 @@ EnableL2SuggestedGasPricePolling = true SyncInterval = "1s" SyncChunkSize = 100 TrustedSequencerURL = "" # If it is empty or not specified, then the value is read from the smc. +SyncBlockProtection = "latest" # latest, finalized, safe L1SynchronizationMode = "sequential" [Synchronizer.L1ParallelSynchronization] MaxClients = 10