diff --git a/.mockery.yaml b/.mockery.yaml index 57f7ba103..7fccd0c8e 100644 --- a/.mockery.yaml +++ b/.mockery.yaml @@ -39,49 +39,11 @@ packages: AggregatorService_ChannelServer: config: mockname: ChannelMock - github.com/0xPolygon/cdk/bridgesync: - config: - dir: "{{ .InterfaceDir }}/mocks" - interfaces: - ReorgDetector: - EthClienter: github.com/0xPolygon/cdk/dataavailability: config: dir: "{{ .InterfaceDir }}/mocks_da" all: true outpkg: "mocks_da" - github.com/0xPolygon/cdk/db: - config: - dir: "{{ .InterfaceDir }}/../aggregator/mocks" - mockname: "{{ .InterfaceName }}Mock" - interfaces: - Txer: - github.com/0xPolygon/cdk/l1infotreesync: - config: - dir: "{{ .InterfaceDir }}/mocks" - interfaces: - EthClienter: - github.com/0xPolygon/cdk/reorgdetector: - config: - dir: "{{ .InterfaceDir }}" - outpkg: "{{ .PackageName }}" - mockname: "{{ .InterfaceName }}Mock" - interfaces: - EthClient: - github.com/0xPolygon/cdk/rpc/client: - config: - interfaces: - BridgeClientInterface: - ClientInterface: - ClientFactoryInterface: - github.com/0xPolygon/cdk/rpc: - config: - dir: "{{ .InterfaceDir }}/mocks" - interfaces: - Bridger: - LastGERer: - L1InfoTreer: - ClaimSponsorer: github.com/0xPolygon/cdk/sequencesender: config: dir: "{{ .InterfaceDir }}/mocks" @@ -111,28 +73,3 @@ packages: - dir: "{{ .InterfaceDir }}/mocks_txbuilder" outpkg: "mocks_txbuilder" mockname: "{{ .InterfaceName | camelcase | firstUpper }}" - github.com/0xPolygon/cdk/sync: - config: - dir: "{{ .InterfaceDir }}" - outpkg: "{{ .PackageName }}" - mockname: "{{ .InterfaceName }}Mock" - inpackage: true - interfaces: - ReorgDetector: - configs: - - dir: "{{ .InterfaceDir }}/../l1infotreesync/mocks" - outpkg: "mocks" - mockname: "{{ .InterfaceName }}Mock" - inpackage: false - - dir: "{{ .InterfaceDir }}" - outpkg: "{{ .PackageName }}" - mockname: "{{ .InterfaceName }}Mock" - processorInterface: - config: - mockname: "ProcessorMock" - evmDownloaderFull: - config: - mockname: "EVMDownloaderMock" - EthClienter: - config: - mockname: "L2Mock" \ No newline at end of file diff --git a/Makefile b/Makefile index 08b682325..1a7d76c24 100644 --- a/Makefile +++ b/Makefile @@ -36,12 +36,12 @@ check-docker: check-docker-compose: @which docker-compose > /dev/null || (echo "Error: docker-compose is not installed" && exit 1) -# Check for Protoc +# Check for protoc .PHONY: check-protoc check-protoc: - @which protoc > /dev/null || (echo "Error: Protoc is not installed" && exit 1) + @which protoc > /dev/null || (echo "Error: protoc is not installed" && exit 1) -# Check for Curl +# Check for curl .PHONY: check-curl check-curl: @which curl > /dev/null || (echo "Error: curl is not installed" && exit 1) diff --git a/agglayer/mock_agglayer_client_interface.go b/agglayer/mock_agglayer_client_interface.go index 8b9a819fd..ba870086b 100644 --- a/agglayer/mock_agglayer_client_interface.go +++ b/agglayer/mock_agglayer_client_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package agglayer diff --git a/aggregator/aggregator.go b/aggregator/aggregator.go index 9ff6dc28e..cc02a4a8a 100644 --- a/aggregator/aggregator.go +++ b/aggregator/aggregator.go @@ -22,8 +22,6 @@ import ( "github.com/0xPolygon/cdk/aggregator/prover" cdkcommon "github.com/0xPolygon/cdk/common" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/l1infotree" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/rpc" "github.com/0xPolygon/cdk/state" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" @@ -33,6 +31,8 @@ import ( "github.com/0xPolygonHermez/zkevm-synchronizer-l1/state/entities" "github.com/0xPolygonHermez/zkevm-synchronizer-l1/synchronizer" "github.com/0xPolygonHermez/zkevm-synchronizer-l1/synchronizer/l1_check_block" + "github.com/agglayer/aggkit/l1infotree" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" "go.uber.org/zap/zapcore" "google.golang.org/grpc" diff --git a/aggregator/aggregator_test.go b/aggregator/aggregator_test.go index 086550ebf..6e012fb63 100644 --- a/aggregator/aggregator_test.go +++ b/aggregator/aggregator_test.go @@ -21,10 +21,10 @@ import ( mocks "github.com/0xPolygon/cdk/aggregator/mocks" "github.com/0xPolygon/cdk/aggregator/prover" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" rpctypes "github.com/0xPolygon/cdk/rpc/types" "github.com/0xPolygon/cdk/state" "github.com/0xPolygonHermez/zkevm-synchronizer-l1/synchronizer" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ethTypes "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/assert" diff --git a/aggregator/config.go b/aggregator/config.go index e17d68af4..477f50882 100644 --- a/aggregator/config.go +++ b/aggregator/config.go @@ -5,9 +5,9 @@ import ( "math/big" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" syncronizerConfig "github.com/0xPolygonHermez/zkevm-synchronizer-l1/config" + "github.com/agglayer/aggkit/log" ) // SettlementBackend is the type of the settlement backend diff --git a/aggregator/db/dbstorage/dbstorage.go b/aggregator/db/dbstorage/dbstorage.go index b20a1c715..05af9aa76 100644 --- a/aggregator/db/dbstorage/dbstorage.go +++ b/aggregator/db/dbstorage/dbstorage.go @@ -4,7 +4,7 @@ import ( "context" "database/sql" - "github.com/0xPolygon/cdk/db" + "github.com/agglayer/aggkit/db" ) // DBStorage implements the Storage interface diff --git a/aggregator/db/dbstorage/proof.go b/aggregator/db/dbstorage/proof.go index d3065c7e1..46a6def79 100644 --- a/aggregator/db/dbstorage/proof.go +++ b/aggregator/db/dbstorage/proof.go @@ -7,8 +7,8 @@ import ( "fmt" "time" - "github.com/0xPolygon/cdk/db" "github.com/0xPolygon/cdk/state" + "github.com/agglayer/aggkit/db" ) // CheckProofExistsForBatch checks if the batch is already included in any proof @@ -170,7 +170,7 @@ func (d *DBStorage) GetProofsToAggregate(ctx context.Context, dbTx db.Txer) (*st &createdAt1, &updatedAt1, &proof2.BatchNumber, &proof2.BatchNumberFinal, &proof2.Proof, &proof2.ProofID, &proof2.InputProver, &proof2.Prover, &proof2.ProverID, &generatingSince2, - &createdAt1, &updatedAt1, + &createdAt2, &updatedAt2, ) if generatingSince1 != nil { diff --git a/aggregator/db/dbstorage/sequence.go b/aggregator/db/dbstorage/sequence.go index 960632010..ed509e64f 100644 --- a/aggregator/db/dbstorage/sequence.go +++ b/aggregator/db/dbstorage/sequence.go @@ -3,8 +3,8 @@ package dbstorage import ( "context" - "github.com/0xPolygon/cdk/db" "github.com/0xPolygon/cdk/state" + "github.com/agglayer/aggkit/db" ) // AddSequence stores the sequence information to allow the aggregator verify sequences. diff --git a/aggregator/db/logger.go b/aggregator/db/logger.go index e60a7b011..441a54fc0 100644 --- a/aggregator/db/logger.go +++ b/aggregator/db/logger.go @@ -4,7 +4,7 @@ import ( "context" "fmt" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/jackc/pgx/v4" ) diff --git a/aggregator/db/migrations.go b/aggregator/db/migrations.go index 221fb1450..695eb0c99 100644 --- a/aggregator/db/migrations.go +++ b/aggregator/db/migrations.go @@ -4,8 +4,8 @@ import ( "embed" "fmt" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/db" + "github.com/agglayer/aggkit/log" migrate "github.com/rubenv/sql-migrate" ) diff --git a/aggregator/interfaces.go b/aggregator/interfaces.go index 5979272d9..3a868d56c 100644 --- a/aggregator/interfaces.go +++ b/aggregator/interfaces.go @@ -7,11 +7,11 @@ import ( ethmanTypes "github.com/0xPolygon/cdk/aggregator/ethmantypes" "github.com/0xPolygon/cdk/aggregator/prover" - "github.com/0xPolygon/cdk/db" "github.com/0xPolygon/cdk/rpc/types" "github.com/0xPolygon/cdk/state" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/db" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/crypto/kzg4844" diff --git a/aggregator/mocks/mock_eth_tx_manager_client.go b/aggregator/mocks/mock_eth_tx_manager_client.go index 47dabe1ca..339e6b893 100644 --- a/aggregator/mocks/mock_eth_tx_manager_client.go +++ b/aggregator/mocks/mock_eth_tx_manager_client.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/aggregator/mocks/mock_etherman.go b/aggregator/mocks/mock_etherman.go index 2982430df..8dab429a4 100644 --- a/aggregator/mocks/mock_etherman.go +++ b/aggregator/mocks/mock_etherman.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/aggregator/mocks/mock_prover_interface.go b/aggregator/mocks/mock_prover_interface.go index 7939667d1..f48d4ff07 100644 --- a/aggregator/mocks/mock_prover_interface.go +++ b/aggregator/mocks/mock_prover_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/aggregator/mocks/mock_rpc_interface.go b/aggregator/mocks/mock_rpc_interface.go index 3927b5db0..6e3871b3b 100644 --- a/aggregator/mocks/mock_rpc_interface.go +++ b/aggregator/mocks/mock_rpc_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/aggregator/mocks/mock_storage_interface.go b/aggregator/mocks/mock_storage_interface.go index 2615f6bca..42aaf118a 100644 --- a/aggregator/mocks/mock_storage_interface.go +++ b/aggregator/mocks/mock_storage_interface.go @@ -1,11 +1,11 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks import ( context "context" - db "github.com/0xPolygon/cdk/db" + db "github.com/agglayer/aggkit/db" mock "github.com/stretchr/testify/mock" sql "database/sql" diff --git a/aggregator/prover/mocks/mock_aggregator_service_channel_server.go b/aggregator/prover/mocks/mock_aggregator_service_channel_server.go index b079d26e9..f65c2f694 100644 --- a/aggregator/prover/mocks/mock_aggregator_service_channel_server.go +++ b/aggregator/prover/mocks/mock_aggregator_service_channel_server.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/aggregator/prover/prover.go b/aggregator/prover/prover.go index ad9c9895f..4b86e6b71 100644 --- a/aggregator/prover/prover.go +++ b/aggregator/prover/prover.go @@ -12,7 +12,7 @@ import ( "time" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" "github.com/iden3/go-iden3-crypto/poseidon" ) diff --git a/aggregator/prover/prover_test.go b/aggregator/prover/prover_test.go index 438718a33..cd25dd2b8 100644 --- a/aggregator/prover/prover_test.go +++ b/aggregator/prover/prover_test.go @@ -11,7 +11,7 @@ import ( "github.com/0xPolygon/cdk/aggregator/prover" "github.com/0xPolygon/cdk/aggregator/prover/mocks" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/bridgesync/bridgesync.go b/bridgesync/bridgesync.go deleted file mode 100644 index 4f6f1e903..000000000 --- a/bridgesync/bridgesync.go +++ /dev/null @@ -1,286 +0,0 @@ -package bridgesync - -import ( - "context" - "time" - - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" -) - -const ( - bridgeSyncL1 = "BridgeSyncL1" - bridgeSyncL2 = "BridgeSyncL2" - downloadBufferSize = 1000 -) - -type ReorgDetector interface { - sync.ReorgDetector -} - -// BridgeSync manages the state of the exit tree for the bridge contract by processing Ethereum blockchain events. -type BridgeSync struct { - processor *processor - driver *sync.EVMDriver - - originNetwork uint32 - blockFinality etherman.BlockNumberFinality -} - -// NewL1 creates a bridge syncer that synchronizes the mainnet exit tree -func NewL1( - ctx context.Context, - dbPath string, - bridge common.Address, - syncBlockChunkSize uint64, - blockFinalityType etherman.BlockNumberFinality, - rd ReorgDetector, - ethClient EthClienter, - initialBlock uint64, - waitForNewBlocksPeriod time.Duration, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - originNetwork uint32, - syncFullClaims bool, - finalizedBlockType etherman.BlockNumberFinality, -) (*BridgeSync, error) { - return newBridgeSync( - ctx, - dbPath, - bridge, - syncBlockChunkSize, - blockFinalityType, - rd, - ethClient, - initialBlock, - bridgeSyncL1, - waitForNewBlocksPeriod, - retryAfterErrorPeriod, - maxRetryAttemptsAfterError, - originNetwork, - syncFullClaims, - finalizedBlockType, - ) -} - -// NewL2 creates a bridge syncer that synchronizes the local exit tree -func NewL2( - ctx context.Context, - dbPath string, - bridge common.Address, - syncBlockChunkSize uint64, - blockFinalityType etherman.BlockNumberFinality, - rd ReorgDetector, - ethClient EthClienter, - initialBlock uint64, - waitForNewBlocksPeriod time.Duration, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - originNetwork uint32, - syncFullClaims bool, - finalizedBlockType etherman.BlockNumberFinality, -) (*BridgeSync, error) { - return newBridgeSync( - ctx, - dbPath, - bridge, - syncBlockChunkSize, - blockFinalityType, - rd, - ethClient, - initialBlock, - bridgeSyncL2, - waitForNewBlocksPeriod, - retryAfterErrorPeriod, - maxRetryAttemptsAfterError, - originNetwork, - syncFullClaims, - finalizedBlockType, - ) -} - -func newBridgeSync( - ctx context.Context, - dbPath string, - bridge common.Address, - syncBlockChunkSize uint64, - blockFinalityType etherman.BlockNumberFinality, - rd ReorgDetector, - ethClient EthClienter, - initialBlock uint64, - layerID string, - waitForNewBlocksPeriod time.Duration, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - originNetwork uint32, - syncFullClaims bool, - finalizedBlockType etherman.BlockNumberFinality, -) (*BridgeSync, error) { - logger := log.WithFields("bridge-syncer", layerID) - processor, err := newProcessor(dbPath, logger) - if err != nil { - return nil, err - } - - lastProcessedBlock, err := processor.GetLastProcessedBlock(ctx) - if err != nil { - return nil, err - } - - if lastProcessedBlock < initialBlock { - err = processor.ProcessBlock(ctx, sync.Block{ - Num: initialBlock, - }) - if err != nil { - return nil, err - } - } - rh := &sync.RetryHandler{ - MaxRetryAttemptsAfterError: maxRetryAttemptsAfterError, - RetryAfterErrorPeriod: retryAfterErrorPeriod, - } - - appender, err := buildAppender(ethClient, bridge, syncFullClaims) - if err != nil { - return nil, err - } - downloader, err := sync.NewEVMDownloader( - layerID, - ethClient, - syncBlockChunkSize, - blockFinalityType, - waitForNewBlocksPeriod, - appender, - []common.Address{bridge}, - rh, - finalizedBlockType, - ) - if err != nil { - return nil, err - } - - driver, err := sync.NewEVMDriver(rd, processor, downloader, layerID, downloadBufferSize, rh) - if err != nil { - return nil, err - } - - logger.Infof( - "BridgeSyncer [%s] created:\n"+ - " dbPath: %s\n"+ - " initialBlock: %d\n"+ - " bridgeAddr: %s\n"+ - " syncFullClaims: %t\n"+ - " maxRetryAttemptsAfterError: %d\n"+ - " retryAfterErrorPeriod: %s\n"+ - " syncBlockChunkSize: %d\n"+ - " blockFinalityType: %s\n"+ - " waitForNewBlocksPeriod: %s", - layerID, - dbPath, - initialBlock, - bridge.String(), - syncFullClaims, - maxRetryAttemptsAfterError, - retryAfterErrorPeriod.String(), - syncBlockChunkSize, - blockFinalityType, - waitForNewBlocksPeriod.String(), - ) - - return &BridgeSync{ - processor: processor, - driver: driver, - originNetwork: originNetwork, - blockFinality: blockFinalityType, - }, nil -} - -// Start starts the synchronization process -func (s *BridgeSync) Start(ctx context.Context) { - s.driver.Sync(ctx) -} - -func (s *BridgeSync) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - if s.processor.isHalted() { - return 0, sync.ErrInconsistentState - } - return s.processor.GetLastProcessedBlock(ctx) -} - -func (s *BridgeSync) GetBridgeRootByHash(ctx context.Context, root common.Hash) (*tree.Root, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.exitTree.GetRootByHash(ctx, root) -} - -func (s *BridgeSync) GetClaims(ctx context.Context, fromBlock, toBlock uint64) ([]Claim, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetClaims(ctx, fromBlock, toBlock) -} - -func (s *BridgeSync) GetBridges(ctx context.Context, fromBlock, toBlock uint64) ([]Bridge, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetBridges(ctx, fromBlock, toBlock) -} - -func (s *BridgeSync) GetBridgesPublished(ctx context.Context, fromBlock, toBlock uint64) ([]Bridge, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetBridgesPublished(ctx, fromBlock, toBlock) -} - -func (s *BridgeSync) GetProof(ctx context.Context, depositCount uint32, localExitRoot common.Hash) (tree.Proof, error) { - if s.processor.isHalted() { - return tree.Proof{}, sync.ErrInconsistentState - } - return s.processor.exitTree.GetProof(ctx, depositCount, localExitRoot) -} - -func (s *BridgeSync) GetBlockByLER(ctx context.Context, ler common.Hash) (uint64, error) { - if s.processor.isHalted() { - return 0, sync.ErrInconsistentState - } - root, err := s.processor.exitTree.GetRootByHash(ctx, ler) - if err != nil { - return 0, err - } - return root.BlockNum, nil -} - -func (s *BridgeSync) GetRootByLER(ctx context.Context, ler common.Hash) (*tree.Root, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - root, err := s.processor.exitTree.GetRootByHash(ctx, ler) - if err != nil { - return root, err - } - return root, nil -} - -// GetExitRootByIndex returns the root of the exit tree at the moment the leaf with the given index was added -func (s *BridgeSync) GetExitRootByIndex(ctx context.Context, index uint32) (tree.Root, error) { - if s.processor.isHalted() { - return tree.Root{}, sync.ErrInconsistentState - } - return s.processor.exitTree.GetRootByIndex(ctx, index) -} - -// OriginNetwork returns the network ID of the origin chain -func (s *BridgeSync) OriginNetwork() uint32 { - return s.originNetwork -} - -// BlockFinality returns the block finality type -func (s *BridgeSync) BlockFinality() etherman.BlockNumberFinality { - return s.blockFinality -} diff --git a/bridgesync/bridgesync_test.go b/bridgesync/bridgesync_test.go deleted file mode 100644 index 838967ebd..000000000 --- a/bridgesync/bridgesync_test.go +++ /dev/null @@ -1,142 +0,0 @@ -package bridgesync - -import ( - "context" - "errors" - "path" - "testing" - "time" - - mocksbridgesync "github.com/0xPolygon/cdk/bridgesync/mocks" - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -// Mock implementations for the interfaces -type MockEthClienter struct { - mock.Mock -} - -type MockBridgeContractor struct { - mock.Mock -} - -func TestNewLx(t *testing.T) { - ctx := context.Background() - dbPath := path.Join(t.TempDir(), "TestNewLx.sqlite") - bridge := common.HexToAddress("0x1234567890abcdef1234567890abcdef12345678") - syncBlockChunkSize := uint64(100) - blockFinalityType := etherman.SafeBlock - initialBlock := uint64(0) - waitForNewBlocksPeriod := time.Second * 10 - retryAfterErrorPeriod := time.Second * 5 - maxRetryAttemptsAfterError := 3 - originNetwork := uint32(1) - - mockEthClient := mocksbridgesync.NewEthClienter(t) - mockReorgDetector := mocksbridgesync.NewReorgDetector(t) - - mockReorgDetector.EXPECT().Subscribe(mock.Anything).Return(nil, nil) - - bridgeSync, err := NewL1( - ctx, - dbPath, - bridge, - syncBlockChunkSize, - blockFinalityType, - mockReorgDetector, - mockEthClient, - initialBlock, - waitForNewBlocksPeriod, - retryAfterErrorPeriod, - maxRetryAttemptsAfterError, - originNetwork, - false, - blockFinalityType, - ) - - assert.NoError(t, err) - assert.NotNil(t, bridgeSync) - assert.Equal(t, originNetwork, bridgeSync.OriginNetwork()) - assert.Equal(t, blockFinalityType, bridgeSync.BlockFinality()) - - bridgeSyncL2, err := NewL2( - ctx, - dbPath, - bridge, - syncBlockChunkSize, - blockFinalityType, - mockReorgDetector, - mockEthClient, - initialBlock, - waitForNewBlocksPeriod, - retryAfterErrorPeriod, - maxRetryAttemptsAfterError, - originNetwork, - false, - blockFinalityType, - ) - - assert.NoError(t, err) - assert.NotNil(t, bridgeSync) - assert.Equal(t, originNetwork, bridgeSyncL2.OriginNetwork()) - assert.Equal(t, blockFinalityType, bridgeSyncL2.BlockFinality()) -} - -func TestGetLastProcessedBlock(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetLastProcessedBlock(context.Background()) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetBridgeRootByHash(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetBridgeRootByHash(context.Background(), common.Hash{}) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetBridges(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetBridges(context.Background(), 0, 0) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetProof(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetProof(context.Background(), 0, common.Hash{}) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetBlockByLER(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetBlockByLER(context.Background(), common.Hash{}) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetRootByLER(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetRootByLER(context.Background(), common.Hash{}) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetExitRootByIndex(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetExitRootByIndex(context.Background(), 0) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetClaims(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetClaims(context.Background(), 0, 0) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetBridgesPublishedTopLevel(t *testing.T) { - s := BridgeSync{processor: &processor{halted: true}} - _, err := s.GetBridgesPublished(context.Background(), 0, 0) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} diff --git a/bridgesync/claimcalldata_test.go b/bridgesync/claimcalldata_test.go deleted file mode 100644 index ef2d60bdd..000000000 --- a/bridgesync/claimcalldata_test.go +++ /dev/null @@ -1,1942 +0,0 @@ -package bridgesync - -import ( - "context" - "math/big" - "os/exec" - "testing" - "time" - - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/test/contracts/claimmock" - "github.com/0xPolygon/cdk/test/contracts/claimmockcaller" - "github.com/0xPolygon/cdk/test/contracts/claimmocktest" - tree "github.com/0xPolygon/cdk/tree/types" - "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/stretchr/testify/require" -) - -type testCase struct { - description string - bridgeAddr common.Address - log types.Log - expectedClaim Claim -} - -func TestClaimCalldata(t *testing.T) { - testCases := []testCase{} - // Setup Docker L1 - log.Debug("starting docker") - ctx := context.Background() - msg, err := exec.Command("bash", "-l", "-c", "docker compose up -d").CombinedOutput() - require.NoError(t, err, string(msg)) - time.Sleep(time.Second * 1) - defer func() { - msg, err = exec.Command("bash", "-l", "-c", "docker compose down").CombinedOutput() - require.NoError(t, err, string(msg)) - }() - log.Debug("docker started") - client, err := ethclient.Dial("http://localhost:8545") - require.NoError(t, err) - privateKey, err := crypto.HexToECDSA("ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80") - require.NoError(t, err) - auth, err := bind.NewKeyedTransactorWithChainID(privateKey, big.NewInt(0).SetUint64(1337)) - require.NoError(t, err) - - // Deploy contracts - bridgeAddr, _, bridgeContract, err := claimmock.DeployClaimmock(auth, client) - require.NoError(t, err) - claimCallerAddr, _, claimCaller, err := claimmockcaller.DeployClaimmockcaller(auth, client, bridgeAddr) - require.NoError(t, err) - _, _, claimTest, err := claimmocktest.DeployClaimmocktest(auth, client, bridgeAddr, claimCallerAddr) - require.NoError(t, err) - - proofLocal := [32][32]byte{} - proofLocalH := tree.Proof{} - proofLocal[5] = common.HexToHash("beef") - proofLocalH[5] = common.HexToHash("beef") - proofRollup := [32][32]byte{} - proofRollupH := tree.Proof{} - proofRollup[4] = common.HexToHash("a1fa") - proofRollupH[4] = common.HexToHash("a1fa") - expectedClaim := Claim{ - OriginNetwork: 69, - OriginAddress: common.HexToAddress("ffaaffaa"), - DestinationAddress: common.HexToAddress("123456789"), - Amount: big.NewInt(3), - MainnetExitRoot: common.HexToHash("5ca1e"), - RollupExitRoot: common.HexToHash("dead"), - ProofLocalExitRoot: proofLocalH, - ProofRollupExitRoot: proofRollupH, - DestinationNetwork: 0, - Metadata: []byte{}, - GlobalExitRoot: crypto.Keccak256Hash(common.HexToHash("5ca1e").Bytes(), common.HexToHash("dead").Bytes()), - } - expectedClaim2 := Claim{ - OriginNetwork: 87, - OriginAddress: common.HexToAddress("eebbeebb"), - DestinationAddress: common.HexToAddress("2233445566"), - Amount: big.NewInt(4), - MainnetExitRoot: common.HexToHash("5ca1e"), - RollupExitRoot: common.HexToHash("dead"), - ProofLocalExitRoot: proofLocalH, - ProofRollupExitRoot: proofRollupH, - DestinationNetwork: 0, - Metadata: []byte{}, - GlobalExitRoot: crypto.Keccak256Hash(common.HexToHash("5ca1e").Bytes(), common.HexToHash("dead").Bytes()), - } - expectedClaim3 := Claim{ - OriginNetwork: 69, - OriginAddress: common.HexToAddress("ffaaffaa"), - DestinationAddress: common.HexToAddress("2233445566"), - Amount: big.NewInt(5), - MainnetExitRoot: common.HexToHash("5ca1e"), - RollupExitRoot: common.HexToHash("dead"), - ProofLocalExitRoot: proofLocalH, - ProofRollupExitRoot: proofRollupH, - DestinationNetwork: 0, - Metadata: []byte{}, - GlobalExitRoot: crypto.Keccak256Hash(common.HexToHash("5ca1e").Bytes(), common.HexToHash("dead").Bytes()), - } - auth.GasLimit = 999999 // for some reason gas estimation fails :( - - abi, err := claimmock.ClaimmockMetaData.GetAbi() - require.NoError(t, err) - - // direct call claim asset - expectedClaim.GlobalIndex = big.NewInt(421) - expectedClaim.IsMessage = false - tx, err := bridgeContract.ClaimAsset( - auth, - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - 0, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - nil, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err := client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "direct call to claim asset", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // indirect call claim asset - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(422) - tx, err = claimCaller.ClaimAsset( - auth, - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - 0, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - nil, - false, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "indirect call to claim asset", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // indirect call claim asset bytes - expectedClaim.GlobalIndex = big.NewInt(423) - expectedClaim.IsMessage = false - expectedClaimBytes, err := abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.ClaimBytes( - auth, - expectedClaimBytes, - false, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "indirect call to claim asset bytes", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // direct call claim message - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(424) - tx, err = bridgeContract.ClaimMessage( - auth, - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - 0, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - nil, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "direct call to claim message", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // indirect call claim message - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(425) - tx, err = claimCaller.ClaimMessage( - auth, - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - 0, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - nil, - false, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "indirect call to claim message", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // indirect call claim message bytes - expectedClaim.GlobalIndex = big.NewInt(426) - expectedClaim.IsMessage = true - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.ClaimBytes( - auth, - expectedClaimBytes, - false, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "indirect call to claim message bytes", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // indirect call claim message bytes - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim.IsMessage = true - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.ClaimBytes( - auth, - expectedClaimBytes, - true, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - log.Infof("%+v", r.Logs) - - reverted := [2]bool{false, false} - - // 2 indirect call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err := abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - // 2 indirect call claim message (diff global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(428) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(429) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - reverted = [2]bool{false, true} - - // 2 indirect call claim message (same global index) (1 ok, 1 reverted) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(430) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(430) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message (same globalIndex) (1 ok, 1 reverted)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // 2 indirect call claim message (diff global index) (1 ok, 1 reverted) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(431) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(432) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message (diff globalIndex) (1 ok, 1 reverted)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - reverted = [2]bool{true, false} - - // 2 indirect call claim message (same global index) (1 reverted, 1 ok) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(433) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(433) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message (same globalIndex) (reverted,ok)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - - // 2 indirect call claim message (diff global index) (1 reverted, 1 ok) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(434) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(435) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim message (diff globalIndex) (reverted,ok)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - - reverted = [2]bool{false, false} - - // 2 indirect call claim asset (same global index) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(436) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(436) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - // 2 indirect call claim asset (diff global index) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(437) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(438) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - reverted = [2]bool{false, true} - - // 2 indirect call claim asset (same global index) (1 ok, 1 reverted) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(439) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(439) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset (same globalIndex) (1 ok, 1 reverted)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - // 2 indirect call claim message (diff global index) (1 ok, 1 reverted) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(440) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(441) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset (diff globalIndex) (1 ok, 1 reverted)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - reverted = [2]bool{true, false} - - // 2 indirect call claim asset (same global index) (1 reverted, 1 ok) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(442) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(442) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset (same globalIndex) (reverted,ok)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - - // 2 indirect call claim asset (diff global index) (1 reverted, 1 ok) - expectedClaim.IsMessage = false - expectedClaim.GlobalIndex = big.NewInt(443) - expectedClaim2.IsMessage = false - expectedClaim2.GlobalIndex = big.NewInt(444) - expectedClaimBytes, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimAsset", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimCaller.Claim2Bytes( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect call claim asset (diff globalIndex) (reverted,ok)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - - // indirect + indirect call claim message bytes - expectedClaim.GlobalIndex = big.NewInt(426) - expectedClaim.IsMessage = true - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.ClaimTestInternal( - auth, - expectedClaimBytes, - false, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "indirect + indirect call to claim message bytes", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - reverted = [2]bool{false, false} - - // 2 indirect + indirect call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim2TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - reverted, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 indirect + indirect call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "2 indirect + indirect call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - reverted3 := [3]bool{false, false, false} - - // 3 ok (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err := abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 3 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[2], - expectedClaim: expectedClaim3, - }) - - // 3 ok (indirectx2, indirect, indirectx2) call claim message (diff global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(428) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(429) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - testCases = append(testCases, testCase{ - description: "3 ok (indirectx2, indirect, indirectx2) call claim message 3 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[2], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{true, false, false} - - // 1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message (diff global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(428) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(429) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{false, true, false} - - // 1 ok 1 ko 1 ok (indirectx2, indirect, indirectx2) call claim message (diff global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(428) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(429) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{false, false, true} - - // 1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message (diff global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(428) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(429) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message 1 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message 2 (diff globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - reverted3 = [3]bool{true, false, false} - - // 1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{false, true, false} - - // 1 ok 1 ko 1 ok (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "1 ko 2 ok (indirectx2, indirect, indirectx2) call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{false, false, true} - - // 1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - testCases = append(testCases, testCase{ - description: "1 ok 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message 2 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[1], - expectedClaim: expectedClaim2, - }) - - reverted3 = [3]bool{true, true, false} - - // 2 ko 1 ok (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "2 ko 1 ok (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim3, - }) - - reverted3 = [3]bool{false, true, true} - - // 1 ok 2 ko (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ok 2 ko (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim, - }) - - reverted3 = [3]bool{true, false, true} - - // 1 ko 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message (same global index) - expectedClaim.IsMessage = true - expectedClaim.GlobalIndex = big.NewInt(427) - expectedClaim2.IsMessage = true - expectedClaim2.GlobalIndex = big.NewInt(427) - expectedClaim3.IsMessage = true - expectedClaim3.GlobalIndex = big.NewInt(427) - expectedClaimBytes, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim.GlobalIndex, - expectedClaim.MainnetExitRoot, - expectedClaim.RollupExitRoot, - expectedClaim.OriginNetwork, - expectedClaim.OriginAddress, - expectedClaim.DestinationNetwork, - expectedClaim.DestinationAddress, - expectedClaim.Amount, - expectedClaim.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes2, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim2.GlobalIndex, - expectedClaim2.MainnetExitRoot, - expectedClaim2.RollupExitRoot, - expectedClaim2.OriginNetwork, - expectedClaim2.OriginAddress, - expectedClaim2.DestinationNetwork, - expectedClaim2.DestinationAddress, - expectedClaim2.Amount, - expectedClaim2.Metadata, - ) - require.NoError(t, err) - expectedClaimBytes3, err = abi.Pack( - "claimMessage", - proofLocal, - proofRollup, - expectedClaim3.GlobalIndex, - expectedClaim3.MainnetExitRoot, - expectedClaim3.RollupExitRoot, - expectedClaim3.OriginNetwork, - expectedClaim3.OriginAddress, - expectedClaim3.DestinationNetwork, - expectedClaim3.DestinationAddress, - expectedClaim3.Amount, - expectedClaim3.Metadata, - ) - require.NoError(t, err) - tx, err = claimTest.Claim3TestInternal( - auth, - expectedClaimBytes, - expectedClaimBytes2, - expectedClaimBytes3, - reverted3, - ) - require.NoError(t, err) - time.Sleep(1 * time.Second) - r, err = client.TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - testCases = append(testCases, testCase{ - description: "1 ko 1 ok 1 ko (indirectx2, indirect, indirectx2) call claim message 1 (same globalIndex)", - bridgeAddr: bridgeAddr, - log: *r.Logs[0], - expectedClaim: expectedClaim2, - }) - - for _, tc := range testCases { - log.Info(tc.description) - t.Run(tc.description, func(t *testing.T) { - claimEvent, err := bridgeContract.ParseClaimEvent(tc.log) - require.NoError(t, err) - actualClaim := Claim{ - GlobalIndex: claimEvent.GlobalIndex, - OriginNetwork: claimEvent.OriginNetwork, - OriginAddress: claimEvent.OriginAddress, - DestinationAddress: claimEvent.DestinationAddress, - Amount: claimEvent.Amount, - } - err = setClaimCalldata(client, tc.bridgeAddr, tc.log.TxHash, &actualClaim) - require.NoError(t, err) - require.Equal(t, tc.expectedClaim, actualClaim) - }) - } -} diff --git a/bridgesync/config.go b/bridgesync/config.go deleted file mode 100644 index 66eb00ed3..000000000 --- a/bridgesync/config.go +++ /dev/null @@ -1,27 +0,0 @@ -package bridgesync - -import ( - "github.com/0xPolygon/cdk/config/types" - "github.com/ethereum/go-ethereum/common" -) - -type Config struct { - // DBPath path of the DB - DBPath string `mapstructure:"DBPath"` - // BlockFinality indicates the status of the blocks that will be queried in order to sync - BlockFinality string `jsonschema:"enum=LatestBlock, enum=SafeBlock, enum=PendingBlock, enum=FinalizedBlock, enum=EarliestBlock" mapstructure:"BlockFinality"` //nolint:lll - // InitialBlockNum is the first block that will be queried when starting the synchronization from scratch. - // It should be a number equal or bellow the creation of the bridge contract - InitialBlockNum uint64 `mapstructure:"InitialBlockNum"` - // BridgeAddr is the address of the bridge smart contract - BridgeAddr common.Address `mapstructure:"BridgeAddr"` - // SyncBlockChunkSize is the amount of blocks that will be queried to the client on each request - SyncBlockChunkSize uint64 `mapstructure:"SyncBlockChunkSize"` - // RetryAfterErrorPeriod is the time that will be waited when an unexpected error happens before retry - RetryAfterErrorPeriod types.Duration `mapstructure:"RetryAfterErrorPeriod"` - // MaxRetryAttemptsAfterError is the maximum number of consecutive attempts that will happen before panicing. - // Any number smaller than zero will be considered as unlimited retries - MaxRetryAttemptsAfterError int `mapstructure:"MaxRetryAttemptsAfterError"` - // WaitForNewBlocksPeriod time that will be waited when the synchronizer has reached the latest block - WaitForNewBlocksPeriod types.Duration `mapstructure:"WaitForNewBlocksPeriod"` -} diff --git a/bridgesync/docker-compose.yml b/bridgesync/docker-compose.yml deleted file mode 100644 index 9a8f77698..000000000 --- a/bridgesync/docker-compose.yml +++ /dev/null @@ -1,24 +0,0 @@ -services: - test-claimdata-l1: - container_name: test-claimdata-l1 - image: hermeznetwork/geth-zkevm-contracts:elderberry-fork.9-geth1.13.11 - environment: - - DEV_PERIOD - ports: - - "8545:8545" - entrypoint: - - geth - - --http - - --http.addr - - "0.0.0.0" - - "--http.corsdomain" - - "*" - - "--http.vhosts" - - "*" - - --dev - - --dev.period - - "1" - - "--datadir" - - "/geth_data" - - "--http.api" - - "admin,eth,debug,miner,net,txpool,personal,web3" diff --git a/bridgesync/downloader.go b/bridgesync/downloader.go deleted file mode 100644 index 3756c9706..000000000 --- a/bridgesync/downloader.go +++ /dev/null @@ -1,301 +0,0 @@ -package bridgesync - -import ( - "bytes" - "fmt" - "math/big" - "strings" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/etrog/polygonzkevmbridge" - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmbridgev2" - rpcTypes "github.com/0xPolygon/cdk-rpc/types" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/sync" - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "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/rpc" - "github.com/golang-collections/collections/stack" -) - -var ( - bridgeEventSignature = crypto.Keccak256Hash([]byte( - "BridgeEvent(uint8,uint32,address,uint32,address,uint256,bytes,uint32)", - )) - claimEventSignature = crypto.Keccak256Hash([]byte("ClaimEvent(uint256,uint32,address,address,uint256)")) - claimEventSignaturePreEtrog = crypto.Keccak256Hash([]byte("ClaimEvent(uint32,uint32,address,address,uint256)")) - methodIDClaimAsset = common.Hex2Bytes("ccaa2d11") - methodIDClaimMessage = common.Hex2Bytes("f5efcd79") -) - -// EthClienter defines the methods required to interact with an Ethereum client. -type EthClienter interface { - ethereum.LogFilterer - ethereum.BlockNumberReader - ethereum.ChainReader - bind.ContractBackend - Client() *rpc.Client -} - -func buildAppender(client EthClienter, bridge common.Address, syncFullClaims bool) (sync.LogAppenderMap, error) { - bridgeContractV1, err := polygonzkevmbridge.NewPolygonzkevmbridge(bridge, client) - if err != nil { - return nil, err - } - bridgeContractV2, err := polygonzkevmbridgev2.NewPolygonzkevmbridgev2(bridge, client) - if err != nil { - return nil, err - } - appender := make(sync.LogAppenderMap) - - appender[bridgeEventSignature] = func(b *sync.EVMBlock, l types.Log) error { - bridge, err := bridgeContractV2.ParseBridgeEvent(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using d.bridgeContractV2.ParseBridgeEvent: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{Bridge: &Bridge{ - BlockNum: b.Num, - BlockPos: uint64(l.Index), - LeafType: bridge.LeafType, - OriginNetwork: bridge.OriginNetwork, - OriginAddress: bridge.OriginAddress, - DestinationNetwork: bridge.DestinationNetwork, - DestinationAddress: bridge.DestinationAddress, - Amount: bridge.Amount, - Metadata: bridge.Metadata, - DepositCount: bridge.DepositCount, - }}) - - return nil - } - - appender[claimEventSignature] = func(b *sync.EVMBlock, l types.Log) error { - claimEvent, err := bridgeContractV2.ParseClaimEvent(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using d.bridgeContractV2.ParseClaimEvent: %w", - l, err, - ) - } - claim := &Claim{ - BlockNum: b.Num, - BlockPos: uint64(l.Index), - GlobalIndex: claimEvent.GlobalIndex, - OriginNetwork: claimEvent.OriginNetwork, - OriginAddress: claimEvent.OriginAddress, - DestinationAddress: claimEvent.DestinationAddress, - Amount: claimEvent.Amount, - } - if syncFullClaims { - if err := setClaimCalldata(client, bridge, l.TxHash, claim); err != nil { - return err - } - } - b.Events = append(b.Events, Event{Claim: claim}) - return nil - } - - appender[claimEventSignaturePreEtrog] = func(b *sync.EVMBlock, l types.Log) error { - claimEvent, err := bridgeContractV1.ParseClaimEvent(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using d.bridgeContractV1.ParseClaimEvent: %w", - l, err, - ) - } - claim := &Claim{ - BlockNum: b.Num, - BlockPos: uint64(l.Index), - GlobalIndex: big.NewInt(int64(claimEvent.Index)), - OriginNetwork: claimEvent.OriginNetwork, - OriginAddress: claimEvent.OriginAddress, - DestinationAddress: claimEvent.DestinationAddress, - Amount: claimEvent.Amount, - } - if syncFullClaims { - if err := setClaimCalldata(client, bridge, l.TxHash, claim); err != nil { - return err - } - } - b.Events = append(b.Events, Event{Claim: claim}) - return nil - } - - return appender, nil -} - -type call struct { - To common.Address `json:"to"` - Value *rpcTypes.ArgBig `json:"value"` - Err *string `json:"error"` - Input rpcTypes.ArgBytes `json:"input"` - Calls []call `json:"calls"` -} - -type tracerCfg struct { - Tracer string `json:"tracer"` -} - -func setClaimCalldata(client EthClienter, bridge common.Address, txHash common.Hash, claim *Claim) error { - c := &call{} - err := client.Client().Call(c, "debug_traceTransaction", txHash, tracerCfg{Tracer: "callTracer"}) - if err != nil { - return err - } - - // find the claim linked to the event using DFS - callStack := stack.New() - callStack.Push(*c) - for { - if callStack.Len() == 0 { - break - } - - currentCallInterface := callStack.Pop() - currentCall, ok := currentCallInterface.(call) - if !ok { - return fmt.Errorf("unexpected type for 'currentCall'. Expected 'call', got '%T'", currentCallInterface) - } - - if currentCall.To == bridge { - found, err := setClaimIfFoundOnInput( - currentCall.Input, - claim, - ) - if err != nil { - return err - } - if found { - return nil - } - } - for _, c := range currentCall.Calls { - callStack.Push(c) - } - } - return db.ErrNotFound -} - -func setClaimIfFoundOnInput(input []byte, claim *Claim) (bool, error) { - smcAbi, err := abi.JSON(strings.NewReader(polygonzkevmbridgev2.Polygonzkevmbridgev2ABI)) - if err != nil { - return false, err - } - methodID := input[:4] - // Recover Method from signature and ABI - method, err := smcAbi.MethodById(methodID) - if err != nil { - return false, err - } - data, err := method.Inputs.Unpack(input[4:]) - if err != nil { - return false, err - } - // Ignore other methods - if bytes.Equal(methodID, methodIDClaimAsset) || bytes.Equal(methodID, methodIDClaimMessage) { - found, err := decodeClaimCallDataAndSetIfFound(data, claim) - if err != nil { - return false, err - } - if found { - if bytes.Equal(methodID, methodIDClaimMessage) { - claim.IsMessage = true - } - return true, nil - } - return false, nil - } else { - return false, nil - } - // TODO: support both claim asset & message, check if previous versions need special treatment -} - -func decodeClaimCallDataAndSetIfFound(data []interface{}, claim *Claim) (bool, error) { - /* Unpack method inputs. Note that both claimAsset and claimMessage have the same interface - for the relevant parts - claimAsset( - 0: smtProofLocalExitRoot, - 1: smtProofRollupExitRoot, - 2: globalIndex, - 3: mainnetExitRoot, - 4: rollupExitRoot, - 5: originNetwork, - 6: originTokenAddress, - 7: destinationNetwork, - 8: destinationAddress, - 9: amount, - 10: metadata, - ) - claimMessage( - 0: smtProofLocalExitRoot, - 1: smtProofRollupExitRoot, - 2: globalIndex, - 3: mainnetExitRoot, - 4: rollupExitRoot, - 5: originNetwork, - 6: originAddress, - 7: destinationNetwork, - 8: destinationAddress, - 9: amount, - 10: metadata, - ) - */ - actualGlobalIndex, ok := data[2].(*big.Int) - if !ok { - return false, fmt.Errorf("unexpected type for actualGlobalIndex, expected *big.Int got '%T'", data[2]) - } - if actualGlobalIndex.Cmp(claim.GlobalIndex) != 0 { - // not the claim we're looking for - return false, nil - } else { - proofLER := [tree.DefaultHeight]common.Hash{} - proofLERBytes, ok := data[0].([32][32]byte) - if !ok { - return false, fmt.Errorf("unexpected type for proofLERBytes, expected [32][32]byte got '%T'", data[0]) - } - - proofRER := [tree.DefaultHeight]common.Hash{} - proofRERBytes, ok := data[1].([32][32]byte) - if !ok { - return false, fmt.Errorf("unexpected type for proofRERBytes, expected [32][32]byte got '%T'", data[1]) - } - - for i := 0; i < int(tree.DefaultHeight); i++ { - proofLER[i] = proofLERBytes[i] - proofRER[i] = proofRERBytes[i] - } - claim.ProofLocalExitRoot = proofLER - claim.ProofRollupExitRoot = proofRER - - claim.MainnetExitRoot, ok = data[3].([32]byte) - if !ok { - return false, fmt.Errorf("unexpected type for 'MainnetExitRoot'. Expected '[32]byte', got '%T'", data[3]) - } - - claim.RollupExitRoot, ok = data[4].([32]byte) - if !ok { - return false, fmt.Errorf("unexpected type for 'RollupExitRoot'. Expected '[32]byte', got '%T'", data[4]) - } - - claim.DestinationNetwork, ok = data[7].(uint32) - if !ok { - return false, fmt.Errorf("unexpected type for 'DestinationNetwork'. Expected 'uint32', got '%T'", data[7]) - } - - claim.Metadata, ok = data[10].([]byte) - if !ok { - return false, fmt.Errorf("unexpected type for 'claim Metadata'. Expected '[]byte', got '%T'", data[10]) - } - - claim.GlobalExitRoot = crypto.Keccak256Hash(claim.MainnetExitRoot.Bytes(), claim.RollupExitRoot.Bytes()) - - return true, nil - } -} diff --git a/bridgesync/e2e_test.go b/bridgesync/e2e_test.go deleted file mode 100644 index 1545398ae..000000000 --- a/bridgesync/e2e_test.go +++ /dev/null @@ -1,112 +0,0 @@ -package bridgesync_test - -import ( - "context" - "math/big" - "testing" - "time" - - "github.com/0xPolygon/cdk/bridgesync" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/test/helpers" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/stretchr/testify/require" -) - -func TestBridgeEventE2E(t *testing.T) { - const ( - blockTime = time.Millisecond * 10 - totalBridges = 80 - totalReorgs = 40 - maxReorgDepth = 2 - reorgEveryXIterations = 4 // every X blocks go back [1,maxReorgDepth] blocks - ) - l1Env, _ := helpers.NewL1EnvWithL2EVM(t) - ctx := context.Background() - // Send bridge txs - bridgesSent := 0 - reorgs := 0 - expectedBridges := []bridgesync.Bridge{} - lastDepositCount := uint32(0) - for i := 1; i > 0; i++ { - // Send bridge - bridge := bridgesync.Bridge{ - Amount: big.NewInt(0), - DepositCount: lastDepositCount, - DestinationNetwork: uint32(i + 1), - DestinationAddress: common.HexToAddress("f00"), - Metadata: []byte{}, - } - lastDepositCount++ - tx, err := l1Env.BridgeContract.BridgeAsset( - l1Env.Auth, - bridge.DestinationNetwork, - bridge.DestinationAddress, - bridge.Amount, - bridge.OriginAddress, - true, nil, - ) - require.NoError(t, err) - helpers.CommitBlocks(t, l1Env.SimBackend, 1, blockTime) - bn, err := l1Env.SimBackend.Client().BlockNumber(ctx) - require.NoError(t, err) - bridge.BlockNum = bn - receipt, err := l1Env.SimBackend.Client().TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - require.Equal(t, receipt.Status, types.ReceiptStatusSuccessful) - expectedBridges = append(expectedBridges, bridge) - bridgesSent++ - - // Trigger reorg - if i%reorgEveryXIterations == 0 { - blocksToReorg := 1 + i%maxReorgDepth - bn, err := l1Env.SimBackend.Client().BlockNumber(ctx) - require.NoError(t, err) - helpers.Reorg(t, l1Env.SimBackend, uint64(blocksToReorg)) - // Clean expected bridges - lastValidBlock := bn - uint64(blocksToReorg) - reorgEffective := false - for i := len(expectedBridges) - 1; i >= 0; i-- { - if expectedBridges[i].BlockNum > lastValidBlock { - log.Debugf("removing expectedBridge with depositCount %d due to reorg", expectedBridges[i].DepositCount) - lastDepositCount = expectedBridges[i].DepositCount - expectedBridges = expectedBridges[0:i] - reorgEffective = true - bridgesSent-- - } - } - if reorgEffective { - reorgs++ - log.Debug("reorgs: ", reorgs) - } - } - - // Finish condition - if bridgesSent >= totalBridges && reorgs >= totalReorgs { - break - } - } - - helpers.CommitBlocks(t, l1Env.SimBackend, 11, blockTime) - - // Wait for syncer to catch up - time.Sleep(time.Second * 2) // sleeping since the processor could be up to date, but have pending reorgs - lb, err := l1Env.SimBackend.Client().BlockNumber(ctx) - require.NoError(t, err) - helpers.RequireProcessorUpdated(t, l1Env.BridgeSync, lb) - - // Get bridges - lastBlock, err := l1Env.SimBackend.Client().BlockNumber(ctx) - require.NoError(t, err) - actualBridges, err := l1Env.BridgeSync.GetBridges(ctx, 0, lastBlock) - require.NoError(t, err) - - // Assert bridges - expectedRoot, err := l1Env.BridgeContract.GetRoot(nil) - require.NoError(t, err) - root, err := l1Env.BridgeSync.GetExitRootByIndex(ctx, expectedBridges[len(expectedBridges)-1].DepositCount) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRoot).Hex(), root.Hash.Hex()) - require.Equal(t, expectedBridges, actualBridges) -} diff --git a/bridgesync/migrations/bridgesync0001.sql b/bridgesync/migrations/bridgesync0001.sql deleted file mode 100644 index 74adc6d50..000000000 --- a/bridgesync/migrations/bridgesync0001.sql +++ /dev/null @@ -1,42 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS block; -DROP TABLE IF EXISTS claim; -DROP TABLE IF EXISTS bridge; - --- +migrate Up -CREATE TABLE block ( - num BIGINT PRIMARY KEY -); - -CREATE TABLE bridge ( - block_num INTEGER NOT NULL REFERENCES block(num) ON DELETE CASCADE, - block_pos INTEGER NOT NULL, - leaf_type INTEGER NOT NULL, - origin_network INTEGER NOT NULL, - origin_address VARCHAR NOT NULL, - destination_network INTEGER NOT NULL, - destination_address VARCHAR NOT NULL, - amount TEXT NOT NULL, - metadata BLOB, - deposit_count INTEGER NOT NULL, - PRIMARY KEY (block_num, block_pos) -); - -CREATE TABLE claim ( - block_num INTEGER NOT NULL REFERENCES block(num) ON DELETE CASCADE, - block_pos INTEGER NOT NULL, - global_index TEXT NOT NULL, - origin_network INTEGER NOT NULL, - origin_address VARCHAR NOT NULL, - destination_address VARCHAR NOT NULL, - amount TEXT NOT NULL, - proof_local_exit_root VARCHAR, - proof_rollup_exit_root VARCHAR, - mainnet_exit_root VARCHAR, - rollup_exit_root VARCHAR, - global_exit_root VARCHAR, - destination_network INTEGER NOT NULL, - metadata BLOB, - is_message BOOLEAN, - PRIMARY KEY (block_num, block_pos) -); \ No newline at end of file diff --git a/bridgesync/migrations/bridgesync0001_test.go b/bridgesync/migrations/bridgesync0001_test.go deleted file mode 100644 index 51e5aded5..000000000 --- a/bridgesync/migrations/bridgesync0001_test.go +++ /dev/null @@ -1,61 +0,0 @@ -package migrations - -import ( - "context" - "path" - "testing" - - "github.com/0xPolygon/cdk/db" - "github.com/stretchr/testify/require" -) - -func Test001(t *testing.T) { - dbPath := path.Join(t.TempDir(), "bridgesyncTest001.sqlite") - - err := RunMigrations(dbPath) - require.NoError(t, err) - db, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - - ctx := context.Background() - tx, err := db.BeginTx(ctx, nil) - require.NoError(t, err) - - _, err = tx.Exec(` - INSERT INTO block (num) VALUES (1); - - INSERT INTO bridge ( - block_num, - block_pos, - leaf_type, - origin_network, - origin_address, - destination_network, - destination_address, - amount, - metadata, - deposit_count - ) VALUES (1, 0, 0, 0, '0x0000', 0, '0x0000', 0, NULL, 0); - - INSERT INTO claim ( - block_num, - block_pos, - global_index, - origin_network, - origin_address, - destination_address, - amount, - proof_local_exit_root, - proof_rollup_exit_root, - mainnet_exit_root, - rollup_exit_root, - global_exit_root, - destination_network, - metadata, - is_message - ) VALUES (1, 0, 0, 0, '0x0000', '0x0000', 0, '0x000,0x000', '0x000,0x000', '0x000', '0x000', '0x0', 0, NULL, FALSE); - `) - require.NoError(t, err) - err = tx.Commit() - require.NoError(t, err) -} diff --git a/bridgesync/migrations/migrations.go b/bridgesync/migrations/migrations.go deleted file mode 100644 index c500ee386..000000000 --- a/bridgesync/migrations/migrations.go +++ /dev/null @@ -1,23 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" - treeMigrations "github.com/0xPolygon/cdk/tree/migrations" -) - -//go:embed bridgesync0001.sql -var mig001 string - -func RunMigrations(dbPath string) error { - migrations := []types.Migration{ - { - ID: "bridgesync0001", - SQL: mig001, - }, - } - migrations = append(migrations, treeMigrations.Migrations...) - return db.RunMigrations(dbPath, migrations) -} diff --git a/bridgesync/mocks/mock_eth_clienter.go b/bridgesync/mocks/mock_eth_clienter.go deleted file mode 100644 index 5cb3146cb..000000000 --- a/bridgesync/mocks/mock_eth_clienter.go +++ /dev/null @@ -1,1136 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - big "math/big" - - common "github.com/ethereum/go-ethereum/common" - - context "context" - - ethereum "github.com/ethereum/go-ethereum" - - mock "github.com/stretchr/testify/mock" - - rpc "github.com/ethereum/go-ethereum/rpc" - - types "github.com/ethereum/go-ethereum/core/types" -) - -// EthClienter is an autogenerated mock type for the EthClienter type -type EthClienter struct { - mock.Mock -} - -type EthClienter_Expecter struct { - mock *mock.Mock -} - -func (_m *EthClienter) EXPECT() *EthClienter_Expecter { - return &EthClienter_Expecter{mock: &_m.Mock} -} - -// BlockByHash provides a mock function with given fields: ctx, hash -func (_m *EthClienter) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for BlockByHash") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Block, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Block); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByHash' -type EthClienter_BlockByHash_Call struct { - *mock.Call -} - -// BlockByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *EthClienter_Expecter) BlockByHash(ctx interface{}, hash interface{}) *EthClienter_BlockByHash_Call { - return &EthClienter_BlockByHash_Call{Call: _e.mock.On("BlockByHash", ctx, hash)} -} - -func (_c *EthClienter_BlockByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *EthClienter_BlockByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_BlockByHash_Call) Return(_a0 *types.Block, _a1 error) *EthClienter_BlockByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Block, error)) *EthClienter_BlockByHash_Call { - _c.Call.Return(run) - return _c -} - -// BlockByNumber provides a mock function with given fields: ctx, number -func (_m *EthClienter) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for BlockByNumber") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Block, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Block); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByNumber' -type EthClienter_BlockByNumber_Call struct { - *mock.Call -} - -// BlockByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *EthClienter_Expecter) BlockByNumber(ctx interface{}, number interface{}) *EthClienter_BlockByNumber_Call { - return &EthClienter_BlockByNumber_Call{Call: _e.mock.On("BlockByNumber", ctx, number)} -} - -func (_c *EthClienter_BlockByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *EthClienter_BlockByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_BlockByNumber_Call) Return(_a0 *types.Block, _a1 error) *EthClienter_BlockByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Block, error)) *EthClienter_BlockByNumber_Call { - _c.Call.Return(run) - return _c -} - -// BlockNumber provides a mock function with given fields: ctx -func (_m *EthClienter) BlockNumber(ctx context.Context) (uint64, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for BlockNumber") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockNumber' -type EthClienter_BlockNumber_Call struct { - *mock.Call -} - -// BlockNumber is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) BlockNumber(ctx interface{}) *EthClienter_BlockNumber_Call { - return &EthClienter_BlockNumber_Call{Call: _e.mock.On("BlockNumber", ctx)} -} - -func (_c *EthClienter_BlockNumber_Call) Run(run func(ctx context.Context)) *EthClienter_BlockNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_BlockNumber_Call) Return(_a0 uint64, _a1 error) *EthClienter_BlockNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockNumber_Call) RunAndReturn(run func(context.Context) (uint64, error)) *EthClienter_BlockNumber_Call { - _c.Call.Return(run) - return _c -} - -// CallContract provides a mock function with given fields: ctx, call, blockNumber -func (_m *EthClienter) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, call, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CallContract") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { - return rf(ctx, call, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { - r0 = rf(ctx, call, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { - r1 = rf(ctx, call, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_CallContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CallContract' -type EthClienter_CallContract_Call struct { - *mock.Call -} - -// CallContract is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -// - blockNumber *big.Int -func (_e *EthClienter_Expecter) CallContract(ctx interface{}, call interface{}, blockNumber interface{}) *EthClienter_CallContract_Call { - return &EthClienter_CallContract_Call{Call: _e.mock.On("CallContract", ctx, call, blockNumber)} -} - -func (_c *EthClienter_CallContract_Call) Run(run func(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int)) *EthClienter_CallContract_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg), args[2].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_CallContract_Call) Return(_a0 []byte, _a1 error) *EthClienter_CallContract_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_CallContract_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)) *EthClienter_CallContract_Call { - _c.Call.Return(run) - return _c -} - -// Client provides a mock function with no fields -func (_m *EthClienter) Client() *rpc.Client { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for Client") - } - - var r0 *rpc.Client - if rf, ok := ret.Get(0).(func() *rpc.Client); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*rpc.Client) - } - } - - return r0 -} - -// EthClienter_Client_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Client' -type EthClienter_Client_Call struct { - *mock.Call -} - -// Client is a helper method to define mock.On call -func (_e *EthClienter_Expecter) Client() *EthClienter_Client_Call { - return &EthClienter_Client_Call{Call: _e.mock.On("Client")} -} - -func (_c *EthClienter_Client_Call) Run(run func()) *EthClienter_Client_Call { - _c.Call.Run(func(args mock.Arguments) { - run() - }) - return _c -} - -func (_c *EthClienter_Client_Call) Return(_a0 *rpc.Client) *EthClienter_Client_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *EthClienter_Client_Call) RunAndReturn(run func() *rpc.Client) *EthClienter_Client_Call { - _c.Call.Return(run) - return _c -} - -// CodeAt provides a mock function with given fields: ctx, contract, blockNumber -func (_m *EthClienter) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, contract, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { - return rf(ctx, contract, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { - r0 = rf(ctx, contract, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { - r1 = rf(ctx, contract, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_CodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CodeAt' -type EthClienter_CodeAt_Call struct { - *mock.Call -} - -// CodeAt is a helper method to define mock.On call -// - ctx context.Context -// - contract common.Address -// - blockNumber *big.Int -func (_e *EthClienter_Expecter) CodeAt(ctx interface{}, contract interface{}, blockNumber interface{}) *EthClienter_CodeAt_Call { - return &EthClienter_CodeAt_Call{Call: _e.mock.On("CodeAt", ctx, contract, blockNumber)} -} - -func (_c *EthClienter_CodeAt_Call) Run(run func(ctx context.Context, contract common.Address, blockNumber *big.Int)) *EthClienter_CodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address), args[2].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_CodeAt_Call) Return(_a0 []byte, _a1 error) *EthClienter_CodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_CodeAt_Call) RunAndReturn(run func(context.Context, common.Address, *big.Int) ([]byte, error)) *EthClienter_CodeAt_Call { - _c.Call.Return(run) - return _c -} - -// EstimateGas provides a mock function with given fields: ctx, call -func (_m *EthClienter) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - ret := _m.Called(ctx, call) - - if len(ret) == 0 { - panic("no return value specified for EstimateGas") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { - return rf(ctx, call) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { - r0 = rf(ctx, call) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { - r1 = rf(ctx, call) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_EstimateGas_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EstimateGas' -type EthClienter_EstimateGas_Call struct { - *mock.Call -} - -// EstimateGas is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -func (_e *EthClienter_Expecter) EstimateGas(ctx interface{}, call interface{}) *EthClienter_EstimateGas_Call { - return &EthClienter_EstimateGas_Call{Call: _e.mock.On("EstimateGas", ctx, call)} -} - -func (_c *EthClienter_EstimateGas_Call) Run(run func(ctx context.Context, call ethereum.CallMsg)) *EthClienter_EstimateGas_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg)) - }) - return _c -} - -func (_c *EthClienter_EstimateGas_Call) Return(_a0 uint64, _a1 error) *EthClienter_EstimateGas_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_EstimateGas_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg) (uint64, error)) *EthClienter_EstimateGas_Call { - _c.Call.Return(run) - return _c -} - -// FilterLogs provides a mock function with given fields: ctx, q -func (_m *EthClienter) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(ctx, q) - - if len(ret) == 0 { - panic("no return value specified for FilterLogs") - } - - var r0 []types.Log - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(ctx, q) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(ctx, q) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Log) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { - r1 = rf(ctx, q) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_FilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FilterLogs' -type EthClienter_FilterLogs_Call struct { - *mock.Call -} - -// FilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -func (_e *EthClienter_Expecter) FilterLogs(ctx interface{}, q interface{}) *EthClienter_FilterLogs_Call { - return &EthClienter_FilterLogs_Call{Call: _e.mock.On("FilterLogs", ctx, q)} -} - -func (_c *EthClienter_FilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery)) *EthClienter_FilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery)) - }) - return _c -} - -func (_c *EthClienter_FilterLogs_Call) Return(_a0 []types.Log, _a1 error) *EthClienter_FilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_FilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery) ([]types.Log, error)) *EthClienter_FilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByHash provides a mock function with given fields: ctx, hash -func (_m *EthClienter) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for HeaderByHash") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Header, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Header); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_HeaderByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByHash' -type EthClienter_HeaderByHash_Call struct { - *mock.Call -} - -// HeaderByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *EthClienter_Expecter) HeaderByHash(ctx interface{}, hash interface{}) *EthClienter_HeaderByHash_Call { - return &EthClienter_HeaderByHash_Call{Call: _e.mock.On("HeaderByHash", ctx, hash)} -} - -func (_c *EthClienter_HeaderByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *EthClienter_HeaderByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_HeaderByHash_Call) Return(_a0 *types.Header, _a1 error) *EthClienter_HeaderByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_HeaderByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Header, error)) *EthClienter_HeaderByHash_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByNumber provides a mock function with given fields: ctx, number -func (_m *EthClienter) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for HeaderByNumber") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_HeaderByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByNumber' -type EthClienter_HeaderByNumber_Call struct { - *mock.Call -} - -// HeaderByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *EthClienter_Expecter) HeaderByNumber(ctx interface{}, number interface{}) *EthClienter_HeaderByNumber_Call { - return &EthClienter_HeaderByNumber_Call{Call: _e.mock.On("HeaderByNumber", ctx, number)} -} - -func (_c *EthClienter_HeaderByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *EthClienter_HeaderByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_HeaderByNumber_Call) Return(_a0 *types.Header, _a1 error) *EthClienter_HeaderByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_HeaderByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Header, error)) *EthClienter_HeaderByNumber_Call { - _c.Call.Return(run) - return _c -} - -// PendingCodeAt provides a mock function with given fields: ctx, account -func (_m *EthClienter) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingCodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { - r0 = rf(ctx, account) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_PendingCodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingCodeAt' -type EthClienter_PendingCodeAt_Call struct { - *mock.Call -} - -// PendingCodeAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *EthClienter_Expecter) PendingCodeAt(ctx interface{}, account interface{}) *EthClienter_PendingCodeAt_Call { - return &EthClienter_PendingCodeAt_Call{Call: _e.mock.On("PendingCodeAt", ctx, account)} -} - -func (_c *EthClienter_PendingCodeAt_Call) Run(run func(ctx context.Context, account common.Address)) *EthClienter_PendingCodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *EthClienter_PendingCodeAt_Call) Return(_a0 []byte, _a1 error) *EthClienter_PendingCodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_PendingCodeAt_Call) RunAndReturn(run func(context.Context, common.Address) ([]byte, error)) *EthClienter_PendingCodeAt_Call { - _c.Call.Return(run) - return _c -} - -// PendingNonceAt provides a mock function with given fields: ctx, account -func (_m *EthClienter) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingNonceAt") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { - r0 = rf(ctx, account) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_PendingNonceAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingNonceAt' -type EthClienter_PendingNonceAt_Call struct { - *mock.Call -} - -// PendingNonceAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *EthClienter_Expecter) PendingNonceAt(ctx interface{}, account interface{}) *EthClienter_PendingNonceAt_Call { - return &EthClienter_PendingNonceAt_Call{Call: _e.mock.On("PendingNonceAt", ctx, account)} -} - -func (_c *EthClienter_PendingNonceAt_Call) Run(run func(ctx context.Context, account common.Address)) *EthClienter_PendingNonceAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *EthClienter_PendingNonceAt_Call) Return(_a0 uint64, _a1 error) *EthClienter_PendingNonceAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_PendingNonceAt_Call) RunAndReturn(run func(context.Context, common.Address) (uint64, error)) *EthClienter_PendingNonceAt_Call { - _c.Call.Return(run) - return _c -} - -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *EthClienter) SendTransaction(ctx context.Context, tx *types.Transaction) error { - ret := _m.Called(ctx, tx) - - if len(ret) == 0 { - panic("no return value specified for SendTransaction") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { - r0 = rf(ctx, tx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// EthClienter_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' -type EthClienter_SendTransaction_Call struct { - *mock.Call -} - -// SendTransaction is a helper method to define mock.On call -// - ctx context.Context -// - tx *types.Transaction -func (_e *EthClienter_Expecter) SendTransaction(ctx interface{}, tx interface{}) *EthClienter_SendTransaction_Call { - return &EthClienter_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} -} - -func (_c *EthClienter_SendTransaction_Call) Run(run func(ctx context.Context, tx *types.Transaction)) *EthClienter_SendTransaction_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*types.Transaction)) - }) - return _c -} - -func (_c *EthClienter_SendTransaction_Call) Return(_a0 error) *EthClienter_SendTransaction_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *EthClienter_SendTransaction_Call) RunAndReturn(run func(context.Context, *types.Transaction) error) *EthClienter_SendTransaction_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeFilterLogs provides a mock function with given fields: ctx, q, ch -func (_m *EthClienter) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - ret := _m.Called(ctx, q, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeFilterLogs") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { - return rf(ctx, q, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { - r0 = rf(ctx, q, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { - r1 = rf(ctx, q, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SubscribeFilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeFilterLogs' -type EthClienter_SubscribeFilterLogs_Call struct { - *mock.Call -} - -// SubscribeFilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -// - ch chan<- types.Log -func (_e *EthClienter_Expecter) SubscribeFilterLogs(ctx interface{}, q interface{}, ch interface{}) *EthClienter_SubscribeFilterLogs_Call { - return &EthClienter_SubscribeFilterLogs_Call{Call: _e.mock.On("SubscribeFilterLogs", ctx, q, ch)} -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log)) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery), args[2].(chan<- types.Log)) - }) - return _c -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) Return(_a0 ethereum.Subscription, _a1 error) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeNewHead provides a mock function with given fields: ctx, ch -func (_m *EthClienter) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { - ret := _m.Called(ctx, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeNewHead") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)); ok { - return rf(ctx, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) ethereum.Subscription); ok { - r0 = rf(ctx, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, chan<- *types.Header) error); ok { - r1 = rf(ctx, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SubscribeNewHead_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeNewHead' -type EthClienter_SubscribeNewHead_Call struct { - *mock.Call -} - -// SubscribeNewHead is a helper method to define mock.On call -// - ctx context.Context -// - ch chan<- *types.Header -func (_e *EthClienter_Expecter) SubscribeNewHead(ctx interface{}, ch interface{}) *EthClienter_SubscribeNewHead_Call { - return &EthClienter_SubscribeNewHead_Call{Call: _e.mock.On("SubscribeNewHead", ctx, ch)} -} - -func (_c *EthClienter_SubscribeNewHead_Call) Run(run func(ctx context.Context, ch chan<- *types.Header)) *EthClienter_SubscribeNewHead_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(chan<- *types.Header)) - }) - return _c -} - -func (_c *EthClienter_SubscribeNewHead_Call) Return(_a0 ethereum.Subscription, _a1 error) *EthClienter_SubscribeNewHead_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SubscribeNewHead_Call) RunAndReturn(run func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)) *EthClienter_SubscribeNewHead_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasPrice provides a mock function with given fields: ctx -func (_m *EthClienter) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasPrice") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SuggestGasPrice_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasPrice' -type EthClienter_SuggestGasPrice_Call struct { - *mock.Call -} - -// SuggestGasPrice is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) SuggestGasPrice(ctx interface{}) *EthClienter_SuggestGasPrice_Call { - return &EthClienter_SuggestGasPrice_Call{Call: _e.mock.On("SuggestGasPrice", ctx)} -} - -func (_c *EthClienter_SuggestGasPrice_Call) Run(run func(ctx context.Context)) *EthClienter_SuggestGasPrice_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_SuggestGasPrice_Call) Return(_a0 *big.Int, _a1 error) *EthClienter_SuggestGasPrice_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SuggestGasPrice_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *EthClienter_SuggestGasPrice_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasTipCap provides a mock function with given fields: ctx -func (_m *EthClienter) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasTipCap") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SuggestGasTipCap_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasTipCap' -type EthClienter_SuggestGasTipCap_Call struct { - *mock.Call -} - -// SuggestGasTipCap is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) SuggestGasTipCap(ctx interface{}) *EthClienter_SuggestGasTipCap_Call { - return &EthClienter_SuggestGasTipCap_Call{Call: _e.mock.On("SuggestGasTipCap", ctx)} -} - -func (_c *EthClienter_SuggestGasTipCap_Call) Run(run func(ctx context.Context)) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_SuggestGasTipCap_Call) Return(_a0 *big.Int, _a1 error) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SuggestGasTipCap_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Return(run) - return _c -} - -// TransactionCount provides a mock function with given fields: ctx, blockHash -func (_m *EthClienter) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { - ret := _m.Called(ctx, blockHash) - - if len(ret) == 0 { - panic("no return value specified for TransactionCount") - } - - var r0 uint - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (uint, error)); ok { - return rf(ctx, blockHash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) uint); ok { - r0 = rf(ctx, blockHash) - } else { - r0 = ret.Get(0).(uint) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, blockHash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_TransactionCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionCount' -type EthClienter_TransactionCount_Call struct { - *mock.Call -} - -// TransactionCount is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -func (_e *EthClienter_Expecter) TransactionCount(ctx interface{}, blockHash interface{}) *EthClienter_TransactionCount_Call { - return &EthClienter_TransactionCount_Call{Call: _e.mock.On("TransactionCount", ctx, blockHash)} -} - -func (_c *EthClienter_TransactionCount_Call) Run(run func(ctx context.Context, blockHash common.Hash)) *EthClienter_TransactionCount_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_TransactionCount_Call) Return(_a0 uint, _a1 error) *EthClienter_TransactionCount_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_TransactionCount_Call) RunAndReturn(run func(context.Context, common.Hash) (uint, error)) *EthClienter_TransactionCount_Call { - _c.Call.Return(run) - return _c -} - -// TransactionInBlock provides a mock function with given fields: ctx, blockHash, index -func (_m *EthClienter) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { - ret := _m.Called(ctx, blockHash, index) - - if len(ret) == 0 { - panic("no return value specified for TransactionInBlock") - } - - var r0 *types.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) (*types.Transaction, error)); ok { - return rf(ctx, blockHash, index) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) *types.Transaction); ok { - r0 = rf(ctx, blockHash, index) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash, uint) error); ok { - r1 = rf(ctx, blockHash, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_TransactionInBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionInBlock' -type EthClienter_TransactionInBlock_Call struct { - *mock.Call -} - -// TransactionInBlock is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -// - index uint -func (_e *EthClienter_Expecter) TransactionInBlock(ctx interface{}, blockHash interface{}, index interface{}) *EthClienter_TransactionInBlock_Call { - return &EthClienter_TransactionInBlock_Call{Call: _e.mock.On("TransactionInBlock", ctx, blockHash, index)} -} - -func (_c *EthClienter_TransactionInBlock_Call) Run(run func(ctx context.Context, blockHash common.Hash, index uint)) *EthClienter_TransactionInBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash), args[2].(uint)) - }) - return _c -} - -func (_c *EthClienter_TransactionInBlock_Call) Return(_a0 *types.Transaction, _a1 error) *EthClienter_TransactionInBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_TransactionInBlock_Call) RunAndReturn(run func(context.Context, common.Hash, uint) (*types.Transaction, error)) *EthClienter_TransactionInBlock_Call { - _c.Call.Return(run) - return _c -} - -// NewEthClienter creates a new instance of EthClienter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEthClienter(t interface { - mock.TestingT - Cleanup(func()) -}) *EthClienter { - mock := &EthClienter{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/bridgesync/mocks/mock_reorg_detector.go b/bridgesync/mocks/mock_reorg_detector.go deleted file mode 100644 index 6dd92f556..000000000 --- a/bridgesync/mocks/mock_reorg_detector.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - - common "github.com/ethereum/go-ethereum/common" - - mock "github.com/stretchr/testify/mock" - - reorgdetector "github.com/0xPolygon/cdk/reorgdetector" -) - -// ReorgDetector is an autogenerated mock type for the ReorgDetector type -type ReorgDetector struct { - mock.Mock -} - -type ReorgDetector_Expecter struct { - mock *mock.Mock -} - -func (_m *ReorgDetector) EXPECT() *ReorgDetector_Expecter { - return &ReorgDetector_Expecter{mock: &_m.Mock} -} - -// AddBlockToTrack provides a mock function with given fields: ctx, id, blockNum, blockHash -func (_m *ReorgDetector) AddBlockToTrack(ctx context.Context, id string, blockNum uint64, blockHash common.Hash) error { - ret := _m.Called(ctx, id, blockNum, blockHash) - - if len(ret) == 0 { - panic("no return value specified for AddBlockToTrack") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, common.Hash) error); ok { - r0 = rf(ctx, id, blockNum, blockHash) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReorgDetector_AddBlockToTrack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlockToTrack' -type ReorgDetector_AddBlockToTrack_Call struct { - *mock.Call -} - -// AddBlockToTrack is a helper method to define mock.On call -// - ctx context.Context -// - id string -// - blockNum uint64 -// - blockHash common.Hash -func (_e *ReorgDetector_Expecter) AddBlockToTrack(ctx interface{}, id interface{}, blockNum interface{}, blockHash interface{}) *ReorgDetector_AddBlockToTrack_Call { - return &ReorgDetector_AddBlockToTrack_Call{Call: _e.mock.On("AddBlockToTrack", ctx, id, blockNum, blockHash)} -} - -func (_c *ReorgDetector_AddBlockToTrack_Call) Run(run func(ctx context.Context, id string, blockNum uint64, blockHash common.Hash)) *ReorgDetector_AddBlockToTrack_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(string), args[2].(uint64), args[3].(common.Hash)) - }) - return _c -} - -func (_c *ReorgDetector_AddBlockToTrack_Call) Return(_a0 error) *ReorgDetector_AddBlockToTrack_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ReorgDetector_AddBlockToTrack_Call) RunAndReturn(run func(context.Context, string, uint64, common.Hash) error) *ReorgDetector_AddBlockToTrack_Call { - _c.Call.Return(run) - return _c -} - -// Subscribe provides a mock function with given fields: id -func (_m *ReorgDetector) Subscribe(id string) (*reorgdetector.Subscription, error) { - ret := _m.Called(id) - - if len(ret) == 0 { - panic("no return value specified for Subscribe") - } - - var r0 *reorgdetector.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(string) (*reorgdetector.Subscription, error)); ok { - return rf(id) - } - if rf, ok := ret.Get(0).(func(string) *reorgdetector.Subscription); ok { - r0 = rf(id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*reorgdetector.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ReorgDetector_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' -type ReorgDetector_Subscribe_Call struct { - *mock.Call -} - -// Subscribe is a helper method to define mock.On call -// - id string -func (_e *ReorgDetector_Expecter) Subscribe(id interface{}) *ReorgDetector_Subscribe_Call { - return &ReorgDetector_Subscribe_Call{Call: _e.mock.On("Subscribe", id)} -} - -func (_c *ReorgDetector_Subscribe_Call) Run(run func(id string)) *ReorgDetector_Subscribe_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(string)) - }) - return _c -} - -func (_c *ReorgDetector_Subscribe_Call) Return(_a0 *reorgdetector.Subscription, _a1 error) *ReorgDetector_Subscribe_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ReorgDetector_Subscribe_Call) RunAndReturn(run func(string) (*reorgdetector.Subscription, error)) *ReorgDetector_Subscribe_Call { - _c.Call.Return(run) - return _c -} - -// NewReorgDetector creates a new instance of ReorgDetector. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReorgDetector(t interface { - mock.TestingT - Cleanup(func()) -}) *ReorgDetector { - mock := &ReorgDetector{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/bridgesync/processor.go b/bridgesync/processor.go deleted file mode 100644 index b74976ccb..000000000 --- a/bridgesync/processor.go +++ /dev/null @@ -1,399 +0,0 @@ -package bridgesync - -import ( - "context" - "database/sql" - "encoding/binary" - "errors" - "fmt" - "math/big" - mutex "sync" - - "github.com/0xPolygon/cdk/bridgesync/migrations" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/0xPolygon/cdk/tree" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/iden3/go-iden3-crypto/keccak256" - "github.com/russross/meddler" - _ "modernc.org/sqlite" -) - -const ( - globalIndexPartSize = 4 - globalIndexMaxSize = 9 -) - -var ( - // errBlockNotProcessedFormat indicates that the given block(s) have not been processed yet. - errBlockNotProcessedFormat = fmt.Sprintf("block %%d not processed, last processed: %%d") -) - -// Bridge is the representation of a bridge event -type Bridge struct { - BlockNum uint64 `meddler:"block_num"` - BlockPos uint64 `meddler:"block_pos"` - LeafType uint8 `meddler:"leaf_type"` - OriginNetwork uint32 `meddler:"origin_network"` - OriginAddress common.Address `meddler:"origin_address"` - DestinationNetwork uint32 `meddler:"destination_network"` - DestinationAddress common.Address `meddler:"destination_address"` - Amount *big.Int `meddler:"amount,bigint"` - Metadata []byte `meddler:"metadata"` - DepositCount uint32 `meddler:"deposit_count"` -} - -// Hash returns the hash of the bridge event as expected by the exit tree -func (b *Bridge) Hash() common.Hash { - const ( - uint32ByteSize = 4 - bigIntSize = 32 - ) - origNet := make([]byte, uint32ByteSize) - binary.BigEndian.PutUint32(origNet, b.OriginNetwork) - destNet := make([]byte, uint32ByteSize) - binary.BigEndian.PutUint32(destNet, b.DestinationNetwork) - - metaHash := keccak256.Hash(b.Metadata) - var buf [bigIntSize]byte - if b.Amount == nil { - b.Amount = big.NewInt(0) - } - - return common.BytesToHash(keccak256.Hash( - []byte{b.LeafType}, - origNet, - b.OriginAddress[:], - destNet, - b.DestinationAddress[:], - b.Amount.FillBytes(buf[:]), - metaHash, - )) -} - -// Claim representation of a claim event -type Claim struct { - BlockNum uint64 `meddler:"block_num"` - BlockPos uint64 `meddler:"block_pos"` - GlobalIndex *big.Int `meddler:"global_index,bigint"` - OriginNetwork uint32 `meddler:"origin_network"` - OriginAddress common.Address `meddler:"origin_address"` - DestinationAddress common.Address `meddler:"destination_address"` - Amount *big.Int `meddler:"amount,bigint"` - ProofLocalExitRoot types.Proof `meddler:"proof_local_exit_root,merkleproof"` - ProofRollupExitRoot types.Proof `meddler:"proof_rollup_exit_root,merkleproof"` - MainnetExitRoot common.Hash `meddler:"mainnet_exit_root,hash"` - RollupExitRoot common.Hash `meddler:"rollup_exit_root,hash"` - GlobalExitRoot common.Hash `meddler:"global_exit_root,hash"` - DestinationNetwork uint32 `meddler:"destination_network"` - Metadata []byte `meddler:"metadata"` - IsMessage bool `meddler:"is_message"` -} - -// Event combination of bridge and claim events -type Event struct { - Pos uint64 - Bridge *Bridge - Claim *Claim -} - -type processor struct { - db *sql.DB - exitTree *tree.AppendOnlyTree - log *log.Logger - mu mutex.RWMutex - halted bool - haltedReason string -} - -func newProcessor(dbPath string, logger *log.Logger) (*processor, error) { - err := migrations.RunMigrations(dbPath) - if err != nil { - return nil, err - } - db, err := db.NewSQLiteDB(dbPath) - if err != nil { - return nil, err - } - - exitTree := tree.NewAppendOnlyTree(db, "") - return &processor{ - db: db, - exitTree: exitTree, - log: logger, - }, nil -} -func (p *processor) GetBridgesPublished( - ctx context.Context, fromBlock, toBlock uint64, -) ([]Bridge, error) { - return p.GetBridges(ctx, fromBlock, toBlock) -} - -func (p *processor) GetBridges( - ctx context.Context, fromBlock, toBlock uint64, -) ([]Bridge, error) { - tx, err := p.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) - if err != nil { - return nil, err - } - defer func() { - if err := tx.Rollback(); err != nil { - log.Warnf("error rolling back tx: %v", err) - } - }() - rows, err := p.queryBlockRange(tx, fromBlock, toBlock, "bridge") - if err != nil { - return nil, err - } - bridgePtrs := []*Bridge{} - if err = meddler.ScanAll(rows, &bridgePtrs); err != nil { - return nil, err - } - bridgesIface := db.SlicePtrsToSlice(bridgePtrs) - bridges, ok := bridgesIface.([]Bridge) - if !ok { - return nil, errors.New("failed to convert from []*Bridge to []Bridge") - } - return bridges, nil -} - -func (p *processor) GetClaims( - ctx context.Context, fromBlock, toBlock uint64, -) ([]Claim, error) { - tx, err := p.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) - if err != nil { - return nil, err - } - defer func() { - if err := tx.Rollback(); err != nil { - log.Warnf("error rolling back tx: %v", err) - } - }() - rows, err := p.queryBlockRange(tx, fromBlock, toBlock, "claim") - if err != nil { - return nil, err - } - claimPtrs := []*Claim{} - if err = meddler.ScanAll(rows, &claimPtrs); err != nil { - return nil, err - } - claimsIface := db.SlicePtrsToSlice(claimPtrs) - claims, ok := claimsIface.([]Claim) - if !ok { - return nil, errors.New("failed to convert from []*Claim to []Claim") - } - return claims, nil -} - -func (p *processor) queryBlockRange(tx db.Querier, fromBlock, toBlock uint64, table string) (*sql.Rows, error) { - if err := p.isBlockProcessed(tx, toBlock); err != nil { - return nil, err - } - rows, err := tx.Query(fmt.Sprintf(` - SELECT * FROM %s - WHERE block_num >= $1 AND block_num <= $2; - `, table), fromBlock, toBlock) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, db.ErrNotFound - } - return nil, err - } - return rows, nil -} - -func (p *processor) isBlockProcessed(tx db.Querier, blockNum uint64) error { - lpb, err := p.getLastProcessedBlockWithTx(tx) - if err != nil { - return err - } - if lpb < blockNum { - return fmt.Errorf(errBlockNotProcessedFormat, blockNum, lpb) - } - return nil -} - -// GetLastProcessedBlock returns the last processed block by the processor, including blocks -// that don't have events -func (p *processor) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - return p.getLastProcessedBlockWithTx(p.db) -} - -func (p *processor) getLastProcessedBlockWithTx(tx db.Querier) (uint64, error) { - var lastProcessedBlock uint64 - row := tx.QueryRow("SELECT num FROM block ORDER BY num DESC LIMIT 1;") - err := row.Scan(&lastProcessedBlock) - if errors.Is(err, sql.ErrNoRows) { - return 0, nil - } - return lastProcessedBlock, err -} - -// Reorg triggers a purge and reset process on the processor to leaf it on a state -// as if the last block processed was firstReorgedBlock-1 -func (p *processor) Reorg(ctx context.Context, firstReorgedBlock uint64) error { - tx, err := db.NewTx(ctx, p.db) - if err != nil { - return err - } - defer func() { - if err != nil { - if errRllbck := tx.Rollback(); errRllbck != nil { - log.Errorf("error while rolling back tx %v", errRllbck) - } - } - }() - - res, err := tx.Exec(`DELETE FROM block WHERE num >= $1;`, firstReorgedBlock) - if err != nil { - return err - } - rowsAffected, err := res.RowsAffected() - if err != nil { - return err - } - - if err = p.exitTree.Reorg(tx, firstReorgedBlock); err != nil { - return err - } - if err := tx.Commit(); err != nil { - return err - } - sync.UnhaltIfAffectedRows(&p.halted, &p.haltedReason, &p.mu, rowsAffected) - return nil -} - -// ProcessBlock process the events of the block to build the exit tree -// and updates the last processed block (can be called without events for that purpose) -func (p *processor) ProcessBlock(ctx context.Context, block sync.Block) error { - if p.isHalted() { - log.Errorf("processor is halted due to: %s", p.haltedReason) - return sync.ErrInconsistentState - } - tx, err := db.NewTx(ctx, p.db) - if err != nil { - return err - } - shouldRollback := true - defer func() { - if shouldRollback { - if errRllbck := tx.Rollback(); errRllbck != nil { - log.Errorf("error while rolling back tx %v", errRllbck) - } - } - }() - - if _, err := tx.Exec(`INSERT INTO block (num) VALUES ($1)`, block.Num); err != nil { - return err - } - for _, e := range block.Events { - event, ok := e.(Event) - if !ok { - return errors.New("failed to convert sync.Block.Event to Event") - } - if event.Bridge != nil { - if err = p.exitTree.AddLeaf(tx, block.Num, event.Pos, types.Leaf{ - Index: event.Bridge.DepositCount, - Hash: event.Bridge.Hash(), - }); err != nil { - if errors.Is(err, tree.ErrInvalidIndex) { - p.mu.Lock() - p.halted = true - p.haltedReason = fmt.Sprintf("error adding leaf to the exit tree: %v", err) - p.mu.Unlock() - } - return sync.ErrInconsistentState - } - if err = meddler.Insert(tx, "bridge", event.Bridge); err != nil { - return err - } - } - if event.Claim != nil { - if err = meddler.Insert(tx, "claim", event.Claim); err != nil { - return err - } - } - } - - if err := tx.Commit(); err != nil { - return err - } - shouldRollback = false - - p.log.Debugf("processed %d events until block %d", len(block.Events), block.Num) - return nil -} - -func GenerateGlobalIndex(mainnetFlag bool, rollupIndex uint32, localExitRootIndex uint32) *big.Int { - var ( - globalIndexBytes []byte - buf [globalIndexPartSize]byte - ) - if mainnetFlag { - globalIndexBytes = append(globalIndexBytes, big.NewInt(1).Bytes()...) - ri := big.NewInt(0).FillBytes(buf[:]) - globalIndexBytes = append(globalIndexBytes, ri...) - } else { - ri := big.NewInt(0).SetUint64(uint64(rollupIndex)).FillBytes(buf[:]) - globalIndexBytes = append(globalIndexBytes, ri...) - } - leri := big.NewInt(0).SetUint64(uint64(localExitRootIndex)).FillBytes(buf[:]) - globalIndexBytes = append(globalIndexBytes, leri...) - - result := big.NewInt(0).SetBytes(globalIndexBytes) - - return result -} - -// Decodes global index to its three parts: -// 1. mainnetFlag - first byte -// 2. rollupIndex - next 4 bytes -// 3. localExitRootIndex - last 4 bytes -// NOTE - mainnet flag is not in the global index bytes if it is false -// NOTE - rollup index is 0 if mainnet flag is true -// NOTE - rollup index is not in the global index bytes if mainnet flag is false and rollup index is 0 -func DecodeGlobalIndex(globalIndex *big.Int) (mainnetFlag bool, - rollupIndex uint32, localExitRootIndex uint32, err error) { - globalIndexBytes := globalIndex.Bytes() - l := len(globalIndexBytes) - if l > globalIndexMaxSize { - return false, 0, 0, errors.New("invalid global index length") - } - - if l == 0 { - // false, 0, 0 - return - } - - if l == globalIndexMaxSize { - // true, rollupIndex, localExitRootIndex - mainnetFlag = true - } - - localExitRootFromIdx := l - globalIndexPartSize - if localExitRootFromIdx < 0 { - localExitRootFromIdx = 0 - } - - rollupIndexFromIdx := localExitRootFromIdx - globalIndexPartSize - if rollupIndexFromIdx < 0 { - rollupIndexFromIdx = 0 - } - - rollupIndex = convertBytesToUint32(globalIndexBytes[rollupIndexFromIdx:localExitRootFromIdx]) - localExitRootIndex = convertBytesToUint32(globalIndexBytes[localExitRootFromIdx:]) - - return -} - -func convertBytesToUint32(bytes []byte) uint32 { - return uint32(big.NewInt(0).SetBytes(bytes).Uint64()) -} - -func (p *processor) isHalted() bool { - p.mu.RLock() - defer p.mu.RUnlock() - return p.halted -} diff --git a/bridgesync/processor_test.go b/bridgesync/processor_test.go deleted file mode 100644 index 594d54bb6..000000000 --- a/bridgesync/processor_test.go +++ /dev/null @@ -1,867 +0,0 @@ -package bridgesync - -import ( - "context" - "encoding/json" - "errors" - "fmt" - "math/big" - "os" - "path" - "slices" - "testing" - - migrationsBridge "github.com/0xPolygon/cdk/bridgesync/migrations" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/0xPolygon/cdk/tree/testvectors" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/russross/meddler" - "github.com/stretchr/testify/require" -) - -func TestBigIntString(t *testing.T) { - globalIndex := GenerateGlobalIndex(true, 0, 1093) - fmt.Println(globalIndex.String()) - - _, ok := new(big.Int).SetString(globalIndex.String(), 10) - require.True(t, ok) - - dbPath := path.Join(t.TempDir(), "bridgesyncTestBigIntString.sqlite") - - err := migrationsBridge.RunMigrations(dbPath) - require.NoError(t, err) - db, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - - ctx := context.Background() - tx, err := db.BeginTx(ctx, nil) - require.NoError(t, err) - - claim := &Claim{ - BlockNum: 1, - BlockPos: 0, - GlobalIndex: GenerateGlobalIndex(true, 0, 1093), - OriginNetwork: 11, - Amount: big.NewInt(11), - OriginAddress: common.HexToAddress("0x11"), - DestinationAddress: common.HexToAddress("0x11"), - ProofLocalExitRoot: types.Proof{}, - ProofRollupExitRoot: types.Proof{}, - MainnetExitRoot: common.Hash{}, - RollupExitRoot: common.Hash{}, - GlobalExitRoot: common.Hash{}, - DestinationNetwork: 12, - } - - _, err = tx.Exec(`INSERT INTO block (num) VALUES ($1)`, claim.BlockNum) - require.NoError(t, err) - require.NoError(t, meddler.Insert(tx, "claim", claim)) - - require.NoError(t, tx.Commit()) - - tx, err = db.BeginTx(ctx, nil) - require.NoError(t, err) - - rows, err := tx.Query(` - SELECT * FROM claim - WHERE block_num >= $1 AND block_num <= $2; - `, claim.BlockNum, claim.BlockNum) - require.NoError(t, err) - - claimsFromDB := []*Claim{} - require.NoError(t, meddler.ScanAll(rows, &claimsFromDB)) - require.Len(t, claimsFromDB, 1) - require.Equal(t, claim, claimsFromDB[0]) -} - -func TestProceessor(t *testing.T) { - path := path.Join(t.TempDir(), "bridgeSyncTestProcessor.sqlite") - logger := log.WithFields("bridge-syncer", "foo") - p, err := newProcessor(path, logger) - require.NoError(t, err) - actions := []processAction{ - // processed: ~ - &getLastProcessedBlockAction{ - p: p, - description: "on an empty processor", - ctx: context.Background(), - expectedLastProcessedBlock: 0, - expectedErr: nil, - }, - &reorgAction{ - p: p, - description: "on an empty processor: firstReorgedBlock = 0", - firstReorgedBlock: 0, - expectedErr: nil, - }, - &reorgAction{ - p: p, - description: "on an empty processor: firstReorgedBlock = 1", - firstReorgedBlock: 1, - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "on an empty processor", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedClaims: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 0), - }, - &getBridges{ - p: p, - description: "on an empty processor", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedBridges: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 0), - }, - &processBlockAction{ - p: p, - description: "block1", - block: block1, - expectedErr: nil, - }, - // processed: block1 - &getLastProcessedBlockAction{ - p: p, - description: "after block1", - ctx: context.Background(), - expectedLastProcessedBlock: 1, - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block1: range 0, 2", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedClaims: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 1), - }, - &getBridges{ - p: p, - description: "after block1: range 0, 2", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedBridges: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 1), - }, - &getClaims{ - p: p, - description: "after block1: range 1, 1", - ctx: context.Background(), - fromBlock: 1, - toBlock: 1, - expectedClaims: eventsToClaims(block1.Events), - expectedErr: nil, - }, - &getBridges{ - p: p, - description: "after block1: range 1, 1", - ctx: context.Background(), - fromBlock: 1, - toBlock: 1, - expectedBridges: eventsToBridges(block1.Events), - expectedErr: nil, - }, - &reorgAction{ - p: p, - description: "after block1", - firstReorgedBlock: 1, - expectedErr: nil, - }, - // processed: ~ - &getClaims{ - p: p, - description: "after block1 reorged", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedClaims: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 0), - }, - &getBridges{ - p: p, - description: "after block1 reorged", - ctx: context.Background(), - fromBlock: 0, - toBlock: 2, - expectedBridges: nil, - expectedErr: fmt.Errorf(errBlockNotProcessedFormat, 2, 0), - }, - &processBlockAction{ - p: p, - description: "block1 (after it's reorged)", - block: block1, - expectedErr: nil, - }, - // processed: block3 - &processBlockAction{ - p: p, - description: "block3", - block: block3, - expectedErr: nil, - }, - // processed: block1, block3 - &getLastProcessedBlockAction{ - p: p, - description: "after block3", - ctx: context.Background(), - expectedLastProcessedBlock: 3, - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block3: range 2, 2", - ctx: context.Background(), - fromBlock: 2, - toBlock: 2, - expectedClaims: []Claim{}, - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block3: range 1, 3", - ctx: context.Background(), - fromBlock: 1, - toBlock: 3, - expectedClaims: append( - eventsToClaims(block1.Events), - eventsToClaims(block3.Events)..., - ), - expectedErr: nil, - }, - &getBridges{ - p: p, - description: "after block3: range 2, 2", - ctx: context.Background(), - fromBlock: 2, - toBlock: 2, - expectedBridges: []Bridge{}, - expectedErr: nil, - }, - &getBridges{ - p: p, - description: "after block3: range 1, 3", - ctx: context.Background(), - fromBlock: 1, - toBlock: 3, - expectedBridges: append( - eventsToBridges(block1.Events), - eventsToBridges(block3.Events)..., - ), - expectedErr: nil, - }, - &reorgAction{ - p: p, - description: "after block3, with value 3", - firstReorgedBlock: 3, - expectedErr: nil, - }, - // processed: block1 - &getLastProcessedBlockAction{ - p: p, - description: "after block3 reorged", - ctx: context.Background(), - expectedLastProcessedBlock: 1, - expectedErr: nil, - }, - &reorgAction{ - p: p, - description: "after block3, with value 2", - firstReorgedBlock: 2, - expectedErr: nil, - }, - &getLastProcessedBlockAction{ - p: p, - description: "after block2 reorged", - ctx: context.Background(), - expectedLastProcessedBlock: 1, - expectedErr: nil, - }, - &processBlockAction{ - p: p, - description: "block3 after reorg", - block: block3, - expectedErr: nil, - }, - // processed: block1, block3 - &processBlockAction{ - p: p, - description: "block4", - block: block4, - expectedErr: nil, - }, - // processed: block1, block3, block4 - &processBlockAction{ - p: p, - description: "block5", - block: block5, - expectedErr: nil, - }, - // processed: block1, block3, block4, block5 - &getLastProcessedBlockAction{ - p: p, - description: "after block5", - ctx: context.Background(), - expectedLastProcessedBlock: 5, - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block5: range 1, 3", - ctx: context.Background(), - fromBlock: 1, - toBlock: 3, - expectedClaims: append( - eventsToClaims(block1.Events), - eventsToClaims(block3.Events)..., - ), - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block5: range 4, 5", - ctx: context.Background(), - fromBlock: 4, - toBlock: 5, - expectedClaims: append( - eventsToClaims(block4.Events), - eventsToClaims(block5.Events)..., - ), - expectedErr: nil, - }, - &getClaims{ - p: p, - description: "after block5: range 0, 5", - ctx: context.Background(), - fromBlock: 0, - toBlock: 5, - expectedClaims: slices.Concat( - eventsToClaims(block1.Events), - eventsToClaims(block3.Events), - eventsToClaims(block4.Events), - eventsToClaims(block5.Events), - ), - expectedErr: nil, - }, - } - - for _, a := range actions { - log.Debugf("%s: %s", a.method(), a.desc()) - a.execute(t) - } -} - -// BOILERPLATE - -// blocks - -var ( - block1 = sync.Block{ - Num: 1, - Events: []interface{}{ - Event{Bridge: &Bridge{ - BlockNum: 1, - BlockPos: 0, - LeafType: 1, - OriginNetwork: 1, - OriginAddress: common.HexToAddress("01"), - DestinationNetwork: 1, - DestinationAddress: common.HexToAddress("01"), - Amount: big.NewInt(1), - Metadata: common.Hex2Bytes("01"), - DepositCount: 0, - }}, - Event{Claim: &Claim{ - BlockNum: 1, - BlockPos: 1, - GlobalIndex: big.NewInt(1), - OriginNetwork: 1, - OriginAddress: common.HexToAddress("01"), - DestinationAddress: common.HexToAddress("01"), - Amount: big.NewInt(1), - }}, - }, - } - block3 = sync.Block{ - Num: 3, - Events: []interface{}{ - Event{Bridge: &Bridge{ - BlockNum: 3, - BlockPos: 0, - LeafType: 2, - OriginNetwork: 2, - OriginAddress: common.HexToAddress("02"), - DestinationNetwork: 2, - DestinationAddress: common.HexToAddress("02"), - Amount: big.NewInt(2), - Metadata: common.Hex2Bytes("02"), - DepositCount: 1, - }}, - Event{Bridge: &Bridge{ - BlockNum: 3, - BlockPos: 1, - LeafType: 3, - OriginNetwork: 3, - OriginAddress: common.HexToAddress("03"), - DestinationNetwork: 3, - DestinationAddress: common.HexToAddress("03"), - Amount: big.NewInt(0), - Metadata: common.Hex2Bytes("03"), - DepositCount: 2, - }}, - }, - } - block4 = sync.Block{ - Num: 4, - Events: []interface{}{}, - } - block5 = sync.Block{ - Num: 5, - Events: []interface{}{ - Event{Claim: &Claim{ - BlockNum: 4, - BlockPos: 0, - GlobalIndex: big.NewInt(4), - OriginNetwork: 4, - OriginAddress: common.HexToAddress("04"), - DestinationAddress: common.HexToAddress("04"), - Amount: big.NewInt(4), - }}, - Event{Claim: &Claim{ - BlockNum: 4, - BlockPos: 1, - GlobalIndex: big.NewInt(5), - OriginNetwork: 5, - OriginAddress: common.HexToAddress("05"), - DestinationAddress: common.HexToAddress("05"), - Amount: big.NewInt(5), - }}, - }, - } -) - -// actions - -type processAction interface { - method() string - desc() string - execute(t *testing.T) -} - -// GetClaims - -type getClaims struct { - p *processor - description string - ctx context.Context - fromBlock uint64 - toBlock uint64 - expectedClaims []Claim - expectedErr error -} - -func (a *getClaims) method() string { - return "GetClaims" -} - -func (a *getClaims) desc() string { - return a.description -} - -func (a *getClaims) execute(t *testing.T) { - t.Helper() - actualEvents, actualErr := a.p.GetClaims(a.ctx, a.fromBlock, a.toBlock) - require.Equal(t, a.expectedErr, actualErr) - require.Equal(t, a.expectedClaims, actualEvents) -} - -// GetBridges - -type getBridges struct { - p *processor - description string - ctx context.Context - fromBlock uint64 - toBlock uint64 - expectedBridges []Bridge - expectedErr error -} - -func (a *getBridges) method() string { - return "GetBridges" -} - -func (a *getBridges) desc() string { - return a.description -} - -func (a *getBridges) execute(t *testing.T) { - t.Helper() - actualEvents, actualErr := a.p.GetBridges(a.ctx, a.fromBlock, a.toBlock) - require.Equal(t, a.expectedBridges, actualEvents) - require.Equal(t, a.expectedErr, actualErr) -} - -// getLastProcessedBlock - -type getLastProcessedBlockAction struct { - p *processor - description string - ctx context.Context - expectedLastProcessedBlock uint64 - expectedErr error -} - -func (a *getLastProcessedBlockAction) method() string { - return "getLastProcessedBlock" -} - -func (a *getLastProcessedBlockAction) desc() string { - return a.description -} - -func (a *getLastProcessedBlockAction) execute(t *testing.T) { - t.Helper() - - actualLastProcessedBlock, actualErr := a.p.GetLastProcessedBlock(a.ctx) - require.Equal(t, a.expectedLastProcessedBlock, actualLastProcessedBlock) - require.Equal(t, a.expectedErr, actualErr) -} - -// reorg - -type reorgAction struct { - p *processor - description string - firstReorgedBlock uint64 - expectedErr error -} - -func (a *reorgAction) method() string { - return "reorg" -} - -func (a *reorgAction) desc() string { - return a.description -} - -func (a *reorgAction) execute(t *testing.T) { - t.Helper() - - actualErr := a.p.Reorg(context.Background(), a.firstReorgedBlock) - require.Equal(t, a.expectedErr, actualErr) -} - -// storeBridgeEvents - -type processBlockAction struct { - p *processor - description string - block sync.Block - expectedErr error -} - -func (a *processBlockAction) method() string { - return "storeBridgeEvents" -} - -func (a *processBlockAction) desc() string { - return a.description -} - -func (a *processBlockAction) execute(t *testing.T) { - t.Helper() - - actualErr := a.p.ProcessBlock(context.Background(), a.block) - require.Equal(t, a.expectedErr, actualErr) -} - -func eventsToBridges(events []interface{}) []Bridge { - bridges := []Bridge{} - for _, event := range events { - e, ok := event.(Event) - if !ok { - panic("should be ok") - } - if e.Bridge != nil { - bridges = append(bridges, *e.Bridge) - } - } - return bridges -} - -func eventsToClaims(events []interface{}) []Claim { - claims := []Claim{} - for _, event := range events { - e, ok := event.(Event) - if !ok { - panic("should be ok") - } - if e.Claim != nil { - claims = append(claims, *e.Claim) - } - } - return claims -} - -func TestHashBridge(t *testing.T) { - data, err := os.ReadFile("../tree/testvectors/leaf-vectors.json") - require.NoError(t, err) - - var leafVectors []testvectors.DepositVectorRaw - err = json.Unmarshal(data, &leafVectors) - require.NoError(t, err) - - for ti, testVector := range leafVectors { - t.Run(fmt.Sprintf("Test vector %d", ti), func(t *testing.T) { - amount, err := big.NewInt(0).SetString(testVector.Amount, 0) - require.True(t, err) - - bridge := Bridge{ - OriginNetwork: testVector.OriginNetwork, - OriginAddress: common.HexToAddress(testVector.TokenAddress), - Amount: amount, - DestinationNetwork: testVector.DestinationNetwork, - DestinationAddress: common.HexToAddress(testVector.DestinationAddress), - DepositCount: uint32(ti + 1), - Metadata: common.FromHex(testVector.Metadata), - } - require.Equal(t, common.HexToHash(testVector.ExpectedHash), bridge.Hash()) - }) - } -} - -func TestDecodeGlobalIndex(t *testing.T) { - t.Parallel() - - tests := []struct { - name string - globalIndex *big.Int - expectedMainnetFlag bool - expectedRollupIndex uint32 - expectedLocalIndex uint32 - expectedErr error - }{ - { - name: "Mainnet flag true, rollup index 0", - globalIndex: GenerateGlobalIndex(true, 0, 2), - expectedMainnetFlag: true, - expectedRollupIndex: 0, - expectedLocalIndex: 2, - expectedErr: nil, - }, - { - name: "Mainnet flag true, indexes 0", - globalIndex: GenerateGlobalIndex(true, 0, 0), - expectedMainnetFlag: true, - expectedRollupIndex: 0, - expectedLocalIndex: 0, - expectedErr: nil, - }, - { - name: "Mainnet flag false, rollup index 0", - globalIndex: GenerateGlobalIndex(false, 0, 2), - expectedMainnetFlag: false, - expectedRollupIndex: 0, - expectedLocalIndex: 2, - expectedErr: nil, - }, - { - name: "Mainnet flag false, rollup index non-zero", - globalIndex: GenerateGlobalIndex(false, 11, 0), - expectedMainnetFlag: false, - expectedRollupIndex: 11, - expectedLocalIndex: 0, - expectedErr: nil, - }, - { - name: "Mainnet flag false, indexes 0", - globalIndex: GenerateGlobalIndex(false, 0, 0), - expectedMainnetFlag: false, - expectedRollupIndex: 0, - expectedLocalIndex: 0, - expectedErr: nil, - }, - { - name: "Mainnet flag false, indexes non zero", - globalIndex: GenerateGlobalIndex(false, 1231, 111234), - expectedMainnetFlag: false, - expectedRollupIndex: 1231, - expectedLocalIndex: 111234, - expectedErr: nil, - }, - { - name: "Invalid global index length", - globalIndex: big.NewInt(0).SetBytes([]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}), - expectedMainnetFlag: false, - expectedRollupIndex: 0, - expectedLocalIndex: 0, - expectedErr: errors.New("invalid global index length"), - }, - } - - for _, tt := range tests { - tt := tt - - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - mainnetFlag, rollupIndex, localExitRootIndex, err := DecodeGlobalIndex(tt.globalIndex) - if tt.expectedErr != nil { - require.EqualError(t, err, tt.expectedErr.Error()) - } else { - require.NoError(t, err) - } - require.Equal(t, tt.expectedMainnetFlag, mainnetFlag) - require.Equal(t, tt.expectedRollupIndex, rollupIndex) - require.Equal(t, tt.expectedLocalIndex, localExitRootIndex) - }) - } -} - -func TestInsertAndGetClaim(t *testing.T) { - path := path.Join(t.TempDir(), "bridgeSyncerTestInsertAndGetClaim.sqlite") - log.Debugf("sqlite path: %s", path) - err := migrationsBridge.RunMigrations(path) - require.NoError(t, err) - logger := log.WithFields("bridge-syncer", "foo") - p, err := newProcessor(path, logger) - require.NoError(t, err) - - tx, err := p.db.BeginTx(context.Background(), nil) - require.NoError(t, err) - - // insert test claim - testClaim := &Claim{ - BlockNum: 1, - BlockPos: 0, - GlobalIndex: GenerateGlobalIndex(true, 0, 1093), - OriginNetwork: 11, - OriginAddress: common.HexToAddress("0x11"), - DestinationAddress: common.HexToAddress("0x11"), - Amount: big.NewInt(11), - ProofLocalExitRoot: types.Proof{}, - ProofRollupExitRoot: types.Proof{}, - MainnetExitRoot: common.Hash{}, - RollupExitRoot: common.Hash{}, - GlobalExitRoot: common.Hash{}, - DestinationNetwork: 12, - Metadata: []byte("0x11"), - IsMessage: false, - } - - _, err = tx.Exec(`INSERT INTO block (num) VALUES ($1)`, testClaim.BlockNum) - require.NoError(t, err) - require.NoError(t, meddler.Insert(tx, "claim", testClaim)) - - require.NoError(t, tx.Commit()) - - // get test claim - claims, err := p.GetClaims(context.Background(), 1, 1) - require.NoError(t, err) - require.Len(t, claims, 1) - require.Equal(t, testClaim, &claims[0]) -} - -func TestGetBridgesPublished(t *testing.T) { - t.Parallel() - - testCases := []struct { - name string - fromBlock uint64 - toBlock uint64 - bridges []Bridge - lastUpdatedDepositCount uint32 - expectedBridges []Bridge - expectedError error - }{ - { - name: "no bridges", - fromBlock: 1, - toBlock: 10, - bridges: []Bridge{}, - lastUpdatedDepositCount: 0, - expectedBridges: []Bridge{}, - expectedError: nil, - }, - { - name: "bridges within deposit count", - fromBlock: 1, - toBlock: 10, - bridges: []Bridge{ - {DepositCount: 1, BlockNum: 1, Amount: big.NewInt(1)}, - {DepositCount: 2, BlockNum: 2, Amount: big.NewInt(1)}, - }, - lastUpdatedDepositCount: 2, - expectedBridges: []Bridge{ - {DepositCount: 1, BlockNum: 1, Amount: big.NewInt(1)}, - {DepositCount: 2, BlockNum: 2, Amount: big.NewInt(1)}, - }, - expectedError: nil, - }, - } - - for _, tc := range testCases { - tc := tc - - t.Run(tc.name, func(t *testing.T) { - t.Parallel() - - path := path.Join(t.TempDir(), fmt.Sprintf("bridgesyncTestGetBridgesPublished_%s.sqlite", tc.name)) - require.NoError(t, migrationsBridge.RunMigrations(path)) - logger := log.WithFields("bridge-syncer", "foo") - p, err := newProcessor(path, logger) - require.NoError(t, err) - - tx, err := p.db.BeginTx(context.Background(), nil) - require.NoError(t, err) - - for i := tc.fromBlock; i <= tc.toBlock; i++ { - _, err = tx.Exec(`INSERT INTO block (num) VALUES ($1)`, i) - require.NoError(t, err) - } - - for _, bridge := range tc.bridges { - require.NoError(t, meddler.Insert(tx, "bridge", &bridge)) - } - - require.NoError(t, tx.Commit()) - - ctx := context.Background() - bridges, err := p.GetBridgesPublished(ctx, tc.fromBlock, tc.toBlock) - - if tc.expectedError != nil { - require.Equal(t, tc.expectedError, err) - } else { - require.NoError(t, err) - require.Equal(t, tc.expectedBridges, bridges) - } - }) - } -} - -func TestProcessBlockInvalidIndex(t *testing.T) { - path := path.Join(t.TempDir(), "testProcessorBlockInvalidIndex.sqlite") - logger := log.WithFields("bridge-syncer", "foo") - p, err := newProcessor(path, logger) - require.NoError(t, err) - err = p.ProcessBlock(context.Background(), sync.Block{ - Num: 0, - Events: []interface{}{ - Event{Bridge: &Bridge{DepositCount: 5}}, - }, - }) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) - require.True(t, p.halted) - err = p.ProcessBlock(context.Background(), sync.Block{}) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} diff --git a/build/docker-compose.yml b/build/docker-compose.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/claimsponsor/claimsponsor.go b/claimsponsor/claimsponsor.go deleted file mode 100644 index e93f18988..000000000 --- a/claimsponsor/claimsponsor.go +++ /dev/null @@ -1,246 +0,0 @@ -package claimsponsor - -import ( - "context" - "database/sql" - "errors" - "fmt" - "math/big" - "time" - - "github.com/0xPolygon/cdk/claimsponsor/migrations" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/russross/meddler" -) - -type ClaimStatus string - -const ( - PendingClaimStatus ClaimStatus = "pending" - WIPClaimStatus ClaimStatus = "work in progress" - SuccessClaimStatus ClaimStatus = "success" - FailedClaimStatus ClaimStatus = "failed" -) - -var ( - ErrInvalidClaim = errors.New("invalid claim") - ErrClaimDoesntExist = errors.New("the claim requested to be updated does not exist") -) - -// Claim representation of a claim event -type Claim struct { - LeafType uint8 `meddler:"leaf_type"` - ProofLocalExitRoot tree.Proof `meddler:"proof_local_exit_root,merkleproof"` - ProofRollupExitRoot tree.Proof `meddler:"proof_rollup_exit_root,merkleproof"` - GlobalIndex *big.Int `meddler:"global_index,bigint"` - MainnetExitRoot common.Hash `meddler:"mainnet_exit_root,hash"` - RollupExitRoot common.Hash `meddler:"rollup_exit_root,hash"` - OriginNetwork uint32 `meddler:"origin_network"` - OriginTokenAddress common.Address `meddler:"origin_token_address,address"` - DestinationNetwork uint32 `meddler:"destination_network"` - DestinationAddress common.Address `meddler:"destination_address,address"` - Amount *big.Int `meddler:"amount,bigint"` - Metadata []byte `meddler:"metadata"` - Status ClaimStatus `meddler:"status"` - TxID string `meddler:"tx_id"` -} - -func (c *Claim) Key() []byte { - return c.GlobalIndex.Bytes() -} - -type ClaimSender interface { - checkClaim(ctx context.Context, claim *Claim) error - sendClaim(ctx context.Context, claim *Claim) (string, error) - claimStatus(ctx context.Context, id string) (ClaimStatus, error) -} - -type ClaimSponsor struct { - logger *log.Logger - db *sql.DB - sender ClaimSender - rh *sync.RetryHandler - waitTxToBeMinedPeriod time.Duration - waitOnEmptyQueue time.Duration -} - -func newClaimSponsor( - logger *log.Logger, - dbPath string, - sender ClaimSender, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - waitTxToBeMinedPeriod time.Duration, - waitOnEmptyQueue time.Duration, -) (*ClaimSponsor, error) { - err := migrations.RunMigrations(dbPath) - if err != nil { - return nil, err - } - db, err := db.NewSQLiteDB(dbPath) - if err != nil { - return nil, err - } - rh := &sync.RetryHandler{ - MaxRetryAttemptsAfterError: maxRetryAttemptsAfterError, - RetryAfterErrorPeriod: retryAfterErrorPeriod, - } - - return &ClaimSponsor{ - logger: logger, - db: db, - sender: sender, - rh: rh, - waitTxToBeMinedPeriod: waitTxToBeMinedPeriod, - waitOnEmptyQueue: waitOnEmptyQueue, - }, nil -} - -func (c *ClaimSponsor) Start(ctx context.Context) { - attempts := 0 - - for { - select { - case <-ctx.Done(): - return - - default: - err := c.claim(ctx) - if err != nil { - attempts++ - c.logger.Error(err) - c.rh.Handle("claimsponsor main loop", attempts) - } else { - attempts = 0 - } - } - } -} - -func (c *ClaimSponsor) claim(ctx context.Context) error { - claim, err := c.getWIPClaim() - if err != nil && !errors.Is(err, db.ErrNotFound) { - return fmt.Errorf("error getting WIP claim: %w", err) - } - if errors.Is(err, db.ErrNotFound) || claim == nil { - // there is no WIP claim, go for the next pending claim - claim, err = c.getFirstPendingClaim() - if err != nil { - if errors.Is(err, db.ErrNotFound) { - c.logger.Debugf("queue is empty") - time.Sleep(c.waitOnEmptyQueue) - return nil - } - return fmt.Errorf("error calling getClaim with globalIndex %s: %w", claim.GlobalIndex.String(), err) - } - txID, err := c.sender.sendClaim(ctx, claim) - if err != nil { - return fmt.Errorf("error getting sending claim: %w", err) - } - if err := c.updateClaimTxID(claim.GlobalIndex, txID); err != nil { - return fmt.Errorf("error updating claim txID: %w", err) - } - } - - c.logger.Infof("waiting for tx %s with global index %s to be processed", claim.TxID, claim.GlobalIndex.String()) - status, err := c.waitForTxResult(ctx, claim.TxID) - if err != nil { - return fmt.Errorf("error calling waitForTxResult for tx %s: %w", claim.TxID, err) - } - c.logger.Infof("tx %s with global index %s is processed, status: %s", claim.TxID, claim.GlobalIndex.String(), status) - return c.updateClaimStatus(claim.GlobalIndex, status) -} - -func (c *ClaimSponsor) getWIPClaim() (*Claim, error) { - claim := &Claim{} - err := meddler.QueryRow( - c.db, claim, - `SELECT * FROM claim WHERE status = $1 ORDER BY rowid ASC LIMIT 1;`, - WIPClaimStatus, - ) - return claim, db.ReturnErrNotFound(err) -} - -func (c *ClaimSponsor) getFirstPendingClaim() (*Claim, error) { - claim := &Claim{} - err := meddler.QueryRow( - c.db, claim, - `SELECT * FROM claim WHERE status = $1 ORDER BY rowid ASC LIMIT 1;`, - PendingClaimStatus, - ) - return claim, db.ReturnErrNotFound(err) -} - -func (c *ClaimSponsor) updateClaimTxID(globalIndex *big.Int, txID string) error { - res, err := c.db.Exec( - `UPDATE claim SET tx_id = $1 WHERE global_index = $2`, - txID, globalIndex.String(), - ) - if err != nil { - return fmt.Errorf("error updating claim status: %w", err) - } - rowsAff, err := res.RowsAffected() - if err != nil { - return fmt.Errorf("error getting rows affected: %w", err) - } - if rowsAff == 0 { - return ErrClaimDoesntExist - } - return nil -} - -func (c *ClaimSponsor) updateClaimStatus(globalIndex *big.Int, status ClaimStatus) error { - res, err := c.db.Exec( - `UPDATE claim SET status = $1 WHERE global_index = $2`, - status, globalIndex.String(), - ) - if err != nil { - return fmt.Errorf("error updating claim status: %w", err) - } - rowsAff, err := res.RowsAffected() - if err != nil { - return fmt.Errorf("error getting rows affected: %w", err) - } - if rowsAff == 0 { - return ErrClaimDoesntExist - } - return nil -} - -func (c *ClaimSponsor) waitForTxResult(ctx context.Context, txID string) (ClaimStatus, error) { - ticker := time.NewTicker(c.waitTxToBeMinedPeriod) - defer ticker.Stop() - - for { - select { - case <-ctx.Done(): - return "", errors.New("context cancelled") - case <-ticker.C: - status, err := c.sender.claimStatus(ctx, txID) - if err != nil { - return "", err - } - - if status == FailedClaimStatus || status == SuccessClaimStatus { - return status, nil - } - } - } -} - -func (c *ClaimSponsor) AddClaimToQueue(claim *Claim) error { - claim.Status = PendingClaimStatus - return meddler.Insert(c.db, "claim", claim) -} - -func (c *ClaimSponsor) GetClaim(globalIndex *big.Int) (*Claim, error) { - claim := &Claim{} - err := meddler.QueryRow( - c.db, claim, `SELECT * FROM claim WHERE global_index = $1`, globalIndex.String(), - ) - return claim, db.ReturnErrNotFound(err) -} diff --git a/claimsponsor/e2e_test.go b/claimsponsor/e2e_test.go deleted file mode 100644 index f64b6aa71..000000000 --- a/claimsponsor/e2e_test.go +++ /dev/null @@ -1,110 +0,0 @@ -package claimsponsor_test - -import ( - "context" - "errors" - "fmt" - "math/big" - "path" - "testing" - "time" - - "github.com/0xPolygon/cdk/bridgesync" - "github.com/0xPolygon/cdk/claimsponsor" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/test/helpers" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestE2EL1toEVML2(t *testing.T) { - // start other needed components - ctx := context.Background() - l1Env, l2Env := helpers.NewL1EnvWithL2EVM(t) - - // start claim sponsor - dbPathClaimSponsor := path.Join(t.TempDir(), "claimsponsorTestE2EL1toEVML2_cs.sqlite") - claimer, err := claimsponsor.NewEVMClaimSponsor( - log.GetDefaultLogger(), - dbPathClaimSponsor, - l2Env.SimBackend.Client(), - l2Env.BridgeAddr, - l2Env.Auth.From, - 200_000, - 0, - l2Env.EthTxManagerMock, - 0, 0, time.Millisecond*10, time.Millisecond*10, - ) - require.NoError(t, err) - go claimer.Start(ctx) - - // test - for i := uint32(0); i < 3; i++ { - // Send bridges to L2, wait for GER to be injected on L2 - amount := new(big.Int).SetUint64(uint64(i) + 1) - l1Env.Auth.Value = amount - _, err := l1Env.BridgeContract.BridgeAsset(l1Env.Auth, l2Env.NetworkID, l2Env.Auth.From, amount, common.Address{}, true, nil) - require.NoError(t, err) - l1Env.SimBackend.Commit() - time.Sleep(time.Millisecond * 300) - - expectedGER, err := l1Env.GERContract.GetLastGlobalExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - _, err = l2Env.GERContract.InsertGlobalExitRoot(l2Env.Auth, expectedGER) - require.NoError(t, err) - l2Env.SimBackend.Commit() - gerIndex, err := l2Env.GERContract.GlobalExitRootMap(nil, expectedGER) - require.NoError(t, err) - require.Equal(t, big.NewInt(int64(i)+1), gerIndex, fmt.Sprintf("iteration %d, GER: %s is not updated on L2", i, common.Bytes2Hex(expectedGER[:]))) - - // Build MP using bridgeSyncL1 & env.InfoTreeSync - info, err := l1Env.InfoTreeSync.GetInfoByIndex(ctx, i) - require.NoError(t, err) - - localProof, err := l1Env.BridgeSync.GetProof(ctx, i, info.MainnetExitRoot) - require.NoError(t, err) - - rollupProof, err := l1Env.InfoTreeSync.GetRollupExitTreeMerkleProof(ctx, 0, common.Hash{}) - require.NoError(t, err) - - // Request to sponsor claim - globalIndex := bridgesync.GenerateGlobalIndex(true, 0, i) - err = claimer.AddClaimToQueue(&claimsponsor.Claim{ - LeafType: claimsponsor.LeafTypeAsset, - ProofLocalExitRoot: localProof, - ProofRollupExitRoot: rollupProof, - GlobalIndex: globalIndex, - MainnetExitRoot: info.MainnetExitRoot, - RollupExitRoot: info.RollupExitRoot, - OriginNetwork: 0, - OriginTokenAddress: common.Address{}, - DestinationNetwork: l2Env.NetworkID, - DestinationAddress: l2Env.Auth.From, - Amount: amount, - Metadata: nil, - }) - require.NoError(t, err) - - // Wait until success - succeed := false - for i := 0; i < 10; i++ { - claim, err := claimer.GetClaim(globalIndex) - require.NoError(t, err) - if claim.Status == claimsponsor.FailedClaimStatus { - require.NoError(t, errors.New("claim failed")) - } else if claim.Status == claimsponsor.SuccessClaimStatus { - succeed = true - - break - } - time.Sleep(100 * time.Millisecond) - } - require.True(t, succeed) - - // Check on contract that is claimed - isClaimed, err := l2Env.BridgeContract.IsClaimed(&bind.CallOpts{Pending: false}, i, 0) - require.NoError(t, err) - require.True(t, isClaimed) - } -} diff --git a/claimsponsor/evmclaimsponsor.go b/claimsponsor/evmclaimsponsor.go deleted file mode 100644 index 8915c6836..000000000 --- a/claimsponsor/evmclaimsponsor.go +++ /dev/null @@ -1,215 +0,0 @@ -package claimsponsor - -import ( - "context" - "fmt" - "math/big" - "time" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmbridgev2" - configTypes "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" - ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" -) - -const ( - // LeafTypeAsset represents a bridge asset - LeafTypeAsset uint8 = 0 - // LeafTypeMessage represents a bridge message - LeafTypeMessage uint8 = 1 - - gasTooHighErrTemplate = "Claim tx estimated to consume more gas than the maximum allowed by the service. " + - "Estimated %d, maximum allowed: %d" -) - -type EthClienter interface { - ethereum.GasEstimator - bind.ContractBackend -} - -type EthTxManager interface { - Remove(ctx context.Context, id common.Hash) error - ResultsByStatus(ctx context.Context, statuses []ethtxtypes.MonitoredTxStatus) ([]ethtxtypes.MonitoredTxResult, error) - Result(ctx context.Context, id common.Hash) (ethtxtypes.MonitoredTxResult, error) - Add(ctx context.Context, to *common.Address, value *big.Int, data []byte, - gasOffset uint64, sidecar *types.BlobTxSidecar) (common.Hash, error) -} - -type EVMClaimSponsor struct { - l2Client EthClienter - bridgeABI *abi.ABI - bridgeAddr common.Address - ethTxManager EthTxManager - sender common.Address - gasOffest uint64 - maxGas uint64 -} - -type EVMClaimSponsorConfig struct { - // DBPath path of the DB - DBPath string `mapstructure:"DBPath"` - // Enabled indicates if the sponsor should be run or not - Enabled bool `mapstructure:"Enabled"` - // SenderAddr is the address that will be used to send the claim txs - SenderAddr common.Address `mapstructure:"SenderAddr"` - // BridgeAddrL2 is the address of the bridge smart contract on L2 - BridgeAddrL2 common.Address `mapstructure:"BridgeAddrL2"` - // MaxGas is the max gas (limit) allowed for a claim to be sponsored - MaxGas uint64 `mapstructure:"MaxGas"` - // RetryAfterErrorPeriod is the time that will be waited when an unexpected error happens before retry - RetryAfterErrorPeriod configTypes.Duration `mapstructure:"RetryAfterErrorPeriod"` - // MaxRetryAttemptsAfterError is the maximum number of consecutive attempts that will happen before panicing. - // Any number smaller than zero will be considered as unlimited retries - MaxRetryAttemptsAfterError int `mapstructure:"MaxRetryAttemptsAfterError"` - // WaitTxToBeMinedPeriod is the period that will be used to ask if a given tx has been mined (or failed) - WaitTxToBeMinedPeriod configTypes.Duration `mapstructure:"WaitTxToBeMinedPeriod"` - // WaitOnEmptyQueue is the time that will be waited before trying to send the next claim of the queue - // if the queue is empty - WaitOnEmptyQueue configTypes.Duration `mapstructure:"WaitOnEmptyQueue"` - // EthTxManager is the configuration of the EthTxManager to be used by the claim sponsor - EthTxManager ethtxmanager.Config `mapstructure:"EthTxManager"` - // GasOffset is the gas to add on top of the estimated gas when sending the claim txs - GasOffset uint64 `mapstructure:"GasOffset"` -} - -func NewEVMClaimSponsor( - logger *log.Logger, - dbPath string, - l2Client EthClienter, - bridgeAddr common.Address, - sender common.Address, - maxGas, gasOffset uint64, - ethTxManager EthTxManager, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - waitTxToBeMinedPeriod time.Duration, - waitOnEmptyQueue time.Duration, -) (*ClaimSponsor, error) { - abi, err := polygonzkevmbridgev2.Polygonzkevmbridgev2MetaData.GetAbi() - if err != nil { - return nil, err - } - - evmSponsor := &EVMClaimSponsor{ - l2Client: l2Client, - bridgeABI: abi, - bridgeAddr: bridgeAddr, - sender: sender, - gasOffest: gasOffset, - maxGas: maxGas, - ethTxManager: ethTxManager, - } - - baseSponsor, err := newClaimSponsor( - logger, - dbPath, - evmSponsor, - retryAfterErrorPeriod, - maxRetryAttemptsAfterError, - waitTxToBeMinedPeriod, - waitOnEmptyQueue, - ) - if err != nil { - return nil, err - } - - return baseSponsor, nil -} - -func (c *EVMClaimSponsor) checkClaim(ctx context.Context, claim *Claim) error { - data, err := c.buildClaimTxData(claim) - if err != nil { - return err - } - gas, err := c.l2Client.EstimateGas(ctx, ethereum.CallMsg{ - From: c.sender, - To: &c.bridgeAddr, - Data: data, - }) - if err != nil { - return err - } - if gas > c.maxGas { - return fmt.Errorf(gasTooHighErrTemplate, gas, c.maxGas) - } - - return nil -} - -func (c *EVMClaimSponsor) sendClaim(ctx context.Context, claim *Claim) (string, error) { - data, err := c.buildClaimTxData(claim) - if err != nil { - return "", err - } - id, err := c.ethTxManager.Add(ctx, &c.bridgeAddr, common.Big0, data, c.gasOffest, nil) - if err != nil { - return "", err - } - - return id.Hex(), nil -} - -func (c *EVMClaimSponsor) claimStatus(ctx context.Context, id string) (ClaimStatus, error) { - res, err := c.ethTxManager.Result(ctx, common.HexToHash(id)) - if err != nil { - return "", err - } - switch res.Status { - case ethtxtypes.MonitoredTxStatusCreated, - ethtxtypes.MonitoredTxStatusSent: - return WIPClaimStatus, nil - case ethtxtypes.MonitoredTxStatusFailed: - return FailedClaimStatus, nil - case ethtxtypes.MonitoredTxStatusMined, - ethtxtypes.MonitoredTxStatusSafe, - ethtxtypes.MonitoredTxStatusFinalized: - log.Infof("claim tx with id %s mined at block %d", id, res.MinedAtBlockNumber) - - return SuccessClaimStatus, nil - default: - return "", fmt.Errorf("unexpected tx status: %v", res.Status) - } -} - -func (c *EVMClaimSponsor) buildClaimTxData(claim *Claim) ([]byte, error) { - switch claim.LeafType { - case LeafTypeAsset: - return c.bridgeABI.Pack( - "claimAsset", - claim.ProofLocalExitRoot, // bytes32[32] smtProofLocalExitRoot - claim.ProofRollupExitRoot, // bytes32[32] smtProofRollupExitRoot - claim.GlobalIndex, // uint256 globalIndex - claim.MainnetExitRoot, // bytes32 mainnetExitRoot - claim.RollupExitRoot, // bytes32 rollupExitRoot - claim.OriginNetwork, // uint32 originNetwork - claim.OriginTokenAddress, // address originTokenAddress, - claim.DestinationNetwork, // uint32 destinationNetwork - claim.DestinationAddress, // address destinationAddress - claim.Amount, // uint256 amount - claim.Metadata, // bytes metadata - ) - case LeafTypeMessage: - return c.bridgeABI.Pack( - "claimMessage", - claim.ProofLocalExitRoot, // bytes32[32] smtProofLocalExitRoot - claim.ProofRollupExitRoot, // bytes32[32] smtProofRollupExitRoot - claim.GlobalIndex, // uint256 globalIndex - claim.MainnetExitRoot, // bytes32 mainnetExitRoot - claim.RollupExitRoot, // bytes32 rollupExitRoot - claim.OriginNetwork, // uint32 originNetwork - claim.OriginTokenAddress, // address originTokenAddress, - claim.DestinationNetwork, // uint32 destinationNetwork - claim.DestinationAddress, // address destinationAddress - claim.Amount, // uint256 amount - claim.Metadata, // bytes metadata - ) - default: - return nil, fmt.Errorf("unexpected leaf type %d", claim.LeafType) - } -} diff --git a/claimsponsor/migrations/claimsponsor0001.sql b/claimsponsor/migrations/claimsponsor0001.sql deleted file mode 100644 index 9e4586ea3..000000000 --- a/claimsponsor/migrations/claimsponsor0001.sql +++ /dev/null @@ -1,20 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS claim; - --- +migrate Up -CREATE TABLE claim ( - leaf_type INT NOT NULL, - proof_local_exit_root VARCHAR NOT NULL, - proof_rollup_exit_root VARCHAR NOT NULL, - global_index VARCHAR NOT NULL, - mainnet_exit_root VARCHAR NOT NULL, - rollup_exit_root VARCHAR NOT NULL, - origin_network INT NOT NULL, - origin_token_address VARCHAR NOT NULL, - destination_network INT NOT NULL, - destination_address VARCHAR NOT NULL, - amount VARCHAR NOT NULL, - metadata VARCHAR, - status VARCHAR NOT NULL, - tx_id VARCHAR NOT NULL -); \ No newline at end of file diff --git a/claimsponsor/migrations/migrations.go b/claimsponsor/migrations/migrations.go deleted file mode 100644 index 9166b5b3a..000000000 --- a/claimsponsor/migrations/migrations.go +++ /dev/null @@ -1,21 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" -) - -//go:embed claimsponsor0001.sql -var mig001 string - -func RunMigrations(dbPath string) error { - migrations := []types.Migration{ - { - ID: "claimsponsor0001", - SQL: mig001, - }, - } - return db.RunMigrations(dbPath, migrations) -} diff --git a/cmd/main.go b/cmd/main.go index 39a9df30b..c2718af24 100644 --- a/cmd/main.go +++ b/cmd/main.go @@ -6,17 +6,12 @@ import ( zkevm "github.com/0xPolygon/cdk" "github.com/0xPolygon/cdk/common" "github.com/0xPolygon/cdk/config" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/urfave/cli/v2" ) const appName = "cdk" -const ( - // NETWORK_CONFIGFILE name to identify the network_custom (genesis) config-file - NETWORK_CONFIGFILE = "custom_network" //nolint:stylecheck -) - var ( configFileFlag = cli.StringSliceFlag{ Name: config.FlagCfg, @@ -41,7 +36,7 @@ var ( Aliases: []string{"co"}, Usage: "List of components to run", Required: false, - Value: cli.NewStringSlice(common.SEQUENCE_SENDER, common.AGGREGATOR, common.BRIDGE), + Value: cli.NewStringSlice(common.SEQUENCE_SENDER, common.AGGREGATOR), } saveConfigFlag = cli.StringFlag{ Name: config.FlagSaveConfigPath, diff --git a/cmd/run.go b/cmd/run.go index 68120be3f..7de38f724 100644 --- a/cmd/run.go +++ b/cmd/run.go @@ -14,8 +14,6 @@ import ( jRPC "github.com/0xPolygon/cdk-rpc/rpc" "github.com/0xPolygon/cdk/aggregator" "github.com/0xPolygon/cdk/aggregator/db" - "github.com/0xPolygon/cdk/bridgesync" - "github.com/0xPolygon/cdk/claimsponsor" cdkcommon "github.com/0xPolygon/cdk/common" "github.com/0xPolygon/cdk/config" "github.com/0xPolygon/cdk/dataavailability" @@ -23,17 +21,15 @@ import ( "github.com/0xPolygon/cdk/etherman" ethermanconfig "github.com/0xPolygon/cdk/etherman/config" "github.com/0xPolygon/cdk/etherman/contracts" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/lastgersync" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/reorgdetector" - "github.com/0xPolygon/cdk/rpc" "github.com/0xPolygon/cdk/sequencesender" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/translator" ethtxman "github.com/0xPolygon/zkevm-ethtx-manager/etherman" "github.com/0xPolygon/zkevm-ethtx-manager/etherman/etherscan" - "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" + aggkitetherman "github.com/agglayer/aggkit/etherman" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" + "github.com/agglayer/aggkit/reorgdetector" "github.com/ethereum/go-ethereum/ethclient" "github.com/urfave/cli/v2" ) @@ -55,7 +51,6 @@ func start(cliCtx *cli.Context) error { components := cliCtx.StringSlice(config.FlagComponents) l1Client := runL1ClientIfNeeded(components, cfg.Etherman.URL) - l2Client := runL2ClientIfNeeded(components, getL2RPCUrl(cfg)) reorgDetectorL1, errChanL1 := runReorgDetectorL1IfNeeded(cliCtx.Context, components, l1Client, &cfg.ReorgDetectorL1) go func() { if err := <-errChanL1; err != nil { @@ -63,23 +58,7 @@ func start(cliCtx *cli.Context) error { } }() - reorgDetectorL2, errChanL2 := runReorgDetectorL2IfNeeded(cliCtx.Context, components, l2Client, &cfg.ReorgDetectorL2) - go func() { - if err := <-errChanL2; err != nil { - log.Fatal("Error from ReorgDetectorL2: ", err) - } - }() - - rollupID := getRollupID(cfg.NetworkConfig.L1Config, l1Client) l1InfoTreeSync := runL1InfoTreeSyncerIfNeeded(cliCtx.Context, components, *cfg, l1Client, reorgDetectorL1) - claimSponsor := runClaimSponsorIfNeeded(cliCtx.Context, components, l2Client, cfg.ClaimSponsor) - l1BridgeSync := runBridgeSyncL1IfNeeded(cliCtx.Context, components, cfg.BridgeL1Sync, reorgDetectorL1, - l1Client, 0) - l2BridgeSync := runBridgeSyncL2IfNeeded(cliCtx.Context, components, cfg.BridgeL2Sync, reorgDetectorL2, - l2Client, rollupID) - lastGERSync := runLastGERSyncIfNeeded( - cliCtx.Context, components, cfg.LastGERSync, reorgDetectorL2, l2Client, l1InfoTreeSync, - ) var rpcServices []jRPC.Service for _, component := range components { switch component { @@ -98,18 +77,6 @@ func start(cliCtx *cli.Context) error { log.Fatal(err) } }() - - case cdkcommon.BRIDGE: - rpcBridge := createBridgeRPC( - cfg.RPC, - cfg.Common.NetworkID, - claimSponsor, - l1InfoTreeSync, - lastGERSync, - l1BridgeSync, - l2BridgeSync, - ) - rpcServices = append(rpcServices, rpcBridge...) } } if len(rpcServices) > 0 { @@ -401,8 +368,7 @@ func runL1InfoTreeSyncerIfNeeded( l1Client *ethclient.Client, reorgDetector *reorgdetector.ReorgDetector, ) *l1infotreesync.L1InfoTreeSync { - if !isNeeded([]string{cdkcommon.BRIDGE, - cdkcommon.SEQUENCE_SENDER, cdkcommon.L1INFOTREESYNC}, components) { + if !isNeeded([]string{cdkcommon.SEQUENCE_SENDER, cdkcommon.L1INFOTREESYNC}, components) { return nil } l1InfoTreeSync, err := l1infotreesync.New( @@ -411,7 +377,7 @@ func runL1InfoTreeSyncerIfNeeded( cfg.L1InfoTreeSync.GlobalExitRootAddr, cfg.L1InfoTreeSync.RollupManagerAddr, cfg.L1InfoTreeSync.SyncBlockChunkSize, - etherman.BlockNumberFinality(cfg.L1InfoTreeSync.BlockFinality), + aggkitetherman.NewBlockNumberFinality(cfg.L1InfoTreeSync.BlockFinality), reorgDetector, l1Client, cfg.L1InfoTreeSync.WaitForNewBlocksPeriod.Duration, @@ -419,7 +385,7 @@ func runL1InfoTreeSyncerIfNeeded( cfg.L1InfoTreeSync.RetryAfterErrorPeriod.Duration, cfg.L1InfoTreeSync.MaxRetryAttemptsAfterError, l1infotreesync.FlagNone, - etherman.FinalizedBlock, + aggkitetherman.FinalizedBlock, ) if err != nil { log.Fatal(err) @@ -431,8 +397,7 @@ func runL1InfoTreeSyncerIfNeeded( func runL1ClientIfNeeded(components []string, urlRPCL1 string) *ethclient.Client { if !isNeeded([]string{ - cdkcommon.SEQUENCE_SENDER, cdkcommon.AGGREGATOR, - cdkcommon.BRIDGE, cdkcommon.L1INFOTREESYNC, + cdkcommon.SEQUENCE_SENDER, cdkcommon.AGGREGATOR, cdkcommon.L1INFOTREESYNC, }, components) { return nil } @@ -454,29 +419,13 @@ func getRollupID(networkConfig ethermanconfig.L1Config, return rollupID } -func runL2ClientIfNeeded(components []string, urlRPCL2 string) *ethclient.Client { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) { - return nil - } - - log.Infof("dialing L2 client at: %s", urlRPCL2) - l2CLient, err := ethclient.Dial(urlRPCL2) - if err != nil { - log.Fatal(err) - } - - return l2CLient -} - func runReorgDetectorL1IfNeeded( ctx context.Context, components []string, l1Client *ethclient.Client, cfg *reorgdetector.Config, ) (*reorgdetector.ReorgDetector, chan error) { - if !isNeeded([]string{ - cdkcommon.SEQUENCE_SENDER, cdkcommon.AGGREGATOR, - cdkcommon.BRIDGE, cdkcommon.L1INFOTREESYNC}, + if !isNeeded([]string{cdkcommon.SEQUENCE_SENDER, cdkcommon.AGGREGATOR, cdkcommon.L1INFOTREESYNC}, components) { return nil, nil } @@ -493,201 +442,6 @@ func runReorgDetectorL1IfNeeded( return rd, errChan } -func runReorgDetectorL2IfNeeded( - ctx context.Context, - components []string, - l2Client *ethclient.Client, - cfg *reorgdetector.Config, -) (*reorgdetector.ReorgDetector, chan error) { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) { - return nil, nil - } - rd := newReorgDetector(cfg, l2Client, reorgdetector.L2) - - errChan := make(chan error) - go func() { - if err := rd.Start(ctx); err != nil { - errChan <- err - } - close(errChan) - }() - - return rd, errChan -} - -func runClaimSponsorIfNeeded( - ctx context.Context, - components []string, - l2Client *ethclient.Client, - cfg claimsponsor.EVMClaimSponsorConfig, -) *claimsponsor.ClaimSponsor { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) || !cfg.Enabled { - return nil - } - - logger := log.WithFields("module", cdkcommon.CLAIM_SPONSOR) - // In the future there may support different backends other than EVM, and this will require different config. - // But today only EVM is supported - ethTxManagerL2, err := ethtxmanager.New(cfg.EthTxManager) - if err != nil { - logger.Fatal(err) - } - go ethTxManagerL2.Start() - cs, err := claimsponsor.NewEVMClaimSponsor( - logger, - cfg.DBPath, - l2Client, - cfg.BridgeAddrL2, - cfg.SenderAddr, - cfg.MaxGas, - cfg.GasOffset, - ethTxManagerL2, - cfg.RetryAfterErrorPeriod.Duration, - cfg.MaxRetryAttemptsAfterError, - cfg.WaitTxToBeMinedPeriod.Duration, - cfg.WaitTxToBeMinedPeriod.Duration, - ) - if err != nil { - logger.Fatalf("error creating claim sponsor: %s", err) - } - go cs.Start(ctx) - - return cs -} - -func runLastGERSyncIfNeeded( - ctx context.Context, - components []string, - cfg lastgersync.Config, - reorgDetectorL2 *reorgdetector.ReorgDetector, - l2Client *ethclient.Client, - l1InfoTreeSync *l1infotreesync.L1InfoTreeSync, -) *lastgersync.LastGERSync { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) { - return nil - } - lastGERSync, err := lastgersync.New( - ctx, - cfg.DBPath, - reorgDetectorL2, - l2Client, - cfg.GlobalExitRootL2Addr, - l1InfoTreeSync, - cfg.RetryAfterErrorPeriod.Duration, - cfg.MaxRetryAttemptsAfterError, - etherman.BlockNumberFinality(cfg.BlockFinality), - cfg.WaitForNewBlocksPeriod.Duration, - cfg.DownloadBufferSize, - ) - if err != nil { - log.Fatalf("error creating lastGERSync: %s", err) - } - go lastGERSync.Start(ctx) - - return lastGERSync -} - -func runBridgeSyncL1IfNeeded( - ctx context.Context, - components []string, - cfg bridgesync.Config, - reorgDetectorL1 *reorgdetector.ReorgDetector, - l1Client *ethclient.Client, - rollupID uint32, -) *bridgesync.BridgeSync { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) { - return nil - } - - bridgeSyncL1, err := bridgesync.NewL1( - ctx, - cfg.DBPath, - cfg.BridgeAddr, - cfg.SyncBlockChunkSize, - etherman.BlockNumberFinality(cfg.BlockFinality), - reorgDetectorL1, - l1Client, - cfg.InitialBlockNum, - cfg.WaitForNewBlocksPeriod.Duration, - cfg.RetryAfterErrorPeriod.Duration, - cfg.MaxRetryAttemptsAfterError, - rollupID, - false, - etherman.FinalizedBlock, - ) - if err != nil { - log.Fatalf("error creating bridgeSyncL1: %s", err) - } - go bridgeSyncL1.Start(ctx) - - return bridgeSyncL1 -} - -func runBridgeSyncL2IfNeeded( - ctx context.Context, - components []string, - cfg bridgesync.Config, - reorgDetectorL2 *reorgdetector.ReorgDetector, - l2Client *ethclient.Client, - rollupID uint32, -) *bridgesync.BridgeSync { - if !isNeeded([]string{cdkcommon.BRIDGE}, components) { - return nil - } - - bridgeSyncL2, err := bridgesync.NewL2( - ctx, - cfg.DBPath, - cfg.BridgeAddr, - cfg.SyncBlockChunkSize, - etherman.BlockNumberFinality(cfg.BlockFinality), - reorgDetectorL2, - l2Client, - cfg.InitialBlockNum, - cfg.WaitForNewBlocksPeriod.Duration, - cfg.RetryAfterErrorPeriod.Duration, - cfg.MaxRetryAttemptsAfterError, - rollupID, - true, - etherman.LatestBlock, - ) - if err != nil { - log.Fatalf("error creating bridgeSyncL2: %s", err) - } - go bridgeSyncL2.Start(ctx) - - return bridgeSyncL2 -} - -func createBridgeRPC( - cfg jRPC.Config, - cdkNetworkID uint32, - sponsor *claimsponsor.ClaimSponsor, - l1InfoTree *l1infotreesync.L1InfoTreeSync, - injectedGERs *lastgersync.LastGERSync, - bridgeL1 *bridgesync.BridgeSync, - bridgeL2 *bridgesync.BridgeSync, -) []jRPC.Service { - logger := log.WithFields("module", cdkcommon.BRIDGE) - services := []jRPC.Service{ - { - Name: rpc.BRIDGE, - Service: rpc.NewBridgeEndpoints( - logger, - cfg.WriteTimeout.Duration, - cfg.ReadTimeout.Duration, - cdkNetworkID, - sponsor, - l1InfoTree, - injectedGERs, - bridgeL1, - bridgeL2, - ), - }, - } - return services -} - func createRPC(cfg jRPC.Config, services []jRPC.Service) *jRPC.Server { logger := log.WithFields("module", "RPC") return jRPC.NewServer(cfg, services, jRPC.WithLogger(logger.GetSugaredLogger())) diff --git a/common/common.go b/common/common.go index 2fe71dce2..9fddbc8f9 100644 --- a/common/common.go +++ b/common/common.go @@ -8,7 +8,7 @@ import ( "path/filepath" "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/keystore" "github.com/ethereum/go-ethereum/common" "github.com/iden3/go-iden3-crypto/keccak256" diff --git a/common/components.go b/common/components.go index 45c8ae327..f60c70c42 100644 --- a/common/components.go +++ b/common/components.go @@ -5,8 +5,6 @@ const ( SEQUENCE_SENDER = "sequence-sender" //nolint:stylecheck // AGGREGATOR name to identify the aggregator component AGGREGATOR = "aggregator" - // BRIDGE name to identify the bridge component (have RPC) - BRIDGE = "bridge" // CLAIM_SPONSOR name to identify the claim sponsor component CLAIM_SPONSOR = "claim-sponsor" //nolint:stylecheck // PROVER name to identify the prover component diff --git a/config/config.go b/config/config.go index 9554559d5..8df52df6b 100644 --- a/config/config.go +++ b/config/config.go @@ -9,15 +9,12 @@ import ( jRPC "github.com/0xPolygon/cdk-rpc/rpc" "github.com/0xPolygon/cdk/aggregator" - "github.com/0xPolygon/cdk/bridgesync" - "github.com/0xPolygon/cdk/claimsponsor" "github.com/0xPolygon/cdk/common" ethermanconfig "github.com/0xPolygon/cdk/etherman/config" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/lastgersync" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/reorgdetector" "github.com/0xPolygon/cdk/sequencesender" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" + "github.com/agglayer/aggkit/reorgdetector" "github.com/mitchellh/mapstructure" "github.com/pelletier/go-toml/v2" "github.com/spf13/viper" @@ -145,27 +142,11 @@ type Config struct { // Configuration of the reorg detector service to be used for the L1 ReorgDetectorL1 reorgdetector.Config - // Configuration of the reorg detector service to be used for the L2 - ReorgDetectorL2 reorgdetector.Config - // Configuration of the L1 Info Treee Sync service L1InfoTreeSync l1infotreesync.Config // RPC is the config for the RPC server RPC jRPC.Config - - // ClaimSponsor is the config for the claim sponsor - ClaimSponsor claimsponsor.EVMClaimSponsorConfig - - // BridgeL1Sync is the configuration for the synchronizer of the bridge of the L1 - BridgeL1Sync bridgesync.Config - - // BridgeL2Sync is the configuration for the synchronizer of the bridge of the L2 - BridgeL2Sync bridgesync.Config - - // LastGERSync is the config for the synchronizer in charge of syncing the last GER injected on L2. - // Needed for the bridge service (RPC) - LastGERSync lastgersync.Config } // Load loads the configuration diff --git a/config/config_render.go b/config/config_render.go index ac251d300..cecdef766 100644 --- a/config/config_render.go +++ b/config/config_render.go @@ -7,7 +7,7 @@ import ( "regexp" "strings" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/knadh/koanf/parsers/json" "github.com/knadh/koanf/parsers/toml" "github.com/knadh/koanf/providers/rawbytes" diff --git a/config/default.go b/config/default.go index 8d2b5047b..a51c5e5b0 100644 --- a/config/default.go +++ b/config/default.go @@ -202,9 +202,6 @@ DBPath = "{{PathRWData}}/aggregator_db.sqlite" [ReorgDetectorL1] DBPath = "{{PathRWData}}/reorgdetectorl1.sqlite" -[ReorgDetectorL2] -DBPath = "{{PathRWData}}/reorgdetectorl2.sqlite" - [L1InfoTreeSync] DBPath = "{{PathRWData}}/L1InfoTreeSync.sqlite" GlobalExitRootAddr="{{NetworkConfig.L1.GlobalExitRootManagerAddr}}" @@ -224,68 +221,6 @@ ReadTimeout = "2s" WriteTimeout = "2s" MaxRequestsPerIPAndSecond = 10 -[ClaimSponsor] -DBPath = "{{PathRWData}}/claimsopnsor.sqlite" -Enabled = true -SenderAddr = "0xfa3b44587990f97ba8b6ba7e230a5f0e95d14b3d" -BridgeAddrL2 = "0xB7098a13a48EcE087d3DA15b2D28eCE0f89819B8" -MaxGas = 200000 -RetryAfterErrorPeriod = "1s" -MaxRetryAttemptsAfterError = -1 -WaitTxToBeMinedPeriod = "3s" -WaitOnEmptyQueue = "3s" -GasOffset = 0 - [ClaimSponsor.EthTxManager] - FrequencyToMonitorTxs = "1s" - WaitTxToBeMined = "2s" - GetReceiptMaxTime = "250ms" - GetReceiptWaitInterval = "1s" - PrivateKeys = [ - {Path = "/app/keystore/claimsopnsor.keystore", Password = "testonly"}, - ] - ForcedGas = 0 - GasPriceMarginFactor = 1 - MaxGasPriceLimit = 0 - StoragePath = "{{PathRWData}}/ethtxmanager-claimsponsor.sqlite" - ReadPendingL1Txs = false - SafeStatusL1NumberOfBlocks = 5 - FinalizedStatusL1NumberOfBlocks = 10 - [ClaimSponsor.EthTxManager.Etherman] - URL = "{{L2URL}}" - MultiGasProvider = false - L1ChainID = {{NetworkConfig.L1.L1ChainID}} - HTTPHeaders = [] - -[BridgeL1Sync] -DBPath = "{{PathRWData}}/bridgel1sync.sqlite" -BlockFinality = "LatestBlock" -InitialBlockNum = 0 -BridgeAddr = "{{polygonBridgeAddr}}" -SyncBlockChunkSize = 100 -RetryAfterErrorPeriod = "1s" -MaxRetryAttemptsAfterError = -1 -WaitForNewBlocksPeriod = "3s" - -[BridgeL2Sync] -DBPath = "{{PathRWData}}/bridgel2sync.sqlite" -BlockFinality = "LatestBlock" -InitialBlockNum = 0 -BridgeAddr = "{{polygonBridgeAddr}}" -SyncBlockChunkSize = 100 -RetryAfterErrorPeriod = "1s" -MaxRetryAttemptsAfterError = -1 -WaitForNewBlocksPeriod = "3s" - -[LastGERSync] -DBPath = "{{PathRWData}}/lastgersync.sqlite" -BlockFinality = "LatestBlock" -InitialBlockNum = 0 -GlobalExitRootL2Addr = "{{L2Config.GlobalExitRootAddr}}" -RetryAfterErrorPeriod = "1s" -MaxRetryAttemptsAfterError = -1 -WaitForNewBlocksPeriod = "1s" -DownloadBufferSize = 100 - [NetworkConfig.L1] L1ChainID = {{L1Config.chainId}} PolAddr = "{{L1Config.polTokenAddress}}" diff --git a/crates/cdk/build.rs b/crates/cdk/build.rs index 8d6fc5845..7948427cb 100644 --- a/crates/cdk/build.rs +++ b/crates/cdk/build.rs @@ -7,63 +7,51 @@ use std::path::Path; use std::path::PathBuf; use std::process::Command; use serde_json::Value; - fn main() { let _ = build_versions(); - let build_script_disabled = env::var("BUILD_SCRIPT_DISABLED") .map(|v| v == "1") .unwrap_or(false); // run by default - if build_script_disabled { println!("cargo:warning=Build script is disabled. Skipping build."); return; } - // Determine the directory where the build script is located let dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let build_path = PathBuf::from(dir + "/../.."); println!("cargo:rerun-if-changed=*.go"); - // Optionally, specify the directory where your Makefile is located // For this example, it's assumed to be the same as the build script's directory // If your Makefile is in a different directory, adjust `build_path` accordingly - // Call the make command let output = Command::new("make") .arg("build-go") // Create a new make command .current_dir(build_path) // Set the current directory for the command .output() // Execute the command and capture the output .expect("Failed to execute make command"); - // Check the output and react accordingly if !output.status.success() { // If the make command failed, print the error and exit let error_message = String::from_utf8_lossy(&output.stderr); panic!("Make command failed with error: {}", error_message); } - // Optionally, print the output of the make command println!( "Make command output: {}", String::from_utf8_lossy(&output.stdout) ); - // Here you can also add additional commands to inform Cargo about // how to rerun the build script. For example, to rerun this script // only when a specific file changes: // println!("cargo:rerun-if-changed=path/to/file"); } - // build_versions retrieves the versions from the Starlark file and embeds them in the binary. fn build_versions() -> io::Result<()> { // URL of the Starlark file let url = "https://raw.githubusercontent.com/0xPolygon/kurtosis-cdk/refs/heads/main/input_parser.star"; - // Download the file content let response = get(url).expect("Failed to send request"); let content = response.text().expect("Failed to read response text"); - // Extract the relevant lines (skip the first 30 lines, take the next 15) let raw_versions = content .lines() @@ -71,24 +59,19 @@ fn build_versions() -> io::Result<()> { .take(15) .collect::>() .join("\n"); - // Remove the declaration `DEFAULT_IMAGES = ` let raw_versions = raw_versions.replace("DEFAULT_IMAGES = ", ""); - // Clean up the content by removing comments and unnecessary spaces let re_comments = Regex::new(r"#.*$").unwrap(); // Regex to remove comments let re_trailing_commas = Regex::new(r",(\s*})").unwrap(); // Regex to fix trailing commas - let cleaned_versions = raw_versions .lines() .map(|line| re_comments.replace_all(line, "").trim().to_string()) // Remove comments and trim spaces .filter(|line| !line.is_empty()) // Filter out empty lines .collect::>() .join("\n"); - // Fix improperly placed trailing commas let cleaned_versions = re_trailing_commas.replace_all(&cleaned_versions, "$1"); - // Attempt to parse the cleaned content as JSON let versions_json: Value = match serde_json::from_str(&cleaned_versions) { Ok(json) => json, @@ -98,7 +81,6 @@ fn build_versions() -> io::Result<()> { return Err(io::Error::new(io::ErrorKind::InvalidData, "JSON parsing failed")); } }; - // Define the output file path for the JSON let dest_path = Path::new(".").join("versions.json"); let mut file = File::create(&dest_path)?; diff --git a/dataavailability/datacommittee/datacommittee.go b/dataavailability/datacommittee/datacommittee.go index 369fc0fe6..6921a5296 100644 --- a/dataavailability/datacommittee/datacommittee.go +++ b/dataavailability/datacommittee/datacommittee.go @@ -13,8 +13,8 @@ import ( "github.com/0xPolygon/cdk-data-availability/client" daTypes "github.com/0xPolygon/cdk-data-availability/types" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygonHermez/zkevm-synchronizer-l1/translator" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" diff --git a/dataavailability/datacommittee/datacommittee_test.go b/dataavailability/datacommittee/datacommittee_test.go index ac138b449..b4ebd186d 100644 --- a/dataavailability/datacommittee/datacommittee_test.go +++ b/dataavailability/datacommittee/datacommittee_test.go @@ -6,9 +6,9 @@ import ( "testing" "github.com/0xPolygon/cdk-contracts-tooling/contracts/banana/polygondatacommittee" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/test/contracts/erc1967proxy" "github.com/0xPolygon/cdk/test/helpers" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" diff --git a/dataavailability/mocks_da/mock_batch_data_provider.go b/dataavailability/mocks_da/mock_batch_data_provider.go index 36e782ace..2529c859f 100644 --- a/dataavailability/mocks_da/mock_batch_data_provider.go +++ b/dataavailability/mocks_da/mock_batch_data_provider.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_da_backender.go b/dataavailability/mocks_da/mock_da_backender.go index d7ae9a050..f9f1187c1 100644 --- a/dataavailability/mocks_da/mock_da_backender.go +++ b/dataavailability/mocks_da/mock_da_backender.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_data_manager.go b/dataavailability/mocks_da/mock_data_manager.go index 34345d715..697f8539f 100644 --- a/dataavailability/mocks_da/mock_data_manager.go +++ b/dataavailability/mocks_da/mock_data_manager.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_sequence_retriever.go b/dataavailability/mocks_da/mock_sequence_retriever.go index f82d9a70d..934376e87 100644 --- a/dataavailability/mocks_da/mock_sequence_retriever.go +++ b/dataavailability/mocks_da/mock_sequence_retriever.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_sequence_sender.go b/dataavailability/mocks_da/mock_sequence_sender.go index f1e447413..a7fc2638b 100644 --- a/dataavailability/mocks_da/mock_sequence_sender.go +++ b/dataavailability/mocks_da/mock_sequence_sender.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_sequence_sender_banana.go b/dataavailability/mocks_da/mock_sequence_sender_banana.go index aca7b1a33..9549518ad 100644 --- a/dataavailability/mocks_da/mock_sequence_sender_banana.go +++ b/dataavailability/mocks_da/mock_sequence_sender_banana.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/dataavailability/mocks_da/mock_sequence_sender_elderberry.go b/dataavailability/mocks_da/mock_sequence_sender_elderberry.go index 3816fa1b9..b37b703e6 100644 --- a/dataavailability/mocks_da/mock_sequence_sender_elderberry.go +++ b/dataavailability/mocks_da/mock_sequence_sender_elderberry.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_da diff --git a/db/interface.go b/db/interface.go deleted file mode 100644 index 03f81aba0..000000000 --- a/db/interface.go +++ /dev/null @@ -1,17 +0,0 @@ -package db - -import ( - "context" - "database/sql" -) - -type Querier interface { - Exec(query string, args ...interface{}) (sql.Result, error) - Query(query string, args ...interface{}) (*sql.Rows, error) - QueryRow(query string, args ...interface{}) *sql.Row -} - -type DBer interface { - Querier - BeginTx(ctx context.Context, opts *sql.TxOptions) (*sql.Tx, error) -} diff --git a/db/meddler.go b/db/meddler.go deleted file mode 100644 index 83df3b8ae..000000000 --- a/db/meddler.go +++ /dev/null @@ -1,236 +0,0 @@ -package db - -import ( - "errors" - "fmt" - "math/big" - "reflect" - "strings" - - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - sqlite "github.com/mattn/go-sqlite3" - "github.com/russross/meddler" -) - -// init registers tags to be used to read/write from SQL DBs using meddler -func init() { - meddler.Default = meddler.SQLite - meddler.Register("bigint", BigIntMeddler{}) - meddler.Register("merkleproof", MerkleProofMeddler{}) - meddler.Register("hash", HashMeddler{}) - meddler.Register("address", AddressMeddler{}) -} - -func SQLiteErr(err error) (*sqlite.Error, bool) { - sqliteErr := &sqlite.Error{} - if ok := errors.As(err, sqliteErr); ok { - return sqliteErr, true - } - if driverErr, ok := meddler.DriverErr(err); ok { - return sqliteErr, errors.As(driverErr, sqliteErr) - } - return sqliteErr, false -} - -// SliceToSlicePtrs converts any []Foo to []*Foo -func SliceToSlicePtrs(slice interface{}) interface{} { - v := reflect.ValueOf(slice) - vLen := v.Len() - typ := v.Type().Elem() - res := reflect.MakeSlice(reflect.SliceOf(reflect.PointerTo(typ)), vLen, vLen) - for i := 0; i < vLen; i++ { - res.Index(i).Set(v.Index(i).Addr()) - } - return res.Interface() -} - -// SlicePtrsToSlice converts any []*Foo to []Foo -func SlicePtrsToSlice(slice interface{}) interface{} { - v := reflect.ValueOf(slice) - vLen := v.Len() - typ := v.Type().Elem().Elem() - res := reflect.MakeSlice(reflect.SliceOf(typ), vLen, vLen) - for i := 0; i < vLen; i++ { - res.Index(i).Set(v.Index(i).Elem()) - } - return res.Interface() -} - -// BigIntMeddler encodes or decodes the field value to or from string -type BigIntMeddler struct{} - -// PreRead is called before a Scan operation for fields that have the BigIntMeddler -func (b BigIntMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) { - // give a pointer to a byte buffer to grab the raw data - return new(string), nil -} - -// PostRead is called after a Scan operation for fields that have the BigIntMeddler -func (b BigIntMeddler) PostRead(fieldPtr, scanTarget interface{}) error { - ptr, ok := scanTarget.(*string) - if !ok { - return errors.New("scanTarget is not *string") - } - if ptr == nil { - return fmt.Errorf("BigIntMeddler.PostRead: nil pointer") - } - field, ok := fieldPtr.(**big.Int) - if !ok { - return errors.New("fieldPtr is not *big.Int") - } - decimal := 10 - *field, ok = new(big.Int).SetString(*ptr, decimal) - if !ok { - return fmt.Errorf("big.Int.SetString failed on \"%v\"", *ptr) - } - return nil -} - -// PreWrite is called before an Insert or Update operation for fields that have the BigIntMeddler -func (b BigIntMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) { - field, ok := fieldPtr.(*big.Int) - if !ok { - return nil, errors.New("fieldPtr is not *big.Int") - } - - return field.String(), nil -} - -// MerkleProofMeddler encodes or decodes the field value to or from string -type MerkleProofMeddler struct{} - -// PreRead is called before a Scan operation for fields that have the MerkleProofMeddler -func (b MerkleProofMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) { - // give a pointer to a byte buffer to grab the raw data - return new(string), nil -} - -// PostRead is called after a Scan operation for fields that have the MerkleProofMeddler -func (b MerkleProofMeddler) PostRead(fieldPtr, scanTarget interface{}) error { - ptr, ok := scanTarget.(*string) - if !ok { - return errors.New("scanTarget is not *string") - } - if ptr == nil { - return errors.New("ProofMeddler.PostRead: nil pointer") - } - field, ok := fieldPtr.(*tree.Proof) - if !ok { - return errors.New("fieldPtr is not tree.Proof") - } - strHashes := strings.Split(*ptr, ",") - if len(strHashes) != int(tree.DefaultHeight) { - return fmt.Errorf("unexpected len of hashes: expected %d actual %d", tree.DefaultHeight, len(strHashes)) - } - for i, strHash := range strHashes { - field[i] = common.HexToHash(strHash) - } - return nil -} - -// PreWrite is called before an Insert or Update operation for fields that have the MerkleProofMeddler -func (b MerkleProofMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) { - field, ok := fieldPtr.(tree.Proof) - if !ok { - return nil, errors.New("fieldPtr is not tree.Proof") - } - var s string - for _, f := range field { - s += f.Hex() + "," - } - s = strings.TrimSuffix(s, ",") - return s, nil -} - -// HashMeddler encodes or decodes the field value to or from string -type HashMeddler struct{} - -// PreRead is called before a Scan operation for fields that have the HashMeddler -func (b HashMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) { - // give a pointer to a byte buffer to grab the raw data - return new(string), nil -} - -// PostRead is called after a Scan operation for fields that have the HashMeddler -func (b HashMeddler) PostRead(fieldPtr, scanTarget interface{}) error { - rawHashPtr, ok := scanTarget.(*string) - if !ok { - return errors.New("scanTarget is not *string") - } - - // Handle the case where fieldPtr is a *common.Hash - field, ok := fieldPtr.(*common.Hash) - if ok { - *field = common.HexToHash(*rawHashPtr) - return nil - } - - // Handle the case where fieldPtr is a **common.Hash (nullable field) - hashPtr, ok := fieldPtr.(**common.Hash) - if ok { - // If the string is empty, set the hash to nil - if len(*rawHashPtr) == 0 { - *hashPtr = nil - // Otherwise, convert the string to a common.Hash and assign it - } else { - tmp := common.HexToHash(*rawHashPtr) - *hashPtr = &tmp - } - return nil - } - - // If fieldPtr is neither a *common.Hash nor a **common.Hash, return an error - return errors.New("fieldPtr is not *common.Hash or **common.Hash") -} - -// PreWrite is called before an Insert or Update operation for fields that have the HashMeddler -func (b HashMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) { - field, ok := fieldPtr.(common.Hash) - if !ok { - hashPtr, ok := fieldPtr.(*common.Hash) - if !ok { - return nil, errors.New("fieldPtr is not common.Hash") - } - if hashPtr == nil { - return []byte{}, nil - } - return hashPtr.Hex(), nil - } - return field.Hex(), nil -} - -// AddressMeddler encodes or decodes the field value to or from string -type AddressMeddler struct{} - -// PreRead is called before a Scan operation for fields that have the AddressMeddler -func (b AddressMeddler) PreRead(fieldAddr interface{}) (scanTarget interface{}, err error) { - // give a pointer to a byte buffer to grab the raw data - return new(string), nil -} - -// PostRead is called after a Scan operation for fields that have the AddressMeddler -func (b AddressMeddler) PostRead(fieldPtr, scanTarget interface{}) error { - ptr, ok := scanTarget.(*string) - if !ok { - return errors.New("scanTarget is not *string") - } - if ptr == nil { - return errors.New("AddressMeddler.PostRead: nil pointer") - } - field, ok := fieldPtr.(*common.Address) - if !ok { - return errors.New("fieldPtr is not common.Address") - } - *field = common.HexToAddress(*ptr) - return nil -} - -// PreWrite is called before an Insert or Update operation for fields that have the AddressMeddler -func (b AddressMeddler) PreWrite(fieldPtr interface{}) (saveValue interface{}, err error) { - field, ok := fieldPtr.(common.Address) - if !ok { - return nil, errors.New("fieldPtr is not common.Address") - } - return field.Hex(), nil -} diff --git a/db/meddler_test.go b/db/meddler_test.go deleted file mode 100644 index 61017bbd9..000000000 --- a/db/meddler_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package db - -import ( - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/assert" -) - -func TestHashMeddler_PreWrite(t *testing.T) { - t.Parallel() - - hex := "0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef" - hash := common.HexToHash(hex) - - tests := []struct { - name string - fieldPtr interface{} - wantValue interface{} - wantErr bool - }{ - { - name: "Valid common.Hash", - fieldPtr: hash, - wantValue: hex, - wantErr: false, - }, - { - name: "Valid *common.Hash", - fieldPtr: &hash, - wantValue: hex, - wantErr: false, - }, - { - name: "Nil *common.Hash", - fieldPtr: (*common.Hash)(nil), - wantValue: []byte{}, - wantErr: false, - }, - { - name: "Invalid type", - fieldPtr: "invalid", - wantValue: nil, - wantErr: true, - }, - } - - for _, tt := range tests { - tt := tt - - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - h := HashMeddler{} - gotValue, err := h.PreWrite(tt.fieldPtr) - if tt.wantErr { - assert.Error(t, err) - } else { - assert.NoError(t, err) - assert.Equal(t, tt.wantValue, gotValue) - } - }) - } -} diff --git a/db/migrations.go b/db/migrations.go deleted file mode 100644 index 8af35874e..000000000 --- a/db/migrations.go +++ /dev/null @@ -1,53 +0,0 @@ -package db - -import ( - "database/sql" - "fmt" - "strings" - - "github.com/0xPolygon/cdk/db/types" - "github.com/0xPolygon/cdk/log" - _ "github.com/mattn/go-sqlite3" - migrate "github.com/rubenv/sql-migrate" -) - -const ( - upDownSeparator = "-- +migrate Up" - dbPrefixReplacer = "/*dbprefix*/" -) - -// RunMigrations will execute pending migrations if needed to keep -// the database updated with the latest changes in either direction, -// up or down. -func RunMigrations(dbPath string, migrations []types.Migration) error { - db, err := NewSQLiteDB(dbPath) - if err != nil { - return fmt.Errorf("error creating DB %w", err) - } - return RunMigrationsDB(log.GetDefaultLogger(), db, migrations) -} - -func RunMigrationsDB(logger *log.Logger, db *sql.DB, migrations []types.Migration) error { - migs := &migrate.MemoryMigrationSource{Migrations: []*migrate.Migration{}} - for _, m := range migrations { - prefixed := strings.ReplaceAll(m.SQL, dbPrefixReplacer, m.Prefix) - splitted := strings.Split(prefixed, upDownSeparator) - migs.Migrations = append(migs.Migrations, &migrate.Migration{ - Id: m.Prefix + m.ID, - Up: []string{splitted[1]}, - Down: []string{splitted[0]}, - }) - } - - logger.Debugf("running migrations:") - for _, m := range migs.Migrations { - logger.Debugf("%+v", m.Id) - } - nMigrations, err := migrate.Exec(db, "sqlite3", migs, migrate.Up) - if err != nil { - return fmt.Errorf("error executing migration %w", err) - } - - logger.Infof("successfully ran %d migrations", nMigrations) - return nil -} diff --git a/db/sqlite.go b/db/sqlite.go deleted file mode 100644 index 23d5d2a19..000000000 --- a/db/sqlite.go +++ /dev/null @@ -1,29 +0,0 @@ -package db - -import ( - "database/sql" - "errors" - "fmt" - - _ "github.com/mattn/go-sqlite3" -) - -const ( - UniqueConstrain = 1555 -) - -var ( - ErrNotFound = errors.New("not found") -) - -// NewSQLiteDB creates a new SQLite DB -func NewSQLiteDB(dbPath string) (*sql.DB, error) { - return sql.Open("sqlite3", fmt.Sprintf("file:%s?_txlock=exclusive&_foreign_keys=on&_journal_mode=WAL", dbPath)) -} - -func ReturnErrNotFound(err error) error { - if errors.Is(err, sql.ErrNoRows) { - return ErrNotFound - } - return err -} diff --git a/db/tx.go b/db/tx.go deleted file mode 100644 index 926da07c9..000000000 --- a/db/tx.go +++ /dev/null @@ -1,60 +0,0 @@ -package db - -import ( - "context" -) - -type SQLTxer interface { - Querier - Commit() error - Rollback() error -} - -type Txer interface { - SQLTxer - AddRollbackCallback(cb func()) - AddCommitCallback(cb func()) -} - -type Tx struct { - SQLTxer - rollbackCallbacks []func() - commitCallbacks []func() -} - -func NewTx(ctx context.Context, db DBer) (Txer, error) { - tx, err := db.BeginTx(ctx, nil) - if err != nil { - return nil, err - } - return &Tx{ - SQLTxer: tx, - }, nil -} - -func (s *Tx) AddRollbackCallback(cb func()) { - s.rollbackCallbacks = append(s.rollbackCallbacks, cb) -} -func (s *Tx) AddCommitCallback(cb func()) { - s.commitCallbacks = append(s.commitCallbacks, cb) -} - -func (s *Tx) Commit() error { - if err := s.SQLTxer.Commit(); err != nil { - return err - } - for _, cb := range s.commitCallbacks { - cb() - } - return nil -} - -func (s *Tx) Rollback() error { - if err := s.SQLTxer.Rollback(); err != nil { - return err - } - for _, cb := range s.rollbackCallbacks { - cb() - } - return nil -} diff --git a/db/types/types.go b/db/types/types.go deleted file mode 100644 index ade190925..000000000 --- a/db/types/types.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -type Migration struct { - ID string - SQL string - Prefix string -} diff --git a/docs/SUMMARY.md b/docs/SUMMARY.md index 04254646d..2cac9ca66 100644 --- a/docs/SUMMARY.md +++ b/docs/SUMMARY.md @@ -1,5 +1,6 @@ # Summary -- [Getting Started](./getting_started.md) - - [Local Debug](./local_debug.md) +Welcome to the official documentation for the Polygon CDK (Chain Development Kit). This guide will help you get started with building and deploying rollups using the Polygon CDK. + +- [Local Debug](./local_debug.md) - [DA Integration](./da_integration.md) diff --git a/docs/da_integration.md b/docs/da_integration.md index a752d01f7..61047922d 100644 --- a/docs/da_integration.md +++ b/docs/da_integration.md @@ -14,7 +14,7 @@ The versions of the smart contracts that are being targeted for the DA integrati - zkEVM to implement a rollup. - Validium to implement a validium. -- Adding a custom solution. +- Adding a custom solution. This document only considers the first approach, reusing the `PolygonValidium` consensus. That being said, the `PolygonValidium` implementation allows a custom smart contract to be used in the relevant interaction. This could be used by DAs to add custom on-chain verification logic. While verifying the DA integrity is optional, any new protocol will need to develop a custom smart contract in order to be successfully integrated (more details bellow) @@ -48,7 +48,7 @@ It's expected that any protocol build their own contract that follows [this inte In order to integrate a DA solution into CDK, the most fundamental part is for the node to be able to post and retrieve data from the DA backend. -Up until now, DAs would fork the `cdk-validium-node` repo to make such an integration. But maintaining forks can be really painful, so the team is proposing this solution that will allow the different DAs to be 1st class citizens and live on the official `cdk` repo. +Up until now, DAs would fork the `cdk-validium-node` repo to make such an integration. But maintaining forks can be really painful, so the team is proposing this solution that will allow the different DAs to be 1st class citizens and live on the official `cdk` repo. These items would need to be implemented to have a successful integration: @@ -64,7 +64,7 @@ These items would need to be implemented to have a successful integration: 1. Create an E2E test that uses your protocol by following the [test/e2e/datacommittee_test.go](https://github.com/0xPolygon/cdk-validium-node/blob/develop/test/e2e/datacommittee_test.go) example. 2. Follow the instructions on [Local Debug](local_debug.md) to run Kurtosis enviroment for local testing -4. Deploy the new contract contract to L1 running in Kurtosis +3. Deploy the new contract contract to L1 running in Kurtosis 4. Call `setDataAvailabilityProtocol` in validium consensus contract to use the newly deployed contract. 5. Modify the `Makefile` to be able to run your test, take the case of the DAC test as an example here diff --git a/docs/getting_started.md b/docs/getting_started.md deleted file mode 100644 index 702dabaf0..000000000 --- a/docs/getting_started.md +++ /dev/null @@ -1,17 +0,0 @@ -# Welcome to Polygon CDK Tech Docs - -Welcome to the official documentation for the Polygon CDK (Chain Development Kit). This guide will help you get started with building and deploying rollups using the Polygon CDK. - -## Getting Started - -To get started with Polygon CDK, follow these steps: -1. [Getting Started](getting_started.md) - -## Documentation - -Explore the comprehensive documentation to understand the various features and capabilities of the Polygon CDK: -- [3rd party data availability integration](da_integration.md) - -## Support - -Happy coding with Polygon CDK! diff --git a/docs/local_debug.md b/docs/local_debug.md index dc6e998bb..4406101ad 100644 --- a/docs/local_debug.md +++ b/docs/local_debug.md @@ -10,7 +10,7 @@ ## Create configuration for this kurtosis environment -``` +```bash scripts/local_config ``` diff --git a/etherman/aggregator.go b/etherman/aggregator.go index 4197c7a27..1d18cdcbd 100644 --- a/etherman/aggregator.go +++ b/etherman/aggregator.go @@ -9,7 +9,7 @@ import ( "strings" ethmanTypes "github.com/0xPolygon/cdk/aggregator/ethmantypes" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" diff --git a/etherman/contracts/base.go b/etherman/contracts/base.go index acc19e76b..33dac74c3 100644 --- a/etherman/contracts/base.go +++ b/etherman/contracts/base.go @@ -3,7 +3,7 @@ package contracts import ( "reflect" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" ) diff --git a/etherman/etherman.go b/etherman/etherman.go index fa0033033..edee4ef05 100644 --- a/etherman/etherman.go +++ b/etherman/etherman.go @@ -14,7 +14,7 @@ import ( cdkcommon "github.com/0xPolygon/cdk/common" "github.com/0xPolygon/cdk/etherman/config" "github.com/0xPolygon/cdk/etherman/contracts" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/accounts/keystore" diff --git a/go.mod b/go.mod index a70c8e608..b2c059cf0 100644 --- a/go.mod +++ b/go.mod @@ -3,39 +3,31 @@ module github.com/0xPolygon/cdk go 1.22.4 require ( - github.com/0xPolygon/cdk-contracts-tooling v0.0.1 - github.com/0xPolygon/cdk-data-availability v0.0.11 + github.com/0xPolygon/cdk-contracts-tooling v0.0.2-0.20241225094934-1d381f5703ef + github.com/0xPolygon/cdk-data-availability v0.0.12-0.20250110120923-25a978231f89 github.com/0xPolygon/cdk-rpc v0.0.0-20241004114257-6c3cb6eebfb6 github.com/0xPolygon/zkevm-ethtx-manager v0.2.4 github.com/0xPolygonHermez/zkevm-synchronizer-l1 v1.0.6 + github.com/agglayer/aggkit v0.0.2-0.20250210155301-c8daf4c3283e github.com/ethereum/go-ethereum v1.14.10 - github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3 - github.com/hermeznetwork/tracerr v0.3.2 github.com/iden3/go-iden3-crypto v0.0.17 - github.com/invopop/jsonschema v0.12.0 + github.com/invopop/jsonschema v0.13.0 github.com/jackc/pgx/v4 v4.18.3 github.com/knadh/koanf/parsers/json v0.1.0 github.com/knadh/koanf/parsers/toml v0.1.0 github.com/knadh/koanf/providers/rawbytes v0.1.0 - github.com/knadh/koanf/v2 v2.1.1 - github.com/mattn/go-sqlite3 v1.14.24 + github.com/knadh/koanf/v2 v2.1.2 github.com/mitchellh/mapstructure v1.5.0 - github.com/pelletier/go-toml/v2 v2.2.2 + github.com/pelletier/go-toml/v2 v2.2.3 github.com/rubenv/sql-migrate v1.7.1 - github.com/russross/meddler v1.0.1 github.com/spf13/viper v1.19.0 github.com/stretchr/testify v1.10.0 - github.com/urfave/cli/v2 v2.27.4 + github.com/urfave/cli/v2 v2.27.5 github.com/valyala/fasttemplate v1.2.2 - go.opentelemetry.io/otel v1.24.0 - go.opentelemetry.io/otel/metric v1.24.0 go.uber.org/zap v1.27.0 - golang.org/x/crypto v0.31.0 - golang.org/x/net v0.33.0 - golang.org/x/sync v0.10.0 + golang.org/x/net v0.34.0 google.golang.org/grpc v1.64.1 - google.golang.org/protobuf v1.34.2 - modernc.org/sqlite v1.32.0 + google.golang.org/protobuf v1.36.5 ) require ( @@ -57,7 +49,7 @@ require ( github.com/cockroachdb/tokenbucket v0.0.0-20230807174530-cc333fc44b06 // indirect github.com/consensys/bavard v0.1.13 // indirect github.com/consensys/gnark-crypto v0.13.0 // indirect - github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect + github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a // indirect github.com/crate-crypto/go-kzg-4844 v1.1.0 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect @@ -71,20 +63,19 @@ require ( github.com/gballet/go-libpcsclite v0.0.0-20191108122812-4678299bea08 // indirect github.com/getsentry/sentry-go v0.28.1 // indirect github.com/go-gorp/gorp/v3 v3.1.0 // indirect - github.com/go-logr/logr v1.4.1 // indirect - github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect github.com/go-pkgz/expirable-cache v0.0.3 // indirect - github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 // indirect + github.com/go-viper/mapstructure/v2 v2.2.1 // indirect github.com/gofrs/flock v0.12.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang-collections/collections v0.0.0-20130729185459-604e922904d3 // indirect github.com/golang-jwt/jwt/v4 v4.5.1 // indirect github.com/golang/snappy v0.0.5-0.20220116011046-fa5810519dcb // indirect github.com/google/uuid v1.6.0 // indirect github.com/gorilla/websocket v1.5.3 // indirect github.com/hashicorp/go-bexpr v0.1.10 // indirect - github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect github.com/hashicorp/hcl v1.0.1-0.20180906183839-65a6292f0157 // indirect + github.com/hermeznetwork/tracerr v0.3.2 // indirect github.com/holiman/billy v0.0.0-20240216141850-2abb0c79d3c4 // indirect github.com/holiman/bloomfilter/v2 v2.0.3 // indirect github.com/holiman/uint256 v1.3.2 // indirect @@ -109,6 +100,7 @@ require ( github.com/mattn/go-colorable v0.1.13 // indirect github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.16 // indirect + github.com/mattn/go-sqlite3 v1.14.24 // indirect github.com/miguelmota/go-solidity-sha3 v0.1.1 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/pointerstructure v1.2.0 // indirect @@ -117,7 +109,6 @@ require ( github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect github.com/olekukonko/tablewriter v0.0.5 // indirect - github.com/onsi/gomega v1.27.10 // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pkg/errors v0.9.1 // indirect github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect @@ -127,9 +118,10 @@ require ( github.com/prometheus/procfs v0.15.1 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/rivo/uniseg v0.2.0 // indirect - github.com/rogpeppe/go-internal v1.12.0 // indirect + github.com/rogpeppe/go-internal v1.13.1 // indirect github.com/rs/cors v1.7.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect + github.com/russross/meddler v1.0.1 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/shirou/gopsutil v3.21.4-0.20210419000835-c7a38de76ee5+incompatible // indirect @@ -148,21 +140,20 @@ require ( github.com/valyala/bytebufferpool v1.0.0 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect - go.opentelemetry.io/otel/trace v1.24.0 // indirect go.uber.org/multierr v1.10.0 // indirect + golang.org/x/crypto v0.33.0 // indirect golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f // indirect - golang.org/x/sys v0.28.0 // indirect - golang.org/x/text v0.21.0 // indirect + golang.org/x/sync v0.11.0 // indirect + golang.org/x/sys v0.30.0 // indirect + golang.org/x/text v0.22.0 // indirect golang.org/x/time v0.5.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240318140521-94a12d6c2237 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect - modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a // indirect modernc.org/libc v1.60.0 // indirect modernc.org/mathutil v1.6.0 // indirect modernc.org/memory v1.8.0 // indirect - modernc.org/strutil v1.2.0 // indirect - modernc.org/token v1.1.0 // indirect + modernc.org/sqlite v1.34.5 // indirect rsc.io/tmplfunc v0.0.3 // indirect ) diff --git a/go.sum b/go.sum index e496f9b30..dada0663a 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ -github.com/0xPolygon/cdk-contracts-tooling v0.0.1 h1:2HH8KpO1CZRl1zHfn0IYwJhPA7l91DOWrjdExmaB9Kk= -github.com/0xPolygon/cdk-contracts-tooling v0.0.1/go.mod h1:mFlcEjsm2YBBsu8atHJ3zyVnwM+Z/fMXpVmIJge+WVU= -github.com/0xPolygon/cdk-data-availability v0.0.11 h1:enmlyFYCvmDmcX/2fnDjWnn3svqqm9o2Fe+Kupoykdo= -github.com/0xPolygon/cdk-data-availability v0.0.11/go.mod h1:20WaXcSp7ggoxWePL9ReKSuqksHUx5h8LNQ+b56OHJE= +github.com/0xPolygon/cdk-contracts-tooling v0.0.2-0.20241225094934-1d381f5703ef h1:DRBrbysjMTyeFRbyo+zoltOTET+vR20CnXc4wupj+qo= +github.com/0xPolygon/cdk-contracts-tooling v0.0.2-0.20241225094934-1d381f5703ef/go.mod h1:mFlcEjsm2YBBsu8atHJ3zyVnwM+Z/fMXpVmIJge+WVU= +github.com/0xPolygon/cdk-data-availability v0.0.12-0.20250110120923-25a978231f89 h1:dqMjGG25vl7yq/G7RN+xvePsxeoMRtC/FU+IJrwcFAs= +github.com/0xPolygon/cdk-data-availability v0.0.12-0.20250110120923-25a978231f89/go.mod h1:Uv6+NnNQ5X6Drdb8YIhfA0kuQvFxVhJsnFZXUyq6050= github.com/0xPolygon/cdk-rpc v0.0.0-20241004114257-6c3cb6eebfb6 h1:FXL/rcO7/GtZ3kRFw+C7J6vmGnl8gcazg+Gh/NVmnas= github.com/0xPolygon/cdk-rpc v0.0.0-20241004114257-6c3cb6eebfb6/go.mod h1:2scWqMMufrQXu7TikDgQ3BsyaKoX8qP26D6E262vSOg= github.com/0xPolygon/zkevm-ethtx-manager v0.2.4 h1:OrtSD8jLVeQnN+1I0c7U/3+EYSd+h3wm1vygrDAXBZg= @@ -20,6 +20,8 @@ github.com/StackExchange/wmi v1.2.1 h1:VIkavFPXSjcnS+O8yTq7NI32k0R5Aj+v39y29VYDO github.com/StackExchange/wmi v1.2.1/go.mod h1:rcmrprowKIVzvc+NUiLncP2uuArMWLCbu9SBzvHz7e8= github.com/VictoriaMetrics/fastcache v1.12.2 h1:N0y9ASrJ0F6h0QaC3o6uJb3NIZ9VKLjCM7NQbSmF7WI= github.com/VictoriaMetrics/fastcache v1.12.2/go.mod h1:AmC+Nzz1+3G2eCPapF6UcsnkThDcMsQicp4xDukwJYI= +github.com/agglayer/aggkit v0.0.2-0.20250210155301-c8daf4c3283e h1:G9WRfV0R94jogpSm3ydKWgWNT+h6wbBhIo7GZLIG6QY= +github.com/agglayer/aggkit v0.0.2-0.20250210155301-c8daf4c3283e/go.mod h1:vT3LjN3DuNqpTs2T9jJAjnorkKjCK15R4y/oI49+hEY= github.com/allegro/bigcache v1.2.1-0.20190218064605-e24eb225f156/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= github.com/allegro/bigcache v1.2.1 h1:hg1sY1raCwic3Vnsvje6TT7/pnZba83LeFck5NrFKSc= github.com/allegro/bigcache v1.2.1/go.mod h1:Cb/ax3seSYIx7SuZdm2G2xzfwmv3TPSk2ucNfQESPXM= @@ -65,8 +67,8 @@ github.com/consensys/gnark-crypto v0.13.0 h1:VPULb/v6bbYELAPTDFINEVaMTTybV5GLxDd github.com/consensys/gnark-crypto v0.13.0/go.mod h1:wKqwsieaKPThcFkHe0d0zMsbHEUWFmZcG7KBCse210o= github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= -github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= +github.com/cpuguy83/go-md2man/v2 v2.0.5 h1:ZtcqGrnekaHpVLArFSe4HK5DoKx1T0rq2DwVB0alcyc= +github.com/cpuguy83/go-md2man/v2 v2.0.5/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a h1:W8mUrRp6NOVl3J+MYp5kPMoUZPp7aOYHtaua31lwRHg= github.com/crate-crypto/go-ipa v0.0.0-20240724233137-53bbb0ceb27a/go.mod h1:sTwzHBvIzm2RfVCGNEBZgRyjwK40bVoun3ZnGOCafNM= github.com/crate-crypto/go-kzg-4844 v1.1.0 h1:EN/u9k2TF6OWSHrCCDBBU6GLNMq88OspHHlMnHfoyU4= @@ -110,11 +112,6 @@ github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= -github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= -github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= -github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= -github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-ole/go-ole v1.2.5/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= @@ -125,8 +122,8 @@ github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfC github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= -github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1 h1:TQcrn6Wq+sKGkpyPvppOz99zsMBaUOKXq6HSv655U1c= -github.com/go-viper/mapstructure/v2 v2.0.0-alpha.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/go-viper/mapstructure/v2 v2.2.1 h1:ZAaOCxANMuZx5RCeg0mBdEZk7DZasvvZIxtHqx8aGss= +github.com/go-viper/mapstructure/v2 v2.2.1/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= github.com/gofrs/flock v0.12.1 h1:MTLVXXHf8ekldpJk3AKicLij9MdwOWkZ+a/jHHZby9E= github.com/gofrs/flock v0.12.1/go.mod h1:9zxTsyu5xtJ9DK+1tFZyibEV7y3uwDxPPfbxeeHCoD0= github.com/gofrs/uuid v4.0.0+incompatible h1:1SD/1F5pU8p29ybwgQSwpQk+mwdRrXCYuPhW6m+TnJw= @@ -168,8 +165,6 @@ github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aN github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= github.com/hashicorp/go-bexpr v0.1.10 h1:9kuI5PFotCboP3dkDYFr/wi0gg0QVbSNz5oFRpxn4uE= github.com/hashicorp/go-bexpr v0.1.10/go.mod h1:oxlubA2vC/gFVfX1A6JGp7ls7uCDlfJn732ehYYg+g0= -github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= -github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= github.com/hashicorp/hcl v1.0.1-0.20180906183839-65a6292f0157 h1:uyodBE3xDz0ynKs1tLBU26wOQoEkAqqiY18DbZ+FZrA= github.com/hashicorp/hcl v1.0.1-0.20180906183839-65a6292f0157/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= github.com/hermeznetwork/tracerr v0.3.2 h1:QB3TlQxO/4XHyixsg+nRZPuoel/FFQlQ7oAoHDD5l1c= @@ -186,8 +181,8 @@ github.com/huin/goupnp v1.3.0/go.mod h1:gnGPsThkYa7bFi/KWmEysQRf48l2dvR5bxr2OFck github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/iden3/go-iden3-crypto v0.0.17 h1:NdkceRLJo/pI4UpcjVah4lN/a3yzxRUGXqxbWcYh9mY= github.com/iden3/go-iden3-crypto v0.0.17/go.mod h1:dLpM4vEPJ3nDHzhWFXDjzkn1qHoBeOT/3UEhXsEsP3E= -github.com/invopop/jsonschema v0.12.0 h1:6ovsNSuvn9wEQVOyc72aycBMVQFKz7cPdMJn10CvzRI= -github.com/invopop/jsonschema v0.12.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0= +github.com/invopop/jsonschema v0.13.0 h1:KvpoAJWEjR3uD9Kbm2HWJmqsEaHt8lBUpd0qHcIi21E= +github.com/invopop/jsonschema v0.13.0/go.mod h1:ffZ5Km5SWWRAIN6wbDXItl95euhFz2uON45H2qjYt+0= github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8= @@ -254,8 +249,8 @@ github.com/knadh/koanf/parsers/toml v0.1.0 h1:S2hLqS4TgWZYj4/7mI5m1CQQcWurxUz6OD github.com/knadh/koanf/parsers/toml v0.1.0/go.mod h1:yUprhq6eo3GbyVXFFMdbfZSo928ksS+uo0FFqNMnO18= github.com/knadh/koanf/providers/rawbytes v0.1.0 h1:dpzgu2KO6uf6oCb4aP05KDmKmAmI51k5pe8RYKQ0qME= github.com/knadh/koanf/providers/rawbytes v0.1.0/go.mod h1:mMTB1/IcJ/yE++A2iEZbY1MLygX7vttU+C+S/YmPu9c= -github.com/knadh/koanf/v2 v2.1.1 h1:/R8eXqasSTsmDCsAyYj+81Wteg8AqrV9CP6gvsTsOmM= -github.com/knadh/koanf/v2 v2.1.1/go.mod h1:4mnTRbZCK+ALuBXHZMjDfG9y714L7TykVnZkXbMU3Es= +github.com/knadh/koanf/v2 v2.1.2 h1:I2rtLRqXRy1p01m/utEtpZSSA6dcJbgGVuE27kW2PzQ= +github.com/knadh/koanf/v2 v2.1.2/go.mod h1:Gphfaen0q1Fc1HTgJgSTC4oRX9R2R5ErYMZJy8fLJBo= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= @@ -338,8 +333,8 @@ github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= github.com/onsi/gomega v1.27.10/go.mod h1:RsS8tutOdbdgzbPtzzATp12yT7kM5I5aElG3evPbQ0M= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= -github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= -github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4= github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= @@ -365,8 +360,8 @@ github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= -github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8= -github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4= +github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= +github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= github.com/rs/cors v1.7.0 h1:+88SsELBHx5r+hZ8TCkggzSstaWNbDvThkVK8H6f9ik= github.com/rs/cors v1.7.0/go.mod h1:gFx+x8UowdsKA9AchylcLynDq+nNFfI8FkUZdN/jGCU= github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= @@ -406,8 +401,6 @@ github.com/status-im/keycard-go v0.2.0/go.mod h1:wlp8ZLbsmrF6g6WjugPAx+IzoLrkdf9 github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= -github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= -github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= @@ -415,11 +408,7 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals= -github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= -github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= -github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= @@ -434,8 +423,8 @@ github.com/tklauser/numcpus v0.6.1 h1:ng9scYS7az0Bk4OZLvrNXNSAO2Pxr1XXRAPyjhIx+F github.com/tklauser/numcpus v0.6.1/go.mod h1:1XfjsgE2zo8GVw7POkMbHENHzVg3GzmoZ9fESEdAacY= github.com/tyler-smith/go-bip39 v1.1.0 h1:5eUemwrMargf3BSLRRCalXT93Ns6pQJIjYQN2nyfOP8= github.com/tyler-smith/go-bip39 v1.1.0/go.mod h1:gUYDtqQw1JS3ZJ8UWVcGTGqqr6YIN3CWg+kkNaLt55U= -github.com/urfave/cli/v2 v2.27.4 h1:o1owoI+02Eb+K107p27wEX9Bb8eqIoZCfLXloLUSWJ8= -github.com/urfave/cli/v2 v2.27.4/go.mod h1:m4QzxcD2qpra4z7WhzEGn74WZLViBnMpb1ToCAKdGRQ= +github.com/urfave/cli/v2 v2.27.5 h1:WoHEJLdsXr6dDWoJgMq/CboDmyY/8HMMH1fTECbih+w= +github.com/urfave/cli/v2 v2.27.5/go.mod h1:3Sevf16NykTbInEnD0yKkjDAeZDS0A6bzhBH5hrMvTQ= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/fasttemplate v1.2.2 h1:lxLXG0uE3Qnshl9QyaK6XJxMXlQZELvChBOCmQD0Loo= @@ -447,12 +436,6 @@ github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBi github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= -go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= -go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= -go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= -go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= -go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= -go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= @@ -479,8 +462,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U= -golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk= +golang.org/x/crypto v0.33.0 h1:IOBPskki6Lysi0lo9qQvbxiQ+FvsCC/YWOecCHAixus= +golang.org/x/crypto v0.33.0/go.mod h1:bVdXmD7IV/4GdElGPozy6U7lWdRXA4qyRVGJV57uQ5M= golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f h1:XdNn9LlyWAhLVp6P/i8QYBW+hlyhrhei9uErw2B5GJo= golang.org/x/exp v0.0.0-20241108190413-2d47ceb2692f/go.mod h1:D5SMRVC3C2/4+F/DB1wZsLRnSNimn2Sp/NPsCrsv8ak= golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -502,15 +485,15 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk= golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= golang.org/x/net v0.0.0-20220607020251-c690dde0001d/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= -golang.org/x/net v0.33.0 h1:74SYHlV8BIgHIFC/LrYkOGIwL19eTYXQ5wc6TBuO36I= -golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4= +golang.org/x/net v0.34.0 h1:Mb7Mrk043xzHgnRM88suvJFwzVrRfHEHJEl5/71CKw0= +golang.org/x/net v0.34.0/go.mod h1:di0qlW3YNM5oh6GqDGQr92MyTozJPmybPK4Ev/Gm31k= golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= -golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ= -golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sync v0.11.0 h1:GGz8+XQP4FvTTrjZPzNKTMFtSXH80RAzG+5ghFPgK9w= +golang.org/x/sync v0.11.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= @@ -542,8 +525,8 @@ golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.14.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA= -golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc= +golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= @@ -553,8 +536,8 @@ golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo= -golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ= +golang.org/x/text v0.22.0 h1:bofq7m3/HAFvbF51jz3Q9wLg3jkvSPuiZu/pD1XwgtM= +golang.org/x/text v0.22.0/go.mod h1:YRoo4H8PVmsu+E3Ou7cqLVH8oXWIHVoX0jqUWALQhfY= golang.org/x/time v0.0.0-20200416051211-89c76fbcd5d1/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk= golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM= @@ -591,8 +574,8 @@ google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzi google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= -google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= @@ -623,8 +606,6 @@ modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE= modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ= modernc.org/gc/v2 v2.5.0 h1:bJ9ChznK1L1mUtAQtxi0wi5AtAs5jQuw4PrPHO5pb6M= modernc.org/gc/v2 v2.5.0/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU= -modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a h1:CfbpOLEo2IwNzJdMvE8aiRbPMxoTpgAJeyePh0SmO8M= -modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= modernc.org/libc v1.60.0 h1:XeRF1gXky7JE5E8IErtYAdKj+ykZPdYUsgJNQ8RFWIA= modernc.org/libc v1.60.0/go.mod h1:xJuobKuNxKH3RUatS7GjR+suWj+5c2K7bi4m/S5arOY= modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= @@ -635,8 +616,8 @@ modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4= modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0= modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc= modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss= -modernc.org/sqlite v1.32.0 h1:6BM4uGza7bWypsw4fdLRsLxut6bHe4c58VeqjRgST8s= -modernc.org/sqlite v1.32.0/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA= +modernc.org/sqlite v1.34.5 h1:Bb6SR13/fjp15jt70CL4f18JIN7p7dnMExd+UFnF15g= +modernc.org/sqlite v1.34.5/go.mod h1:YLuNmX9NKs8wRNK2ko1LW1NGYcc9FkBO69JOt1AR9JE= modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= diff --git a/hex/hex.go b/hex/hex.go deleted file mode 100644 index c7e1f860c..000000000 --- a/hex/hex.go +++ /dev/null @@ -1,124 +0,0 @@ -package hex - -import ( - "encoding/hex" - "fmt" - "math/big" - "strconv" - "strings" -) - -const ( - // Base represents the hexadecimal base, which is 16 - Base = 16 - - // BitSize64 64 bits - BitSize64 = 64 -) - -// DecError represents an error when decoding a hex value -type DecError struct{ msg string } - -func (err DecError) Error() string { return err.msg } - -// EncodeToHex generates a hex string based on the byte representation, with the '0x' prefix -func EncodeToHex(str []byte) string { - return "0x" + hex.EncodeToString(str) -} - -// EncodeToString is a wrapper method for hex.EncodeToString -func EncodeToString(str []byte) string { - return hex.EncodeToString(str) -} - -// DecodeString returns the byte representation of the hexadecimal string -func DecodeString(str string) ([]byte, error) { - return hex.DecodeString(str) -} - -// DecodeHex converts a hex string to a byte array -func DecodeHex(str string) ([]byte, error) { - str = strings.TrimPrefix(str, "0x") - - // Check if the string has an odd length - if len(str)%2 != 0 { - // Prepend a '0' to make it even-length - str = "0" + str - } - - return hex.DecodeString(str) -} - -// MustDecodeHex type-checks and converts a hex string to a byte array -func MustDecodeHex(str string) []byte { - buf, err := DecodeHex(str) - if err != nil { - panic(fmt.Errorf("could not decode hex: %w", err)) - } - - return buf -} - -// DecodeUint64 type-checks and converts a hex string to a uint64 -func DecodeUint64(str string) uint64 { - i := DecodeBig(str) - - return i.Uint64() -} - -// EncodeUint64 encodes a number as a hex string with 0x prefix. -func EncodeUint64(i uint64) string { - enc := make([]byte, 2, 10) //nolint:mnd - copy(enc, "0x") - - return string(strconv.AppendUint(enc, i, Base)) -} - -// BadNibble is a nibble that is bad -const BadNibble = ^uint64(0) - -// DecodeNibble decodes a byte into a uint64 -func DecodeNibble(in byte) uint64 { - switch { - case in >= '0' && in <= '9': - return uint64(in - '0') - case in >= 'A' && in <= 'F': - return uint64(in - 'A' + 10) //nolint:mnd - case in >= 'a' && in <= 'f': - return uint64(in - 'a' + 10) //nolint:mnd - default: - return BadNibble - } -} - -// EncodeBig encodes bigint as a hex string with 0x prefix. -// The sign of the integer is ignored. -func EncodeBig(bigint *big.Int) string { - numBits := bigint.BitLen() - if numBits == 0 { - return "0x0" - } - - return fmt.Sprintf("%#x", bigint) -} - -// DecodeBig converts a hex number to a big.Int value -func DecodeBig(hexNum string) *big.Int { - str := strings.TrimPrefix(hexNum, "0x") - createdNum := new(big.Int) - createdNum.SetString(str, Base) - - return createdNum -} - -// IsValid checks if the provided string is a valid hexadecimal value -func IsValid(s string) bool { - str := strings.TrimPrefix(s, "0x") - for _, b := range []byte(str) { - if !(b >= '0' && b <= '9' || b >= 'a' && b <= 'f' || b >= 'A' && b <= 'F') { - return false - } - } - - return true -} diff --git a/hex/hex_test.go b/hex/hex_test.go deleted file mode 100644 index da86da358..000000000 --- a/hex/hex_test.go +++ /dev/null @@ -1,52 +0,0 @@ -package hex - -import ( - "encoding/hex" - "math" - "math/big" - "testing" - - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -func TestEncodeDecodeBig(t *testing.T) { - b := big.NewInt(math.MaxInt64) - e := EncodeBig(b) - d := DecodeBig(e) - assert.Equal(t, b.Uint64(), d.Uint64()) -} - -// Define a struct for test cases -type TestCase struct { - input string - output []byte - err error -} - -// Unit test function -func TestDecodeHex(t *testing.T) { - testCases := []TestCase{ - {"0", []byte{0}, nil}, - {"00", []byte{0}, nil}, - {"0x0", []byte{0}, nil}, - {"0x00", []byte{0}, nil}, - {"1", []byte{1}, nil}, - {"01", []byte{1}, nil}, - {"", []byte{}, hex.ErrLength}, - {"0x", []byte{}, hex.ErrLength}, - {"zz", []byte{}, hex.InvalidByteError('z')}, - } - - for _, tc := range testCases { - t.Run(tc.input, func(t *testing.T) { - output, err := DecodeHex(tc.input) - if tc.err != nil { - require.Error(t, tc.err, err) - } else { - require.NoError(t, err) - } - require.Equal(t, output, tc.output) - }) - } -} diff --git a/l1infotree/hash.go b/l1infotree/hash.go deleted file mode 100644 index 5a33f5a32..000000000 --- a/l1infotree/hash.go +++ /dev/null @@ -1,45 +0,0 @@ -package l1infotree - -import ( - "encoding/binary" - - "github.com/ethereum/go-ethereum/common" - "github.com/iden3/go-iden3-crypto/keccak256" - "golang.org/x/crypto/sha3" -) - -// Hash calculates the keccak hash of elements. -func Hash(data ...[32]byte) [32]byte { - var res [32]byte - hash := sha3.NewLegacyKeccak256() - for _, d := range data { - hash.Write(d[:]) - } - copy(res[:], hash.Sum(nil)) - - return res -} - -func generateZeroHashes(height uint8) [][32]byte { - var zeroHashes = [][32]byte{ - common.Hash{}, - } - // This generates a leaf = HashZero in position 0. In the rest of the positions that - // are equivalent to the ascending levels, we set the hashes of the nodes. - // So all nodes from level i=5 will have the same value and same children nodes. - for i := 1; i <= int(height); i++ { - zeroHashes = append(zeroHashes, Hash(zeroHashes[i-1], zeroHashes[i-1])) - } - - return zeroHashes -} - -// HashLeafData calculates the keccak hash of the leaf values. -func HashLeafData(ger, prevBlockHash common.Hash, minTimestamp uint64) [32]byte { - var res [32]byte - t := make([]byte, 8) //nolint:mnd - binary.BigEndian.PutUint64(t, minTimestamp) - copy(res[:], keccak256.Hash(ger.Bytes(), prevBlockHash.Bytes(), t)) - - return res -} diff --git a/l1infotree/hash_test.go b/l1infotree/hash_test.go deleted file mode 100644 index a792c0b82..000000000 --- a/l1infotree/hash_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package l1infotree - -import ( - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/assert" -) - -func TestHashLeaf(t *testing.T) { - expectedLeafHash := common.HexToHash("0xf62f487534b899b1c362242616725878188ca891fab60854b792ca0628286de7") - - prevBlockHash := common.HexToHash("0x24a5871d68723340d9eadc674aa8ad75f3e33b61d5a9db7db92af856a19270bb") - var minTimestamp uint64 = 1697231573 - ger := common.HexToHash("0x16994edfddddb9480667b64174fc00d3b6da7290d37b8db3a16571b4ddf0789f") - - leaf := HashLeafData(ger, prevBlockHash, minTimestamp) - - assert.Equal(t, expectedLeafHash, common.BytesToHash(leaf[:])) -} diff --git a/l1infotree/tree.go b/l1infotree/tree.go deleted file mode 100644 index f3ad6d36e..000000000 --- a/l1infotree/tree.go +++ /dev/null @@ -1,206 +0,0 @@ -package l1infotree - -import ( - "fmt" - - "github.com/0xPolygon/cdk/log" - "github.com/ethereum/go-ethereum/common" -) - -// L1InfoTree provides methods to compute L1InfoTree -type L1InfoTree struct { - logger *log.Logger - height uint8 - zeroHashes [][32]byte - count uint32 - siblings [][32]byte - currentRoot common.Hash -} - -// NewL1InfoTree creates new L1InfoTree. -func NewL1InfoTree(logger *log.Logger, height uint8, initialLeaves [][32]byte) (*L1InfoTree, error) { - mt := &L1InfoTree{ - logger: logger, - zeroHashes: generateZeroHashes(height), - height: height, - count: uint32(len(initialLeaves)), - } - var err error - mt.siblings, mt.currentRoot, err = mt.initSiblings(initialLeaves) - if err != nil { - mt.logger.Error("error initializing siblings. Error: ", err) - - return nil, err - } - mt.logger.Debug("Initial count: ", mt.count) - mt.logger.Debug("Initial root: ", mt.currentRoot) - return mt, nil -} - -// ResetL1InfoTree resets the L1InfoTree. -func (mt *L1InfoTree) ResetL1InfoTree(initialLeaves [][32]byte) (*L1InfoTree, error) { - const defaultTreeHeight = 32 - mt.logger.Info("Resetting L1InfoTree...") - newMT := &L1InfoTree{ - zeroHashes: generateZeroHashes(defaultTreeHeight), - height: defaultTreeHeight, - count: uint32(len(initialLeaves)), - } - var err error - newMT.siblings, newMT.currentRoot, err = newMT.initSiblings(initialLeaves) - if err != nil { - mt.logger.Error("error initializing siblings. Error: ", err) - - return nil, err - } - mt.logger.Debug("Reset initial count: ", newMT.count) - mt.logger.Debug("Reset initial root: ", newMT.currentRoot) - return newMT, nil -} - -func buildIntermediate(leaves [][32]byte) ([][][]byte, [][32]byte) { - var ( - nodes [][][]byte - hashes [][32]byte - ) - for i := 0; i < len(leaves); i += 2 { - var left, right = i, i + 1 - hash := Hash(leaves[left], leaves[right]) - nodes = append(nodes, [][]byte{hash[:], leaves[left][:], leaves[right][:]}) - hashes = append(hashes, hash) - } - - return nodes, hashes -} - -// BuildL1InfoRoot computes the root given the leaves of the tree -func (mt *L1InfoTree) BuildL1InfoRoot(leaves [][32]byte) (common.Hash, error) { - var ( - nodes [][][][]byte - ns [][][]byte - ) - if len(leaves) == 0 { - leaves = append(leaves, mt.zeroHashes[0]) - } - - for h := uint8(0); h < mt.height; h++ { - if len(leaves)%2 == 1 { - leaves = append(leaves, mt.zeroHashes[h]) - } - ns, leaves = buildIntermediate(leaves) - nodes = append(nodes, ns) - } - if len(ns) != 1 { - return common.Hash{}, fmt.Errorf("error: more than one root detected: %+v", nodes) - } - - return common.BytesToHash(ns[0][0]), nil -} - -// ComputeMerkleProof computes the merkleProof and root given the leaves of the tree -func (mt *L1InfoTree) ComputeMerkleProof(gerIndex uint32, leaves [][32]byte) ([][32]byte, common.Hash, error) { - var ns [][][]byte - if len(leaves) == 0 { - leaves = append(leaves, mt.zeroHashes[0]) - } - var siblings [][32]byte - index := gerIndex - for h := uint8(0); h < mt.height; h++ { - if len(leaves)%2 == 1 { - leaves = append(leaves, mt.zeroHashes[h]) - } - if index >= uint32(len(leaves)) { - siblings = append(siblings, mt.zeroHashes[h]) - } else { - if index%2 == 1 { // If it is odd - siblings = append(siblings, leaves[index-1]) - } else { // It is even - siblings = append(siblings, leaves[index+1]) - } - } - var ( - nsi [][][]byte - hashes [][32]byte - ) - for i := 0; i < len(leaves); i += 2 { - var left, right = i, i + 1 - hash := Hash(leaves[left], leaves[right]) - nsi = append(nsi, [][]byte{hash[:], leaves[left][:], leaves[right][:]}) - hashes = append(hashes, hash) - } - // Find the index of the leaf in the next level of the tree. - // Divide the index by 2 to find the position in the upper level - index = uint32(float64(index) / 2) //nolint:mnd - ns = nsi - leaves = hashes - } - if len(ns) != 1 { - return nil, common.Hash{}, fmt.Errorf("error: more than one root detected: %+v", ns) - } - - return siblings, common.BytesToHash(ns[0][0]), nil -} - -// AddLeaf adds new leaves to the tree and computes the new root -func (mt *L1InfoTree) AddLeaf(index uint32, leaf [32]byte) (common.Hash, error) { - if index != mt.count { - return common.Hash{}, fmt.Errorf("mismatched leaf count: %d, expected: %d", index, mt.count) - } - cur := leaf - isFilledSubTree := true - - for h := uint8(0); h < mt.height; h++ { - if index&(1< 0 { - var child [32]byte - copy(child[:], cur[:]) - parent := Hash(mt.siblings[h], child) - cur = parent - } else { - if isFilledSubTree { - // we will update the sibling when the sub tree is complete - copy(mt.siblings[h][:], cur[:]) - // we have a left child in this layer, it means the right child is empty so the sub tree is not completed - isFilledSubTree = false - } - var child [32]byte - copy(child[:], cur[:]) - parent := Hash(child, mt.zeroHashes[h]) - cur = parent - // the sibling of 0 bit should be the zero hash, since we are in the last node of the tree - } - } - mt.currentRoot = cur - mt.count++ - - return cur, nil -} - -// initSiblings returns the siblings of the node at the given index. -// it is used to initialize the siblings array in the beginning. -func (mt *L1InfoTree) initSiblings(initialLeaves [][32]byte) ([][32]byte, common.Hash, error) { - if mt.count != uint32(len(initialLeaves)) { - return nil, [32]byte{}, fmt.Errorf("error: mt.count and initialLeaves length mismatch") - } - if mt.count == 0 { - var siblings [][32]byte - for h := 0; h < int(mt.height); h++ { - var left [32]byte - copy(left[:], mt.zeroHashes[h][:]) - siblings = append(siblings, left) - } - root, err := mt.BuildL1InfoRoot(initialLeaves) - if err != nil { - mt.logger.Error("error calculating initial root: ", err) - return nil, [32]byte{}, err - } - - return siblings, root, nil - } - - return mt.ComputeMerkleProof(mt.count, initialLeaves) -} - -// GetCurrentRootCountAndSiblings returns the latest root, count and sibblings -func (mt *L1InfoTree) GetCurrentRootCountAndSiblings() (common.Hash, uint32, [][32]byte) { - return mt.currentRoot, mt.count, mt.siblings -} diff --git a/l1infotree/tree_test.go b/l1infotree/tree_test.go deleted file mode 100644 index 6af4b8b30..000000000 --- a/l1infotree/tree_test.go +++ /dev/null @@ -1,131 +0,0 @@ -package l1infotree_test - -import ( - "encoding/hex" - "encoding/json" - "os" - "testing" - - "github.com/0xPolygon/cdk/l1infotree" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/test/vectors" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestComputeTreeRoot(t *testing.T) { - data, err := os.ReadFile("../test/vectors/src/merkle-tree/l1-info-tree/root-vectors.json") - require.NoError(t, err) - var mtTestVectors []vectors.L1InfoTree - err = json.Unmarshal(data, &mtTestVectors) - require.NoError(t, err) - for _, testVector := range mtTestVectors { - input := testVector.PreviousLeafValues - mt, err := l1infotree.NewL1InfoTree(log.GetDefaultLogger(), uint8(32), [][32]byte{}) - require.NoError(t, err) - - var leaves [][32]byte - for _, v := range input { - leaves = append(leaves, v) - } - - if len(leaves) != 0 { - root, err := mt.BuildL1InfoRoot(leaves) - require.NoError(t, err) - require.Equal(t, testVector.CurrentRoot, root) - } - - leaves = append(leaves, testVector.NewLeafValue) - newRoot, err := mt.BuildL1InfoRoot(leaves) - require.NoError(t, err) - require.Equal(t, testVector.NewRoot, newRoot) - } -} - -func TestComputeMerkleProof(t *testing.T) { - logger := log.GetDefaultLogger() - mt, err := l1infotree.NewL1InfoTree(logger, uint8(32), [][32]byte{}) - require.NoError(t, err) - leaves := [][32]byte{ - common.HexToHash("0x83fc198de31e1b2b1a8212d2430fbb7766c13d9ad305637dea3759065606475d"), - common.HexToHash("0x83fc198de31e1b2b1a8212d2430fbb7766c13d9ad305637dea3759065606475d"), - common.HexToHash("0x0349657c7850dc9b2b73010501b01cd6a38911b6a2ad2167c164c5b2a5b344de"), - common.HexToHash("0xb32f96fad8af99f3b3cb90dfbb4849f73435dbee1877e4ac2c213127379549ce"), - common.HexToHash("0x79ffa1294bf48e0dd41afcb23b2929921e4e17f2f81b7163c23078375b06ba4f"), - common.HexToHash("0x0004063b5c83f56a17f580db0908339c01206cdf8b59beb13ce6f146bb025fe2"), - common.HexToHash("0x68e4f2c517c7f60c3664ac6bbe78f904eacdbe84790aa0d15d79ddd6216c556e"), - common.HexToHash("0xf7245f4d84367a189b90873e4563a000702dbfe974b872fdb13323a828c8fb71"), - common.HexToHash("0x0e43332c71c6e2f4a48326258ea17b75d77d3063a4127047dd32a4cb089e62a4"), - common.HexToHash("0xd35a1dc90098c0869a69891094c119eb281cee1a7829d210df1bf8afbea08adc"), - common.HexToHash("0x13bffd0da370d1e80a470821f1bee9607f116881feb708f1ec255da1689164b3"), - common.HexToHash("0x5fa79a24c9bc73cd507b02e5917cef9782529080aa75eacb2bf4e1d45fda7f1d"), - common.HexToHash("0x975b5bbc67345adc6ee6d1d67d1d5cd2a430c231d93e5a8b5a6f00b0c0862215"), - common.HexToHash("0x0d0fa887c045a53ec6212dee58964d0ae89595b7d11745a05c397240a4dceb20"), - common.HexToHash("0xa6ae5bc494a2ee0e5173d0e0b546533973104e0031c69d0cd65cdc7bb4d64670"), - common.HexToHash("0x21ccc18196a8fd74e720c6c129977d80bb804d3331673d6411871df14f7e7ae4"), - common.HexToHash("0xf8b1b98ac75bea8dbed034d0b3cd08b4c9275644c2242781a827e53deb2386c3"), - common.HexToHash("0x26401c418ef8bc5a80380f25f16dfc78b7053a26c0ca425fda294b1678b779fc"), - common.HexToHash("0xc53fd99005361738fc811ce87d194deed34a7f06ebd5371b19a008e8d1e8799f"), - common.HexToHash("0x570bd643e35fbcda95393994812d9212335e6bd4504b3b1dc8f3c6f1eeb247b2"), - common.HexToHash("0xb21ac971d007810540583bd3c0d4f35e0c2f4b62753e51c104a5753c6372caf8"), - common.HexToHash("0xb8dae305b34c749cbbd98993bfd71ec2323e8364861f25b4c5e0ac3c9587e16d"), - common.HexToHash("0x57c7fabd0f70e0059e871953fcb3dd43c6b8a5f348dbe771190cc8b0320336a5"), - common.HexToHash("0x95b0d23c347e2a88fc8e2ab900b09212a1295ab8f169075aa27e8719557d9b06"), - common.HexToHash("0x95b0d23c347e2a88fc8e2ab900b09212a1295ab8f169075aa27e8719557d9b06"), - common.HexToHash("0x95b0d23c347e2a88fc8e2ab900b09212a1295ab8f169075aa27e8719557d9b06"), - } - require.Equal(t, 26, len(leaves)) - siblings, root, err := mt.ComputeMerkleProof(1, leaves) - require.NoError(t, err) - require.Equal(t, "0x4ed479841384358f765966486782abb598ece1d4f834a22474050d66a18ad296", root.String()) - expectedProof := []string{"0x83fc198de31e1b2b1a8212d2430fbb7766c13d9ad305637dea3759065606475d", "0x2815e0bbb1ec18b8b1bc64454a86d072e12ee5d43bb559b44059e01edff0af7a", "0x7fb6cc0f2120368a845cf435da7102ff6e369280f787bc51b8a989fc178f7252", "0x407db5edcdc0ddd4f7327f208f46db40c4c4dbcc46c94a757e1d1654acbd8b72", "0xce2cdd1ef2e87e82264532285998ff37024404ab3a2b77b50eb1ad856ae83e14", "0x0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d", "0x887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968", "0xffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83", "0x9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af", "0xcefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0", "0xf9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5", "0xf8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892", "0x3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c", "0xc1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb", "0x5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc", "0xda7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2", "0x2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f", "0xe1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a", "0x5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0", "0xb46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0", "0xc65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2", "0xf4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9", "0x5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377", "0x4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652", "0xcdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef", "0x0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d", "0xb8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0", "0x838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e", "0x662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e", "0x388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322", "0x93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735", "0x8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9"} - for i := 0; i < len(siblings); i++ { - require.Equal(t, expectedProof[i], "0x"+hex.EncodeToString(siblings[i][:])) - } -} - -func TestAddLeaf(t *testing.T) { - data, err := os.ReadFile("../test/vectors/src/merkle-tree/l1-info-tree/proof-vectors.json") - require.NoError(t, err) - var mtTestVectors []vectors.L1InfoTreeProof - err = json.Unmarshal(data, &mtTestVectors) - require.NoError(t, err) - testVector := mtTestVectors[3] - var leaves [][32]byte - mt, err := l1infotree.NewL1InfoTree(log.GetDefaultLogger(), uint8(32), leaves) - require.NoError(t, err) - for _, leaf := range testVector.Leaves { - _, count, _ := mt.GetCurrentRootCountAndSiblings() - _, err := mt.AddLeaf(count, leaf) - require.NoError(t, err) - } - log.Debugf("%d leaves added successfully", len(testVector.Leaves)) - root, _, _ := mt.GetCurrentRootCountAndSiblings() - require.Equal(t, testVector.Root, root) - log.Debug("Final root: ", root) -} - -func TestAddLeaf2(t *testing.T) { - data, err := os.ReadFile("../test/vectors/src/merkle-tree/l1-info-tree/root-vectors.json") - require.NoError(t, err) - var mtTestVectors []vectors.L1InfoTree - err = json.Unmarshal(data, &mtTestVectors) - require.NoError(t, err) - for _, testVector := range mtTestVectors { - input := testVector.PreviousLeafValues - - var leaves [][32]byte - for _, v := range input { - leaves = append(leaves, v) - } - mt, err := l1infotree.NewL1InfoTree(log.GetDefaultLogger(), uint8(32), leaves) - require.NoError(t, err) - - initialRoot, count, _ := mt.GetCurrentRootCountAndSiblings() - require.Equal(t, testVector.CurrentRoot, initialRoot) - - newRoot, err := mt.AddLeaf(count, testVector.NewLeafValue) - require.NoError(t, err) - require.Equal(t, testVector.NewRoot, newRoot) - } -} diff --git a/l1infotreesync/config.go b/l1infotreesync/config.go deleted file mode 100644 index 64318fae4..000000000 --- a/l1infotreesync/config.go +++ /dev/null @@ -1,20 +0,0 @@ -package l1infotreesync - -import ( - "github.com/0xPolygon/cdk/config/types" - "github.com/ethereum/go-ethereum/common" -) - -type Config struct { - DBPath string `mapstructure:"DBPath"` - GlobalExitRootAddr common.Address `mapstructure:"GlobalExitRootAddr"` - RollupManagerAddr common.Address `mapstructure:"RollupManagerAddr"` - SyncBlockChunkSize uint64 `mapstructure:"SyncBlockChunkSize"` - // BlockFinality indicates the status of the blocks that will be queried in order to sync - BlockFinality string `jsonschema:"enum=LatestBlock, enum=SafeBlock, enum=PendingBlock, enum=FinalizedBlock, enum=EarliestBlock" mapstructure:"BlockFinality"` //nolint:lll - URLRPCL1 string `mapstructure:"URLRPCL1"` - WaitForNewBlocksPeriod types.Duration `mapstructure:"WaitForNewBlocksPeriod"` - InitialBlock uint64 `mapstructure:"InitialBlock"` - RetryAfterErrorPeriod types.Duration `mapstructure:"RetryAfterErrorPeriod"` - MaxRetryAttemptsAfterError int `mapstructure:"MaxRetryAttemptsAfterError"` -} diff --git a/l1infotreesync/downloader.go b/l1infotreesync/downloader.go deleted file mode 100644 index 48e237025..000000000 --- a/l1infotreesync/downloader.go +++ /dev/null @@ -1,191 +0,0 @@ -package l1infotreesync - -import ( - "fmt" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/etrog/polygonrollupmanager" - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmglobalexitrootv2" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum" - "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" -) - -var ( - updateL1InfoTreeSignatureV1 = crypto.Keccak256Hash([]byte("UpdateL1InfoTree(bytes32,bytes32)")) - updateL1InfoTreeSignatureV2 = crypto.Keccak256Hash([]byte("UpdateL1InfoTreeV2(bytes32,uint32,uint256,uint64)")) - verifyBatchesSignature = crypto.Keccak256Hash( - []byte("VerifyBatches(uint32,uint64,bytes32,bytes32,address)"), - ) - verifyBatchesTrustedAggregatorSignature = crypto.Keccak256Hash( - []byte("VerifyBatchesTrustedAggregator(uint32,uint64,bytes32,bytes32,address)"), - ) - initL1InfoRootMapSignature = crypto.Keccak256Hash([]byte("InitL1InfoRootMap(uint32,bytes32)")) -) - -type EthClienter interface { - ethereum.LogFilterer - ethereum.BlockNumberReader - ethereum.ChainReader - bind.ContractBackend -} - -func checkSMCIsRollupManager(rollupManagerAddr common.Address, - rollupManagerContract *polygonrollupmanager.Polygonrollupmanager) error { - bridgeAddr, err := rollupManagerContract.BridgeAddress(nil) - if err != nil { - return fmt.Errorf("fail sanity check RollupManager(%s) Contract. Err: %w", rollupManagerAddr.String(), err) - } - log.Infof("sanity check rollupManager(%s) OK. bridgeAddr: %s", rollupManagerAddr.String(), bridgeAddr.String()) - return nil -} - -func checkSMCIsGlobalExitRoot(globalExitRootAddr common.Address, - gerContract *polygonzkevmglobalexitrootv2.Polygonzkevmglobalexitrootv2) error { - depositCount, err := gerContract.DepositCount(nil) - if err != nil { - return fmt.Errorf("fail sanity check GlobalExitRoot(%s) Contract. Err: %w", globalExitRootAddr.String(), err) - } - log.Infof("sanity check GlobalExitRoot(%s) OK. DepositCount: %v", globalExitRootAddr.String(), depositCount) - return nil -} - -func sanityCheckContracts(globalExitRoot, rollupManager common.Address, - gerContract *polygonzkevmglobalexitrootv2.Polygonzkevmglobalexitrootv2, - rollupManagerContract *polygonrollupmanager.Polygonrollupmanager) error { - errGER := checkSMCIsGlobalExitRoot(globalExitRoot, gerContract) - errRollup := checkSMCIsRollupManager(rollupManager, rollupManagerContract) - if errGER != nil || errRollup != nil { - err := fmt.Errorf("sanityCheckContracts: fails sanity check contracts. ErrGER: %w, ErrRollup: %w", errGER, errRollup) - log.Error(err) - return err - } - return nil -} - -func createContracts(client EthClienter, globalExitRoot, rollupManager common.Address) ( - *polygonzkevmglobalexitrootv2.Polygonzkevmglobalexitrootv2, - *polygonrollupmanager.Polygonrollupmanager, - error) { - gerContract, err := polygonzkevmglobalexitrootv2.NewPolygonzkevmglobalexitrootv2(globalExitRoot, client) - if err != nil { - return nil, nil, err - } - - rollupManagerContract, err := polygonrollupmanager.NewPolygonrollupmanager(rollupManager, client) - if err != nil { - return nil, nil, err - } - return gerContract, rollupManagerContract, nil -} - -func buildAppender(client EthClienter, globalExitRoot, - rollupManager common.Address, flags CreationFlags) (sync.LogAppenderMap, error) { - ger, rm, err := createContracts(client, globalExitRoot, rollupManager) - if err != nil { - err := fmt.Errorf("buildAppender: fails contracts creation. Err:%w", err) - log.Error(err) - return nil, err - } - err = sanityCheckContracts(globalExitRoot, rollupManager, ger, rm) - if err != nil && flags&FlagAllowWrongContractsAddrs == 0 { - return nil, fmt.Errorf("buildAppender: fails sanity check contracts. Err:%w", err) - } - - appender := make(sync.LogAppenderMap) - appender[initL1InfoRootMapSignature] = func(b *sync.EVMBlock, l types.Log) error { - init, err := ger.ParseInitL1InfoRootMap(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using ger.ParseInitL1InfoRootMap: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{InitL1InfoRootMap: &InitL1InfoRootMap{ - LeafCount: init.LeafCount, - CurrentL1InfoRoot: init.CurrentL1InfoRoot, - }}) - - return nil - } - appender[updateL1InfoTreeSignatureV1] = func(b *sync.EVMBlock, l types.Log) error { - l1InfoTreeUpdate, err := ger.ParseUpdateL1InfoTree(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using ger.ParseUpdateL1InfoTree: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{UpdateL1InfoTree: &UpdateL1InfoTree{ - BlockPosition: uint64(l.Index), - MainnetExitRoot: l1InfoTreeUpdate.MainnetExitRoot, - RollupExitRoot: l1InfoTreeUpdate.RollupExitRoot, - ParentHash: b.ParentHash, - Timestamp: b.Timestamp, - }}) - - return nil - } - - appender[updateL1InfoTreeSignatureV2] = func(b *sync.EVMBlock, l types.Log) error { - l1InfoTreeUpdateV2, err := ger.ParseUpdateL1InfoTreeV2(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using ger.ParseUpdateL1InfoTreeV2: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{UpdateL1InfoTreeV2: &UpdateL1InfoTreeV2{ - CurrentL1InfoRoot: l1InfoTreeUpdateV2.CurrentL1InfoRoot, - LeafCount: l1InfoTreeUpdateV2.LeafCount, - Blockhash: common.BytesToHash(l1InfoTreeUpdateV2.Blockhash.Bytes()), - MinTimestamp: l1InfoTreeUpdateV2.MinTimestamp, - }}) - - return nil - } - // This event is coming from RollupManager - appender[verifyBatchesSignature] = func(b *sync.EVMBlock, l types.Log) error { - verifyBatches, err := rm.ParseVerifyBatches(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using rm.ParseVerifyBatches: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{VerifyBatches: &VerifyBatches{ - BlockPosition: uint64(l.Index), - RollupID: verifyBatches.RollupID, - NumBatch: verifyBatches.NumBatch, - StateRoot: verifyBatches.StateRoot, - ExitRoot: verifyBatches.ExitRoot, - Aggregator: verifyBatches.Aggregator, - }}) - - return nil - } - appender[verifyBatchesTrustedAggregatorSignature] = func(b *sync.EVMBlock, l types.Log) error { - verifyBatches, err := rm.ParseVerifyBatchesTrustedAggregator(l) - if err != nil { - return fmt.Errorf( - "error parsing log %+v using rm.ParseVerifyBatches: %w", - l, err, - ) - } - b.Events = append(b.Events, Event{VerifyBatches: &VerifyBatches{ - BlockPosition: uint64(l.Index), - RollupID: verifyBatches.RollupID, - NumBatch: verifyBatches.NumBatch, - StateRoot: verifyBatches.StateRoot, - ExitRoot: verifyBatches.ExitRoot, - Aggregator: verifyBatches.Aggregator, - }}) - - return nil - } - - return appender, nil -} diff --git a/l1infotreesync/downloader_test.go b/l1infotreesync/downloader_test.go deleted file mode 100644 index 9d79b9a6c..000000000 --- a/l1infotreesync/downloader_test.go +++ /dev/null @@ -1,55 +0,0 @@ -package l1infotreesync - -import ( - "fmt" - "math/big" - "strings" - "testing" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmglobalexitrootv2" - mocks_l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync/mocks" - "github.com/ethereum/go-ethereum/accounts/abi" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func TestBuildAppenderErrorOnBadContractAddr(t *testing.T) { - l1Client := mocks_l1infotreesync.NewEthClienter(t) - globalExitRoot := common.HexToAddress("0x1") - rollupManager := common.HexToAddress("0x2") - l1Client.EXPECT().CallContract(mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("test-error")) - flags := FlagNone - _, err := buildAppender(l1Client, globalExitRoot, rollupManager, flags) - require.Error(t, err) -} - -func TestBuildAppenderBypassBadContractAddr(t *testing.T) { - l1Client := mocks_l1infotreesync.NewEthClienter(t) - globalExitRoot := common.HexToAddress("0x1") - rollupManager := common.HexToAddress("0x2") - l1Client.EXPECT().CallContract(mock.Anything, mock.Anything, mock.Anything).Return(nil, fmt.Errorf("test-error")) - flags := FlagAllowWrongContractsAddrs - _, err := buildAppender(l1Client, globalExitRoot, rollupManager, flags) - require.NoError(t, err) -} - -func TestBuildAppenderVerifiedContractAddr(t *testing.T) { - l1Client := mocks_l1infotreesync.NewEthClienter(t) - globalExitRoot := common.HexToAddress("0x1") - rollupManager := common.HexToAddress("0x2") - - smcAbi, err := abi.JSON(strings.NewReader(polygonzkevmglobalexitrootv2.Polygonzkevmglobalexitrootv2ABI)) - require.NoError(t, err) - bigInt := big.NewInt(1) - returnGER, err := smcAbi.Methods["depositCount"].Outputs.Pack(bigInt) - require.NoError(t, err) - l1Client.EXPECT().CallContract(mock.Anything, mock.Anything, mock.Anything).Return(returnGER, nil).Once() - v := common.HexToAddress("0x1234") - returnRM, err := smcAbi.Methods["bridgeAddress"].Outputs.Pack(v) - require.NoError(t, err) - l1Client.EXPECT().CallContract(mock.Anything, mock.Anything, mock.Anything).Return(returnRM, nil).Once() - flags := FlagNone - _, err = buildAppender(l1Client, globalExitRoot, rollupManager, flags) - require.NoError(t, err) -} diff --git a/l1infotreesync/e2e_test.go b/l1infotreesync/e2e_test.go deleted file mode 100644 index ea3db7ca9..000000000 --- a/l1infotreesync/e2e_test.go +++ /dev/null @@ -1,345 +0,0 @@ -package l1infotreesync_test - -import ( - "context" - "fmt" - "math/big" - "path" - "strconv" - "testing" - "time" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmglobalexitrootv2" - cdktypes "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/l1infotreesync" - mocks_l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync/mocks" - "github.com/0xPolygon/cdk/reorgdetector" - "github.com/0xPolygon/cdk/test/contracts/verifybatchesmock" - "github.com/0xPolygon/cdk/test/helpers" - "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/simulated" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func newSimulatedClient(t *testing.T) ( - *simulated.Backend, - *bind.TransactOpts, - common.Address, - common.Address, - *polygonzkevmglobalexitrootv2.Polygonzkevmglobalexitrootv2, - *verifybatchesmock.Verifybatchesmock, -) { - t.Helper() - ctx := context.Background() - - deployerAuth, err := helpers.CreateAccount(big.NewInt(1337)) - require.NoError(t, err) - - client, setup := helpers.NewSimulatedBackend(t, nil, deployerAuth) - - nonce, err := client.Client().PendingNonceAt(ctx, setup.UserAuth.From) - require.NoError(t, err) - - precalculatedGERAddr := crypto.CreateAddress(setup.UserAuth.From, nonce+1) - verifyAddr, _, verifyContract, err := verifybatchesmock.DeployVerifybatchesmock(setup.UserAuth, client.Client(), precalculatedGERAddr) - require.NoError(t, err) - client.Commit() - - gerAddr, _, gerContract, err := polygonzkevmglobalexitrootv2.DeployPolygonzkevmglobalexitrootv2(setup.UserAuth, client.Client(), verifyAddr, setup.UserAuth.From) - require.NoError(t, err) - require.Equal(t, precalculatedGERAddr, gerAddr) - client.Commit() - - err = setup.DeployBridge(client, gerAddr, 0) - require.NoError(t, err) - - return client, setup.UserAuth, gerAddr, verifyAddr, gerContract, verifyContract -} - -func TestE2E(t *testing.T) { - ctx, cancelCtx := context.WithCancel(context.Background()) - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestE2E.sqlite") - - rdm := mocks_l1infotreesync.NewReorgDetectorMock(t) - rdm.On("Subscribe", mock.Anything).Return(&reorgdetector.Subscription{}, nil) - rdm.On("AddBlockToTrack", mock.Anything, mock.Anything, mock.Anything, mock.Anything).Return(nil) - - client, auth, gerAddr, verifyAddr, gerSc, verifySC := newSimulatedClient(t) - syncer, err := l1infotreesync.New(ctx, dbPath, gerAddr, verifyAddr, 10, etherman.LatestBlock, rdm, client.Client(), time.Millisecond, 0, 100*time.Millisecond, 25, - l1infotreesync.FlagAllowWrongContractsAddrs, etherman.SafeBlock) - require.NoError(t, err) - - go syncer.Start(ctx) - - // Update GER 3 times - for i := 0; i < 3; i++ { - tx, err := gerSc.UpdateExitRoot(auth, common.HexToHash(strconv.Itoa(i))) - require.NoError(t, err) - client.Commit() - g, err := gerSc.L1InfoRootMap(nil, uint32(i+1)) - require.NoError(t, err) - receipt, err := client.Client().TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - require.Equal(t, receipt.Status, types.ReceiptStatusSuccessful) - // Let the processor catch up - helpers.RequireProcessorUpdated(t, syncer, receipt.BlockNumber.Uint64()) - - expectedGER, err := gerSc.GetLastGlobalExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - info, err := syncer.GetInfoByIndex(ctx, uint32(i)) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedGER), info.GlobalExitRoot, fmt.Sprintf("index: %d", i)) - require.Equal(t, receipt.BlockNumber.Uint64(), info.BlockNumber) - - expectedRoot, err := gerSc.GetRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - require.Equal(t, g, expectedRoot) - actualRoot, err := syncer.GetL1InfoTreeRootByIndex(ctx, uint32(i)) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRoot), actualRoot.Hash) - } - - // Restart syncer - cancelCtx() - ctx = context.Background() - go syncer.Start(ctx) - - // Update 3 rollups (verify batches event) 3 times - for rollupID := uint32(1); rollupID < 3; rollupID++ { - for i := 0; i < 3; i++ { - newLocalExitRoot := common.HexToHash(strconv.Itoa(int(rollupID)) + "ffff" + strconv.Itoa(i)) - tx, err := verifySC.VerifyBatches(auth, rollupID, 0, newLocalExitRoot, common.Hash{}, i%2 != 0) - require.NoError(t, err) - client.Commit() - receipt, err := client.Client().TransactionReceipt(ctx, tx.Hash()) - require.NoError(t, err) - require.Equal(t, receipt.Status, types.ReceiptStatusSuccessful) - require.True(t, len(receipt.Logs) == 1+i%2+i%2) - - // Let the processor catch - helpers.RequireProcessorUpdated(t, syncer, receipt.BlockNumber.Uint64()) - - // Assert rollup exit root - expectedRollupExitRoot, err := verifySC.GetRollupExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualRollupExitRoot, err := syncer.GetLastRollupExitRoot(ctx) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRollupExitRoot), actualRollupExitRoot.Hash, fmt.Sprintf("rollupID: %d, i: %d", rollupID, i)) - - // Assert verify batches - expectedVerify := l1infotreesync.VerifyBatches{ - BlockNumber: receipt.BlockNumber.Uint64(), - BlockPosition: uint64(i%2 + i%2), - RollupID: rollupID, - ExitRoot: newLocalExitRoot, - Aggregator: auth.From, - RollupExitRoot: expectedRollupExitRoot, - } - actualVerify, err := syncer.GetLastVerifiedBatches(rollupID) - require.NoError(t, err) - require.Equal(t, expectedVerify, *actualVerify) - } - } -} - -func TestWithReorgs(t *testing.T) { - ctx := context.Background() - dbPathSyncer := path.Join(t.TempDir(), "l1infotreesyncTestWithReorgs_sync.sqlite") - dbPathReorg := path.Join(t.TempDir(), "l1infotreesyncTestWithReorgs_reorg.sqlite") - - client, auth, gerAddr, verifyAddr, gerSc, verifySC := newSimulatedClient(t) - - rd, err := reorgdetector.New(client.Client(), reorgdetector.Config{DBPath: dbPathReorg, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 30)}, reorgdetector.L1) - require.NoError(t, err) - require.NoError(t, rd.Start(ctx)) - - syncer, err := l1infotreesync.New(ctx, dbPathSyncer, gerAddr, verifyAddr, 10, etherman.LatestBlock, rd, client.Client(), time.Millisecond, 0, time.Second, 25, - l1infotreesync.FlagAllowWrongContractsAddrs, etherman.SafeBlock) - require.NoError(t, err) - go syncer.Start(ctx) - - // Commit block - header, err := client.Client().HeaderByHash(ctx, client.Commit()) // Block 3 - require.NoError(t, err) - reorgFrom := header.Hash() - fmt.Println("start from header:", header.Number) - - updateL1InfoTreeAndRollupExitTree := func(i int, rollupID uint32) { - // Update L1 Info Tree - _, err := gerSc.UpdateExitRoot(auth, common.HexToHash(strconv.Itoa(i))) - require.NoError(t, err) - - // Update L1 Info Tree + Rollup Exit Tree - newLocalExitRoot := common.HexToHash(strconv.Itoa(i) + "ffff" + strconv.Itoa(1)) - _, err = verifySC.VerifyBatchesTrustedAggregator(auth, rollupID, 0, newLocalExitRoot, common.Hash{}, true) - require.NoError(t, err) - - // Update Rollup Exit Tree - newLocalExitRoot = common.HexToHash(strconv.Itoa(i) + "ffff" + strconv.Itoa(2)) - _, err = verifySC.VerifyBatchesTrustedAggregator(auth, rollupID, 0, newLocalExitRoot, common.Hash{}, false) - require.NoError(t, err) - } - - // create some events and update the trees - updateL1InfoTreeAndRollupExitTree(1, 1) - - // Block 4 - helpers.CommitBlocks(t, client, 1, time.Second*5) - - // Make sure syncer is up to date - waitForSyncerToCatchUp(ctx, t, syncer, client) - - // Assert rollup exit root - expectedRollupExitRoot, err := verifySC.GetRollupExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualRollupExitRoot, err := syncer.GetLastRollupExitRoot(ctx) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRollupExitRoot), actualRollupExitRoot.Hash) - - // Assert L1 Info tree root - expectedL1InfoRoot, err := gerSc.GetRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - expectedGER, err := gerSc.GetLastGlobalExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualL1InfoRoot, err := syncer.GetLastL1InfoTreeRoot(ctx) - require.NoError(t, err) - info, err := syncer.GetInfoByIndex(ctx, actualL1InfoRoot.Index) - require.NoError(t, err) - - require.Equal(t, common.Hash(expectedL1InfoRoot), actualL1InfoRoot.Hash) - require.Equal(t, common.Hash(expectedGER), info.GlobalExitRoot, fmt.Sprintf("%+v", info)) - - // Forking from block 3 - err = client.Fork(reorgFrom) - require.NoError(t, err) - - // Block 4, 5, 6 after the fork - helpers.CommitBlocks(t, client, 3, time.Millisecond*500) - - // Assert rollup exit root after the fork - should be zero since there are no events in the block after the fork - expectedRollupExitRoot, err = verifySC.GetRollupExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualRollupExitRoot, err = syncer.GetLastRollupExitRoot(ctx) - require.ErrorContains(t, err, "not found") // rollup exit tree reorged, it does not have any exits in it - require.Equal(t, common.Hash(expectedRollupExitRoot), actualRollupExitRoot.Hash) - - // Forking from block 3 again - err = client.Fork(reorgFrom) - require.NoError(t, err) - time.Sleep(time.Millisecond * 500) - - helpers.CommitBlocks(t, client, 1, time.Millisecond*100) - - // create some events and update the trees - updateL1InfoTreeAndRollupExitTree(2, 1) - - helpers.CommitBlocks(t, client, 1, time.Millisecond*100) - - // Make sure syncer is up to date - waitForSyncerToCatchUp(ctx, t, syncer, client) - - // Assert rollup exit root after the fork - should be zero since there are no events in the block after the fork - expectedRollupExitRoot, err = verifySC.GetRollupExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualRollupExitRoot, err = syncer.GetLastRollupExitRoot(ctx) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRollupExitRoot), actualRollupExitRoot.Hash) -} - -func TestStressAndReorgs(t *testing.T) { - const ( - totalIterations = 3 - blocksInIteration = 140 - reorgEveryXIterations = 70 - reorgSizeInBlocks = 2 - maxRollupID = 31 - extraBlocksToMine = 10 - ) - - ctx := context.Background() - dbPathSyncer := path.Join(t.TempDir(), "l1infotreesyncTestStressAndReorgs_sync.sqlite") - dbPathReorg := path.Join(t.TempDir(), "l1infotreesyncTestStressAndReorgs_reorg.sqlite") - - client, auth, gerAddr, verifyAddr, gerSc, verifySC := newSimulatedClient(t) - - rd, err := reorgdetector.New(client.Client(), reorgdetector.Config{DBPath: dbPathReorg, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, reorgdetector.L1) - require.NoError(t, err) - require.NoError(t, rd.Start(ctx)) - - syncer, err := l1infotreesync.New(ctx, dbPathSyncer, gerAddr, verifyAddr, 10, etherman.LatestBlock, rd, client.Client(), time.Millisecond, 0, time.Second, 100, - l1infotreesync.FlagAllowWrongContractsAddrs, etherman.SafeBlock) - require.NoError(t, err) - go syncer.Start(ctx) - - updateL1InfoTreeAndRollupExitTree := func(i, j int, rollupID uint32) { - // Update L1 Info Tree - _, err := gerSc.UpdateExitRoot(auth, common.HexToHash(strconv.Itoa(i))) - require.NoError(t, err) - - // Update L1 Info Tree + Rollup Exit Tree - newLocalExitRoot := common.HexToHash(strconv.Itoa(i) + "ffff" + strconv.Itoa(j)) - _, err = verifySC.VerifyBatches(auth, rollupID, 0, newLocalExitRoot, common.Hash{}, true) - require.NoError(t, err) - - // Update Rollup Exit Tree - newLocalExitRoot = common.HexToHash(strconv.Itoa(i) + "fffa" + strconv.Itoa(j)) - _, err = verifySC.VerifyBatches(auth, rollupID, 0, newLocalExitRoot, common.Hash{}, false) - require.NoError(t, err) - } - - for i := 1; i <= totalIterations; i++ { - for j := 1; j <= blocksInIteration; j++ { - helpers.CommitBlocks(t, client, 1, time.Millisecond*10) - if j%reorgEveryXIterations == 0 { - helpers.Reorg(t, client, reorgSizeInBlocks) - } else { - updateL1InfoTreeAndRollupExitTree(i, j, uint32(j%maxRollupID)+1) - } - } - } - - helpers.CommitBlocks(t, client, 11, time.Millisecond*10) - - waitForSyncerToCatchUp(ctx, t, syncer, client) - - // Assert rollup exit root - expectedRollupExitRoot, err := verifySC.GetRollupExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - actualRollupExitRoot, err := syncer.GetLastRollupExitRoot(ctx) - require.NoError(t, err) - require.Equal(t, common.Hash(expectedRollupExitRoot), actualRollupExitRoot.Hash) - - // Assert L1 Info tree root - expectedL1InfoRoot, err := gerSc.GetRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - expectedGER, err := gerSc.GetLastGlobalExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - lastRoot, err := syncer.GetLastL1InfoTreeRoot(ctx) - require.NoError(t, err) - info, err := syncer.GetInfoByIndex(ctx, lastRoot.Index) - require.NoError(t, err, fmt.Sprintf("index: %d", lastRoot.Index)) - - t.Logf("expectedL1InfoRoot: %s", common.Hash(expectedL1InfoRoot).String()) - require.Equal(t, common.Hash(expectedGER), info.GlobalExitRoot, fmt.Sprintf("%+v", info)) - require.Equal(t, common.Hash(expectedL1InfoRoot), lastRoot.Hash) -} - -func waitForSyncerToCatchUp(ctx context.Context, t *testing.T, syncer *l1infotreesync.L1InfoTreeSync, client *simulated.Backend) { - t.Helper() - for { - lastBlockNum, err := client.Client().BlockNumber(ctx) - require.NoError(t, err) - helpers.RequireProcessorUpdated(t, syncer, lastBlockNum) - time.Sleep(time.Second / 2) - lastBlockNum2, err := client.Client().BlockNumber(ctx) - require.NoError(t, err) - if lastBlockNum == lastBlockNum2 { - return - } - } -} diff --git a/l1infotreesync/l1infotreesync.go b/l1infotreesync/l1infotreesync.go deleted file mode 100644 index df685d520..000000000 --- a/l1infotreesync/l1infotreesync.go +++ /dev/null @@ -1,278 +0,0 @@ -package l1infotreesync - -import ( - "context" - "errors" - "time" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/sync" - "github.com/0xPolygon/cdk/tree" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" -) - -type CreationFlags uint64 - -const ( - reorgDetectorID = "l1infotreesync" - downloadBufferSize = 1000 - // CreationFlags defitinion - FlagNone CreationFlags = 0 - FlagAllowWrongContractsAddrs CreationFlags = 1 << iota // Allow to set wrong contracts addresses -) - -var ( - ErrNotFound = errors.New("l1infotreesync: not found") -) - -type L1InfoTreeSync struct { - processor *processor - driver *sync.EVMDriver -} - -// New creates a L1 Info tree syncer that syncs the L1 info tree -// and the rollup exit tree -func New( - ctx context.Context, - dbPath string, - globalExitRoot, rollupManager common.Address, - syncBlockChunkSize uint64, - blockFinalityType etherman.BlockNumberFinality, - rd sync.ReorgDetector, - l1Client EthClienter, - waitForNewBlocksPeriod time.Duration, - initialBlock uint64, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - flags CreationFlags, - finalizedBlockType etherman.BlockNumberFinality, -) (*L1InfoTreeSync, error) { - processor, err := newProcessor(dbPath) - if err != nil { - return nil, err - } - // TODO: get the initialBlock from L1 to simplify config - lastProcessedBlock, err := processor.GetLastProcessedBlock(ctx) - if err != nil { - return nil, err - } - if initialBlock > 0 && lastProcessedBlock < initialBlock-1 { - err = processor.ProcessBlock(ctx, sync.Block{ - Num: initialBlock - 1, - }) - if err != nil { - return nil, err - } - } - rh := &sync.RetryHandler{ - RetryAfterErrorPeriod: retryAfterErrorPeriod, - MaxRetryAttemptsAfterError: maxRetryAttemptsAfterError, - } - - appender, err := buildAppender(l1Client, globalExitRoot, rollupManager, flags) - if err != nil { - return nil, err - } - downloader, err := sync.NewEVMDownloader( - "l1infotreesync", - l1Client, - syncBlockChunkSize, - blockFinalityType, - waitForNewBlocksPeriod, - appender, - []common.Address{globalExitRoot, rollupManager}, - rh, - finalizedBlockType, - ) - if err != nil { - return nil, err - } - - driver, err := sync.NewEVMDriver(rd, processor, downloader, reorgDetectorID, downloadBufferSize, rh) - if err != nil { - return nil, err - } - - return &L1InfoTreeSync{ - processor: processor, - driver: driver, - }, nil -} - -// Start starts the synchronization process -func (s *L1InfoTreeSync) Start(ctx context.Context) { - s.driver.Sync(ctx) -} - -// GetL1InfoTreeMerkleProof creates a merkle proof for the L1 Info tree -func (s *L1InfoTreeSync) GetL1InfoTreeMerkleProof(ctx context.Context, index uint32) (types.Proof, types.Root, error) { - if s.processor.isHalted() { - return types.Proof{}, types.Root{}, sync.ErrInconsistentState - } - return s.processor.GetL1InfoTreeMerkleProof(ctx, index) -} - -// GetRollupExitTreeMerkleProof creates a merkle proof for the rollup exit tree -func (s *L1InfoTreeSync) GetRollupExitTreeMerkleProof( - ctx context.Context, - networkID uint32, - root common.Hash, -) (types.Proof, error) { - if s.processor.isHalted() { - return types.Proof{}, sync.ErrInconsistentState - } - if networkID == 0 { - return tree.EmptyProof, nil - } - - return s.processor.rollupExitTree.GetProof(ctx, networkID-1, root) -} - -func translateError(err error) error { - if errors.Is(err, db.ErrNotFound) { - return ErrNotFound - } - return err -} - -// GetLatestInfoUntilBlock returns the most recent L1InfoTreeLeaf that occurred before or at blockNum. -// If the blockNum has not been processed yet the error ErrBlockNotProcessed will be returned -// It can returns next errors: -// - ErrBlockNotProcessed, -// - ErrNotFound -func (s *L1InfoTreeSync) GetLatestInfoUntilBlock(ctx context.Context, blockNum uint64) (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - leaf, err := s.processor.GetLatestInfoUntilBlock(ctx, blockNum) - return leaf, translateError(err) -} - -// GetInfoByIndex returns the value of a leaf (not the hash) of the L1 info tree -func (s *L1InfoTreeSync) GetInfoByIndex(ctx context.Context, index uint32) (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetInfoByIndex(ctx, index) -} - -// GetL1InfoTreeRootByIndex returns the root of the L1 info tree at the moment the leaf with the given index was added -func (s *L1InfoTreeSync) GetL1InfoTreeRootByIndex(ctx context.Context, index uint32) (types.Root, error) { - if s.processor.isHalted() { - return types.Root{}, sync.ErrInconsistentState - } - return s.processor.l1InfoTree.GetRootByIndex(ctx, index) -} - -// GetLastRollupExitRoot return the last rollup exit root processed -func (s *L1InfoTreeSync) GetLastRollupExitRoot(ctx context.Context) (types.Root, error) { - if s.processor.isHalted() { - return types.Root{}, sync.ErrInconsistentState - } - return s.processor.rollupExitTree.GetLastRoot(nil) -} - -// GetLastL1InfoTreeRoot return the last root and index processed from the L1 Info tree -func (s *L1InfoTreeSync) GetLastL1InfoTreeRoot(ctx context.Context) (types.Root, error) { - if s.processor.isHalted() { - return types.Root{}, sync.ErrInconsistentState - } - return s.processor.l1InfoTree.GetLastRoot(nil) -} - -// GetLastProcessedBlock return the last processed block -func (s *L1InfoTreeSync) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - if s.processor.isHalted() { - return 0, sync.ErrInconsistentState - } - return s.processor.GetLastProcessedBlock(ctx) -} - -func (s *L1InfoTreeSync) GetLocalExitRoot( - ctx context.Context, networkID uint32, rollupExitRoot common.Hash, -) (common.Hash, error) { - if s.processor.isHalted() { - return common.Hash{}, sync.ErrInconsistentState - } - if networkID == 0 { - return common.Hash{}, errors.New("network 0 is not a rollup, and it's not part of the rollup exit tree") - } - - return s.processor.rollupExitTree.GetLeaf(nil, networkID-1, rollupExitRoot) -} - -func (s *L1InfoTreeSync) GetLastVerifiedBatches(rollupID uint32) (*VerifyBatches, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetLastVerifiedBatches(rollupID) -} - -func (s *L1InfoTreeSync) GetFirstVerifiedBatches(rollupID uint32) (*VerifyBatches, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetFirstVerifiedBatches(rollupID) -} - -func (s *L1InfoTreeSync) GetFirstVerifiedBatchesAfterBlock(rollupID uint32, blockNum uint64) (*VerifyBatches, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetFirstVerifiedBatchesAfterBlock(rollupID, blockNum) -} - -func (s *L1InfoTreeSync) GetFirstL1InfoWithRollupExitRoot(rollupExitRoot common.Hash) (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetFirstL1InfoWithRollupExitRoot(rollupExitRoot) -} - -func (s *L1InfoTreeSync) GetLastInfo() (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetLastInfo() -} - -func (s *L1InfoTreeSync) GetFirstInfo() (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetFirstInfo() -} - -func (s *L1InfoTreeSync) GetFirstInfoAfterBlock(blockNum uint64) (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetFirstInfoAfterBlock(blockNum) -} - -func (s *L1InfoTreeSync) GetInfoByGlobalExitRoot(ger common.Hash) (*L1InfoTreeLeaf, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetInfoByGlobalExitRoot(ger) -} - -// GetL1InfoTreeMerkleProofFromIndexToRoot creates a merkle proof for the L1 Info tree -func (s *L1InfoTreeSync) GetL1InfoTreeMerkleProofFromIndexToRoot( - ctx context.Context, index uint32, root common.Hash, -) (types.Proof, error) { - if s.processor.isHalted() { - return types.Proof{}, sync.ErrInconsistentState - } - return s.processor.l1InfoTree.GetProof(ctx, index, root) -} - -// GetInitL1InfoRootMap returns the initial L1 info root map, nil if no root map has been set -func (s *L1InfoTreeSync) GetInitL1InfoRootMap(ctx context.Context) (*L1InfoTreeInitial, error) { - if s.processor.isHalted() { - return nil, sync.ErrInconsistentState - } - return s.processor.GetInitL1InfoRootMap(nil) -} diff --git a/l1infotreesync/l1infotreesync_test.go b/l1infotreesync/l1infotreesync_test.go deleted file mode 100644 index a6c5ef036..000000000 --- a/l1infotreesync/l1infotreesync_test.go +++ /dev/null @@ -1,198 +0,0 @@ -package l1infotreesync - -import ( - "context" - "errors" - "testing" - - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestGetL1InfoTreeMerkleProof(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, _, err := s.GetL1InfoTreeMerkleProof(context.Background(), 0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetRollupExitTreeMerkleProof(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetRollupExitTreeMerkleProof(context.Background(), 0, common.Hash{}) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLatestInfoUntilBlock(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLatestInfoUntilBlock(context.Background(), 0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetInfoByIndex(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetInfoByIndex(context.Background(), 0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetL1InfoTreeRootByIndex(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetL1InfoTreeRootByIndex(context.Background(), 0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLastRollupExitRoot(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLastRollupExitRoot(context.Background()) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLastL1InfoTreeRoot(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLastL1InfoTreeRoot(context.Background()) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLastProcessedBlock(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLastProcessedBlock(context.Background()) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLocalExitRoot(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLocalExitRoot(context.Background(), 0, common.Hash{}) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLastVerifiedBatches(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLastVerifiedBatches(0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetFirstVerifiedBatches(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetFirstVerifiedBatches(0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetFirstVerifiedBatchesAfterBlock(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetFirstVerifiedBatchesAfterBlock(0, 0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetFirstL1InfoWithRollupExitRoot(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetFirstL1InfoWithRollupExitRoot(common.Hash{}) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetLastInfo(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetLastInfo() - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetFirstInfo(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetFirstInfo() - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetFirstInfoAfterBlock(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetFirstInfoAfterBlock(0) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} - -func TestGetL1InfoTreeMerkleProofFromIndexToRoot(t *testing.T) { - s := L1InfoTreeSync{ - processor: &processor{ - halted: true, - }, - } - _, err := s.GetL1InfoTreeMerkleProofFromIndexToRoot(context.Background(), 0, common.Hash{}) - require.Error(t, err) - require.True(t, errors.Is(err, sync.ErrInconsistentState)) -} diff --git a/l1infotreesync/migrations/l1infotreesync0001.sql b/l1infotreesync/migrations/l1infotreesync0001.sql deleted file mode 100644 index 7a6892812..000000000 --- a/l1infotreesync/migrations/l1infotreesync0001.sql +++ /dev/null @@ -1,34 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS block; -DROP TABLE IF EXISTS claim; -DROP TABLE IF EXISTS bridge; - --- +migrate Up -CREATE TABLE block ( - num BIGINT PRIMARY KEY -); - -CREATE TABLE l1info_leaf ( - block_num INTEGER NOT NULL REFERENCES block(num) ON DELETE CASCADE, - block_pos INTEGER NOT NULL, - position INTEGER NOT NULL, - previous_block_hash VARCHAR NOT NULL, - timestamp INTEGER NOT NULL, - mainnet_exit_root VARCHAR NOT NULL, - rollup_exit_root VARCHAR NOT NULL, - global_exit_root VARCHAR NOT NULL UNIQUE, - hash VARCHAR NOT NULL, - PRIMARY KEY (block_num, block_pos) -); - -CREATE TABLE verify_batches ( - block_num INTEGER NOT NULL REFERENCES block(num) ON DELETE CASCADE, - block_pos INTEGER NOT NULL, - rollup_id INTEGER NOT NULL, - batch_num INTEGER NOT NULL, - state_root VARCHAR NOT NULL, - exit_root VARCHAR NOT NULL, - aggregator VARCHAR NOT NULL, - rollup_exit_root VARCHAR NOT NULL, - PRIMARY KEY (block_num, block_pos) -); diff --git a/l1infotreesync/migrations/l1infotreesync0002.sql b/l1infotreesync/migrations/l1infotreesync0002.sql deleted file mode 100644 index d1f09481b..000000000 --- a/l1infotreesync/migrations/l1infotreesync0002.sql +++ /dev/null @@ -1,14 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS l1info_initial; - --- +migrate Up - -CREATE TABLE l1info_initial ( - -- single_row_id prevent to have more than 1 row in this table - single_row_id INTEGER check(single_row_id=1) NOT NULL DEFAULT 1, - block_num INTEGER NOT NULL REFERENCES block(num) ON DELETE CASCADE, - leaf_count INTEGER NOT NULL, - l1_info_root VARCHAR NOT NULL, - PRIMARY KEY (single_row_id) -); - diff --git a/l1infotreesync/migrations/l1infotreesync0003.sql b/l1infotreesync/migrations/l1infotreesync0003.sql deleted file mode 100644 index 0453081d7..000000000 --- a/l1infotreesync/migrations/l1infotreesync0003.sql +++ /dev/null @@ -1,5 +0,0 @@ --- +migrate Down -ALTER TABLE block DROP COLUMN hash; - --- +migrate Up -ALTER TABLE block ADD COLUMN hash VARCHAR; \ No newline at end of file diff --git a/l1infotreesync/migrations/migrations.go b/l1infotreesync/migrations/migrations.go deleted file mode 100644 index 6de760147..000000000 --- a/l1infotreesync/migrations/migrations.go +++ /dev/null @@ -1,53 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" - treeMigrations "github.com/0xPolygon/cdk/tree/migrations" -) - -const ( - RollupExitTreePrefix = "rollup_exit_" - L1InfoTreePrefix = "l1_info_" -) - -//go:embed l1infotreesync0001.sql -var mig001 string - -//go:embed l1infotreesync0002.sql -var mig002 string - -//go:embed l1infotreesync0003.sql -var mig003 string - -func RunMigrations(dbPath string) error { - migrations := []types.Migration{ - { - ID: "l1infotreesync0001", - SQL: mig001, - }, - { - ID: "l1infotreesync0002", - SQL: mig002, - }, - { - ID: "l1infotreesync0003", - SQL: mig003, - }, - } - for _, tm := range treeMigrations.Migrations { - migrations = append(migrations, types.Migration{ - ID: tm.ID, - SQL: tm.SQL, - Prefix: RollupExitTreePrefix, - }) - migrations = append(migrations, types.Migration{ - ID: tm.ID, - SQL: tm.SQL, - Prefix: L1InfoTreePrefix, - }) - } - return db.RunMigrations(dbPath, migrations) -} diff --git a/l1infotreesync/mocks/mock_eth_clienter.go b/l1infotreesync/mocks/mock_eth_clienter.go deleted file mode 100644 index 72d67a978..000000000 --- a/l1infotreesync/mocks/mock_eth_clienter.go +++ /dev/null @@ -1,1086 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - big "math/big" - - common "github.com/ethereum/go-ethereum/common" - - ethereum "github.com/ethereum/go-ethereum" - - mock "github.com/stretchr/testify/mock" - - types "github.com/ethereum/go-ethereum/core/types" -) - -// EthClienter is an autogenerated mock type for the EthClienter type -type EthClienter struct { - mock.Mock -} - -type EthClienter_Expecter struct { - mock *mock.Mock -} - -func (_m *EthClienter) EXPECT() *EthClienter_Expecter { - return &EthClienter_Expecter{mock: &_m.Mock} -} - -// BlockByHash provides a mock function with given fields: ctx, hash -func (_m *EthClienter) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for BlockByHash") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Block, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Block); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByHash' -type EthClienter_BlockByHash_Call struct { - *mock.Call -} - -// BlockByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *EthClienter_Expecter) BlockByHash(ctx interface{}, hash interface{}) *EthClienter_BlockByHash_Call { - return &EthClienter_BlockByHash_Call{Call: _e.mock.On("BlockByHash", ctx, hash)} -} - -func (_c *EthClienter_BlockByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *EthClienter_BlockByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_BlockByHash_Call) Return(_a0 *types.Block, _a1 error) *EthClienter_BlockByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Block, error)) *EthClienter_BlockByHash_Call { - _c.Call.Return(run) - return _c -} - -// BlockByNumber provides a mock function with given fields: ctx, number -func (_m *EthClienter) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for BlockByNumber") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Block, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Block); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByNumber' -type EthClienter_BlockByNumber_Call struct { - *mock.Call -} - -// BlockByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *EthClienter_Expecter) BlockByNumber(ctx interface{}, number interface{}) *EthClienter_BlockByNumber_Call { - return &EthClienter_BlockByNumber_Call{Call: _e.mock.On("BlockByNumber", ctx, number)} -} - -func (_c *EthClienter_BlockByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *EthClienter_BlockByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_BlockByNumber_Call) Return(_a0 *types.Block, _a1 error) *EthClienter_BlockByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Block, error)) *EthClienter_BlockByNumber_Call { - _c.Call.Return(run) - return _c -} - -// BlockNumber provides a mock function with given fields: ctx -func (_m *EthClienter) BlockNumber(ctx context.Context) (uint64, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for BlockNumber") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_BlockNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockNumber' -type EthClienter_BlockNumber_Call struct { - *mock.Call -} - -// BlockNumber is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) BlockNumber(ctx interface{}) *EthClienter_BlockNumber_Call { - return &EthClienter_BlockNumber_Call{Call: _e.mock.On("BlockNumber", ctx)} -} - -func (_c *EthClienter_BlockNumber_Call) Run(run func(ctx context.Context)) *EthClienter_BlockNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_BlockNumber_Call) Return(_a0 uint64, _a1 error) *EthClienter_BlockNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_BlockNumber_Call) RunAndReturn(run func(context.Context) (uint64, error)) *EthClienter_BlockNumber_Call { - _c.Call.Return(run) - return _c -} - -// CallContract provides a mock function with given fields: ctx, call, blockNumber -func (_m *EthClienter) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, call, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CallContract") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { - return rf(ctx, call, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { - r0 = rf(ctx, call, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { - r1 = rf(ctx, call, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_CallContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CallContract' -type EthClienter_CallContract_Call struct { - *mock.Call -} - -// CallContract is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -// - blockNumber *big.Int -func (_e *EthClienter_Expecter) CallContract(ctx interface{}, call interface{}, blockNumber interface{}) *EthClienter_CallContract_Call { - return &EthClienter_CallContract_Call{Call: _e.mock.On("CallContract", ctx, call, blockNumber)} -} - -func (_c *EthClienter_CallContract_Call) Run(run func(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int)) *EthClienter_CallContract_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg), args[2].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_CallContract_Call) Return(_a0 []byte, _a1 error) *EthClienter_CallContract_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_CallContract_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)) *EthClienter_CallContract_Call { - _c.Call.Return(run) - return _c -} - -// CodeAt provides a mock function with given fields: ctx, contract, blockNumber -func (_m *EthClienter) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, contract, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { - return rf(ctx, contract, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { - r0 = rf(ctx, contract, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { - r1 = rf(ctx, contract, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_CodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CodeAt' -type EthClienter_CodeAt_Call struct { - *mock.Call -} - -// CodeAt is a helper method to define mock.On call -// - ctx context.Context -// - contract common.Address -// - blockNumber *big.Int -func (_e *EthClienter_Expecter) CodeAt(ctx interface{}, contract interface{}, blockNumber interface{}) *EthClienter_CodeAt_Call { - return &EthClienter_CodeAt_Call{Call: _e.mock.On("CodeAt", ctx, contract, blockNumber)} -} - -func (_c *EthClienter_CodeAt_Call) Run(run func(ctx context.Context, contract common.Address, blockNumber *big.Int)) *EthClienter_CodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address), args[2].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_CodeAt_Call) Return(_a0 []byte, _a1 error) *EthClienter_CodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_CodeAt_Call) RunAndReturn(run func(context.Context, common.Address, *big.Int) ([]byte, error)) *EthClienter_CodeAt_Call { - _c.Call.Return(run) - return _c -} - -// EstimateGas provides a mock function with given fields: ctx, call -func (_m *EthClienter) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - ret := _m.Called(ctx, call) - - if len(ret) == 0 { - panic("no return value specified for EstimateGas") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { - return rf(ctx, call) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { - r0 = rf(ctx, call) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { - r1 = rf(ctx, call) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_EstimateGas_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EstimateGas' -type EthClienter_EstimateGas_Call struct { - *mock.Call -} - -// EstimateGas is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -func (_e *EthClienter_Expecter) EstimateGas(ctx interface{}, call interface{}) *EthClienter_EstimateGas_Call { - return &EthClienter_EstimateGas_Call{Call: _e.mock.On("EstimateGas", ctx, call)} -} - -func (_c *EthClienter_EstimateGas_Call) Run(run func(ctx context.Context, call ethereum.CallMsg)) *EthClienter_EstimateGas_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg)) - }) - return _c -} - -func (_c *EthClienter_EstimateGas_Call) Return(_a0 uint64, _a1 error) *EthClienter_EstimateGas_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_EstimateGas_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg) (uint64, error)) *EthClienter_EstimateGas_Call { - _c.Call.Return(run) - return _c -} - -// FilterLogs provides a mock function with given fields: ctx, q -func (_m *EthClienter) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(ctx, q) - - if len(ret) == 0 { - panic("no return value specified for FilterLogs") - } - - var r0 []types.Log - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(ctx, q) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(ctx, q) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Log) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { - r1 = rf(ctx, q) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_FilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FilterLogs' -type EthClienter_FilterLogs_Call struct { - *mock.Call -} - -// FilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -func (_e *EthClienter_Expecter) FilterLogs(ctx interface{}, q interface{}) *EthClienter_FilterLogs_Call { - return &EthClienter_FilterLogs_Call{Call: _e.mock.On("FilterLogs", ctx, q)} -} - -func (_c *EthClienter_FilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery)) *EthClienter_FilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery)) - }) - return _c -} - -func (_c *EthClienter_FilterLogs_Call) Return(_a0 []types.Log, _a1 error) *EthClienter_FilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_FilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery) ([]types.Log, error)) *EthClienter_FilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByHash provides a mock function with given fields: ctx, hash -func (_m *EthClienter) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for HeaderByHash") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Header, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Header); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_HeaderByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByHash' -type EthClienter_HeaderByHash_Call struct { - *mock.Call -} - -// HeaderByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *EthClienter_Expecter) HeaderByHash(ctx interface{}, hash interface{}) *EthClienter_HeaderByHash_Call { - return &EthClienter_HeaderByHash_Call{Call: _e.mock.On("HeaderByHash", ctx, hash)} -} - -func (_c *EthClienter_HeaderByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *EthClienter_HeaderByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_HeaderByHash_Call) Return(_a0 *types.Header, _a1 error) *EthClienter_HeaderByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_HeaderByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Header, error)) *EthClienter_HeaderByHash_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByNumber provides a mock function with given fields: ctx, number -func (_m *EthClienter) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for HeaderByNumber") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_HeaderByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByNumber' -type EthClienter_HeaderByNumber_Call struct { - *mock.Call -} - -// HeaderByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *EthClienter_Expecter) HeaderByNumber(ctx interface{}, number interface{}) *EthClienter_HeaderByNumber_Call { - return &EthClienter_HeaderByNumber_Call{Call: _e.mock.On("HeaderByNumber", ctx, number)} -} - -func (_c *EthClienter_HeaderByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *EthClienter_HeaderByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *EthClienter_HeaderByNumber_Call) Return(_a0 *types.Header, _a1 error) *EthClienter_HeaderByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_HeaderByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Header, error)) *EthClienter_HeaderByNumber_Call { - _c.Call.Return(run) - return _c -} - -// PendingCodeAt provides a mock function with given fields: ctx, account -func (_m *EthClienter) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingCodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { - r0 = rf(ctx, account) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_PendingCodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingCodeAt' -type EthClienter_PendingCodeAt_Call struct { - *mock.Call -} - -// PendingCodeAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *EthClienter_Expecter) PendingCodeAt(ctx interface{}, account interface{}) *EthClienter_PendingCodeAt_Call { - return &EthClienter_PendingCodeAt_Call{Call: _e.mock.On("PendingCodeAt", ctx, account)} -} - -func (_c *EthClienter_PendingCodeAt_Call) Run(run func(ctx context.Context, account common.Address)) *EthClienter_PendingCodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *EthClienter_PendingCodeAt_Call) Return(_a0 []byte, _a1 error) *EthClienter_PendingCodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_PendingCodeAt_Call) RunAndReturn(run func(context.Context, common.Address) ([]byte, error)) *EthClienter_PendingCodeAt_Call { - _c.Call.Return(run) - return _c -} - -// PendingNonceAt provides a mock function with given fields: ctx, account -func (_m *EthClienter) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingNonceAt") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { - r0 = rf(ctx, account) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_PendingNonceAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingNonceAt' -type EthClienter_PendingNonceAt_Call struct { - *mock.Call -} - -// PendingNonceAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *EthClienter_Expecter) PendingNonceAt(ctx interface{}, account interface{}) *EthClienter_PendingNonceAt_Call { - return &EthClienter_PendingNonceAt_Call{Call: _e.mock.On("PendingNonceAt", ctx, account)} -} - -func (_c *EthClienter_PendingNonceAt_Call) Run(run func(ctx context.Context, account common.Address)) *EthClienter_PendingNonceAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *EthClienter_PendingNonceAt_Call) Return(_a0 uint64, _a1 error) *EthClienter_PendingNonceAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_PendingNonceAt_Call) RunAndReturn(run func(context.Context, common.Address) (uint64, error)) *EthClienter_PendingNonceAt_Call { - _c.Call.Return(run) - return _c -} - -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *EthClienter) SendTransaction(ctx context.Context, tx *types.Transaction) error { - ret := _m.Called(ctx, tx) - - if len(ret) == 0 { - panic("no return value specified for SendTransaction") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { - r0 = rf(ctx, tx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// EthClienter_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' -type EthClienter_SendTransaction_Call struct { - *mock.Call -} - -// SendTransaction is a helper method to define mock.On call -// - ctx context.Context -// - tx *types.Transaction -func (_e *EthClienter_Expecter) SendTransaction(ctx interface{}, tx interface{}) *EthClienter_SendTransaction_Call { - return &EthClienter_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} -} - -func (_c *EthClienter_SendTransaction_Call) Run(run func(ctx context.Context, tx *types.Transaction)) *EthClienter_SendTransaction_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*types.Transaction)) - }) - return _c -} - -func (_c *EthClienter_SendTransaction_Call) Return(_a0 error) *EthClienter_SendTransaction_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *EthClienter_SendTransaction_Call) RunAndReturn(run func(context.Context, *types.Transaction) error) *EthClienter_SendTransaction_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeFilterLogs provides a mock function with given fields: ctx, q, ch -func (_m *EthClienter) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - ret := _m.Called(ctx, q, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeFilterLogs") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { - return rf(ctx, q, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { - r0 = rf(ctx, q, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { - r1 = rf(ctx, q, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SubscribeFilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeFilterLogs' -type EthClienter_SubscribeFilterLogs_Call struct { - *mock.Call -} - -// SubscribeFilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -// - ch chan<- types.Log -func (_e *EthClienter_Expecter) SubscribeFilterLogs(ctx interface{}, q interface{}, ch interface{}) *EthClienter_SubscribeFilterLogs_Call { - return &EthClienter_SubscribeFilterLogs_Call{Call: _e.mock.On("SubscribeFilterLogs", ctx, q, ch)} -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log)) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery), args[2].(chan<- types.Log)) - }) - return _c -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) Return(_a0 ethereum.Subscription, _a1 error) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SubscribeFilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)) *EthClienter_SubscribeFilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeNewHead provides a mock function with given fields: ctx, ch -func (_m *EthClienter) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { - ret := _m.Called(ctx, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeNewHead") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)); ok { - return rf(ctx, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) ethereum.Subscription); ok { - r0 = rf(ctx, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, chan<- *types.Header) error); ok { - r1 = rf(ctx, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SubscribeNewHead_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeNewHead' -type EthClienter_SubscribeNewHead_Call struct { - *mock.Call -} - -// SubscribeNewHead is a helper method to define mock.On call -// - ctx context.Context -// - ch chan<- *types.Header -func (_e *EthClienter_Expecter) SubscribeNewHead(ctx interface{}, ch interface{}) *EthClienter_SubscribeNewHead_Call { - return &EthClienter_SubscribeNewHead_Call{Call: _e.mock.On("SubscribeNewHead", ctx, ch)} -} - -func (_c *EthClienter_SubscribeNewHead_Call) Run(run func(ctx context.Context, ch chan<- *types.Header)) *EthClienter_SubscribeNewHead_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(chan<- *types.Header)) - }) - return _c -} - -func (_c *EthClienter_SubscribeNewHead_Call) Return(_a0 ethereum.Subscription, _a1 error) *EthClienter_SubscribeNewHead_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SubscribeNewHead_Call) RunAndReturn(run func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)) *EthClienter_SubscribeNewHead_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasPrice provides a mock function with given fields: ctx -func (_m *EthClienter) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasPrice") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SuggestGasPrice_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasPrice' -type EthClienter_SuggestGasPrice_Call struct { - *mock.Call -} - -// SuggestGasPrice is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) SuggestGasPrice(ctx interface{}) *EthClienter_SuggestGasPrice_Call { - return &EthClienter_SuggestGasPrice_Call{Call: _e.mock.On("SuggestGasPrice", ctx)} -} - -func (_c *EthClienter_SuggestGasPrice_Call) Run(run func(ctx context.Context)) *EthClienter_SuggestGasPrice_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_SuggestGasPrice_Call) Return(_a0 *big.Int, _a1 error) *EthClienter_SuggestGasPrice_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SuggestGasPrice_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *EthClienter_SuggestGasPrice_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasTipCap provides a mock function with given fields: ctx -func (_m *EthClienter) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasTipCap") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_SuggestGasTipCap_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasTipCap' -type EthClienter_SuggestGasTipCap_Call struct { - *mock.Call -} - -// SuggestGasTipCap is a helper method to define mock.On call -// - ctx context.Context -func (_e *EthClienter_Expecter) SuggestGasTipCap(ctx interface{}) *EthClienter_SuggestGasTipCap_Call { - return &EthClienter_SuggestGasTipCap_Call{Call: _e.mock.On("SuggestGasTipCap", ctx)} -} - -func (_c *EthClienter_SuggestGasTipCap_Call) Run(run func(ctx context.Context)) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *EthClienter_SuggestGasTipCap_Call) Return(_a0 *big.Int, _a1 error) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_SuggestGasTipCap_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *EthClienter_SuggestGasTipCap_Call { - _c.Call.Return(run) - return _c -} - -// TransactionCount provides a mock function with given fields: ctx, blockHash -func (_m *EthClienter) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { - ret := _m.Called(ctx, blockHash) - - if len(ret) == 0 { - panic("no return value specified for TransactionCount") - } - - var r0 uint - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (uint, error)); ok { - return rf(ctx, blockHash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) uint); ok { - r0 = rf(ctx, blockHash) - } else { - r0 = ret.Get(0).(uint) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, blockHash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_TransactionCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionCount' -type EthClienter_TransactionCount_Call struct { - *mock.Call -} - -// TransactionCount is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -func (_e *EthClienter_Expecter) TransactionCount(ctx interface{}, blockHash interface{}) *EthClienter_TransactionCount_Call { - return &EthClienter_TransactionCount_Call{Call: _e.mock.On("TransactionCount", ctx, blockHash)} -} - -func (_c *EthClienter_TransactionCount_Call) Run(run func(ctx context.Context, blockHash common.Hash)) *EthClienter_TransactionCount_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClienter_TransactionCount_Call) Return(_a0 uint, _a1 error) *EthClienter_TransactionCount_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_TransactionCount_Call) RunAndReturn(run func(context.Context, common.Hash) (uint, error)) *EthClienter_TransactionCount_Call { - _c.Call.Return(run) - return _c -} - -// TransactionInBlock provides a mock function with given fields: ctx, blockHash, index -func (_m *EthClienter) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { - ret := _m.Called(ctx, blockHash, index) - - if len(ret) == 0 { - panic("no return value specified for TransactionInBlock") - } - - var r0 *types.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) (*types.Transaction, error)); ok { - return rf(ctx, blockHash, index) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) *types.Transaction); ok { - r0 = rf(ctx, blockHash, index) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash, uint) error); ok { - r1 = rf(ctx, blockHash, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClienter_TransactionInBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionInBlock' -type EthClienter_TransactionInBlock_Call struct { - *mock.Call -} - -// TransactionInBlock is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -// - index uint -func (_e *EthClienter_Expecter) TransactionInBlock(ctx interface{}, blockHash interface{}, index interface{}) *EthClienter_TransactionInBlock_Call { - return &EthClienter_TransactionInBlock_Call{Call: _e.mock.On("TransactionInBlock", ctx, blockHash, index)} -} - -func (_c *EthClienter_TransactionInBlock_Call) Run(run func(ctx context.Context, blockHash common.Hash, index uint)) *EthClienter_TransactionInBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash), args[2].(uint)) - }) - return _c -} - -func (_c *EthClienter_TransactionInBlock_Call) Return(_a0 *types.Transaction, _a1 error) *EthClienter_TransactionInBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClienter_TransactionInBlock_Call) RunAndReturn(run func(context.Context, common.Hash, uint) (*types.Transaction, error)) *EthClienter_TransactionInBlock_Call { - _c.Call.Return(run) - return _c -} - -// NewEthClienter creates a new instance of EthClienter. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEthClienter(t interface { - mock.TestingT - Cleanup(func()) -}) *EthClienter { - mock := &EthClienter{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/l1infotreesync/mocks/mock_reorg_detector.go b/l1infotreesync/mocks/mock_reorg_detector.go deleted file mode 100644 index b49281c83..000000000 --- a/l1infotreesync/mocks/mock_reorg_detector.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - - common "github.com/ethereum/go-ethereum/common" - - mock "github.com/stretchr/testify/mock" - - reorgdetector "github.com/0xPolygon/cdk/reorgdetector" -) - -// ReorgDetectorMock is an autogenerated mock type for the ReorgDetector type -type ReorgDetectorMock struct { - mock.Mock -} - -type ReorgDetectorMock_Expecter struct { - mock *mock.Mock -} - -func (_m *ReorgDetectorMock) EXPECT() *ReorgDetectorMock_Expecter { - return &ReorgDetectorMock_Expecter{mock: &_m.Mock} -} - -// AddBlockToTrack provides a mock function with given fields: ctx, id, blockNum, blockHash -func (_m *ReorgDetectorMock) AddBlockToTrack(ctx context.Context, id string, blockNum uint64, blockHash common.Hash) error { - ret := _m.Called(ctx, id, blockNum, blockHash) - - if len(ret) == 0 { - panic("no return value specified for AddBlockToTrack") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, common.Hash) error); ok { - r0 = rf(ctx, id, blockNum, blockHash) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReorgDetectorMock_AddBlockToTrack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlockToTrack' -type ReorgDetectorMock_AddBlockToTrack_Call struct { - *mock.Call -} - -// AddBlockToTrack is a helper method to define mock.On call -// - ctx context.Context -// - id string -// - blockNum uint64 -// - blockHash common.Hash -func (_e *ReorgDetectorMock_Expecter) AddBlockToTrack(ctx interface{}, id interface{}, blockNum interface{}, blockHash interface{}) *ReorgDetectorMock_AddBlockToTrack_Call { - return &ReorgDetectorMock_AddBlockToTrack_Call{Call: _e.mock.On("AddBlockToTrack", ctx, id, blockNum, blockHash)} -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) Run(run func(ctx context.Context, id string, blockNum uint64, blockHash common.Hash)) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(string), args[2].(uint64), args[3].(common.Hash)) - }) - return _c -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) Return(_a0 error) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) RunAndReturn(run func(context.Context, string, uint64, common.Hash) error) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Return(run) - return _c -} - -// Subscribe provides a mock function with given fields: id -func (_m *ReorgDetectorMock) Subscribe(id string) (*reorgdetector.Subscription, error) { - ret := _m.Called(id) - - if len(ret) == 0 { - panic("no return value specified for Subscribe") - } - - var r0 *reorgdetector.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(string) (*reorgdetector.Subscription, error)); ok { - return rf(id) - } - if rf, ok := ret.Get(0).(func(string) *reorgdetector.Subscription); ok { - r0 = rf(id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*reorgdetector.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ReorgDetectorMock_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' -type ReorgDetectorMock_Subscribe_Call struct { - *mock.Call -} - -// Subscribe is a helper method to define mock.On call -// - id string -func (_e *ReorgDetectorMock_Expecter) Subscribe(id interface{}) *ReorgDetectorMock_Subscribe_Call { - return &ReorgDetectorMock_Subscribe_Call{Call: _e.mock.On("Subscribe", id)} -} - -func (_c *ReorgDetectorMock_Subscribe_Call) Run(run func(id string)) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(string)) - }) - return _c -} - -func (_c *ReorgDetectorMock_Subscribe_Call) Return(_a0 *reorgdetector.Subscription, _a1 error) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ReorgDetectorMock_Subscribe_Call) RunAndReturn(run func(string) (*reorgdetector.Subscription, error)) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Return(run) - return _c -} - -// NewReorgDetectorMock creates a new instance of ReorgDetectorMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReorgDetectorMock(t interface { - mock.TestingT - Cleanup(func()) -}) *ReorgDetectorMock { - mock := &ReorgDetectorMock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/l1infotreesync/processor.go b/l1infotreesync/processor.go deleted file mode 100644 index e0cc19599..000000000 --- a/l1infotreesync/processor.go +++ /dev/null @@ -1,489 +0,0 @@ -package l1infotreesync - -import ( - "context" - "database/sql" - "encoding/binary" - "errors" - "fmt" - mutex "sync" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/l1infotreesync/migrations" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/0xPolygon/cdk/tree" - treeTypes "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/iden3/go-iden3-crypto/keccak256" - "github.com/russross/meddler" - "golang.org/x/crypto/sha3" -) - -var ( - ErrBlockNotProcessed = errors.New("given block(s) have not been processed yet") - ErrNoBlock0 = errors.New("blockNum must be greater than 0") -) - -type processor struct { - db *sql.DB - l1InfoTree *tree.AppendOnlyTree - rollupExitTree *tree.UpdatableTree - mu mutex.RWMutex - halted bool - haltedReason string - log *log.Logger -} - -// UpdateL1InfoTree representation of the UpdateL1InfoTree event -type UpdateL1InfoTree struct { - BlockPosition uint64 - MainnetExitRoot common.Hash - RollupExitRoot common.Hash - ParentHash common.Hash - Timestamp uint64 -} - -type UpdateL1InfoTreeV2 struct { - CurrentL1InfoRoot common.Hash - LeafCount uint32 - Blockhash common.Hash - MinTimestamp uint64 -} - -// VerifyBatches representation of the VerifyBatches and VerifyBatchesTrustedAggregator events -type VerifyBatches struct { - BlockNumber uint64 `meddler:"block_num"` - BlockPosition uint64 `meddler:"block_pos"` - RollupID uint32 `meddler:"rollup_id"` - NumBatch uint64 `meddler:"batch_num"` - StateRoot common.Hash `meddler:"state_root,hash"` - ExitRoot common.Hash `meddler:"exit_root,hash"` - Aggregator common.Address `meddler:"aggregator,address"` - - // Not provided by downloader - RollupExitRoot common.Hash `meddler:"rollup_exit_root,hash"` -} - -func (v *VerifyBatches) String() string { - return fmt.Sprintf("BlockNumber: %d, BlockPosition: %d, RollupID: %d, NumBatch: %d, StateRoot: %s, "+ - "ExitRoot: %s, Aggregator: %s, RollupExitRoot: %s", - v.BlockNumber, v.BlockPosition, v.RollupID, v.NumBatch, v.StateRoot.String(), - v.ExitRoot.String(), v.Aggregator.String(), v.RollupExitRoot.String()) -} - -type InitL1InfoRootMap struct { - LeafCount uint32 - CurrentL1InfoRoot common.Hash -} - -func (i *InitL1InfoRootMap) String() string { - return fmt.Sprintf("LeafCount: %d, CurrentL1InfoRoot: %s", i.LeafCount, i.CurrentL1InfoRoot.String()) -} - -type Event struct { - UpdateL1InfoTree *UpdateL1InfoTree - UpdateL1InfoTreeV2 *UpdateL1InfoTreeV2 - VerifyBatches *VerifyBatches - InitL1InfoRootMap *InitL1InfoRootMap -} - -// L1InfoTreeLeaf representation of a leaf of the L1 Info tree -type L1InfoTreeLeaf struct { - BlockNumber uint64 `meddler:"block_num"` - BlockPosition uint64 `meddler:"block_pos"` - L1InfoTreeIndex uint32 `meddler:"position"` - PreviousBlockHash common.Hash `meddler:"previous_block_hash,hash"` - Timestamp uint64 `meddler:"timestamp"` - MainnetExitRoot common.Hash `meddler:"mainnet_exit_root,hash"` - RollupExitRoot common.Hash `meddler:"rollup_exit_root,hash"` - GlobalExitRoot common.Hash `meddler:"global_exit_root,hash"` - Hash common.Hash `meddler:"hash,hash"` -} - -func (l *L1InfoTreeLeaf) String() string { - return fmt.Sprintf("BlockNumber: %d, BlockPosition: %d, L1InfoTreeIndex: %d, PreviousBlockHash: %s, "+ - "Timestamp: %d, MainnetExitRoot: %s, RollupExitRoot: %s, GlobalExitRoot: %s, Hash: %s", - l.BlockNumber, l.BlockPosition, l.L1InfoTreeIndex, l.PreviousBlockHash.String(), - l.Timestamp, l.MainnetExitRoot.String(), l.RollupExitRoot.String(), l.GlobalExitRoot.String(), l.Hash.String()) -} - -// L1InfoTreeInitial representation of the initial info of the L1 Info tree for this rollup -type L1InfoTreeInitial struct { - BlockNumber uint64 `meddler:"block_num"` - LeafCount uint32 `meddler:"leaf_count"` - L1InfoRoot common.Hash `meddler:"l1_info_root,hash"` -} - -func (l *L1InfoTreeInitial) String() string { - return fmt.Sprintf("BlockNumber: %d, LeafCount: %d, L1InfoRoot: %s", l.BlockNumber, l.LeafCount, l.L1InfoRoot.String()) -} - -// Hash as expected by the tree -func (l *L1InfoTreeLeaf) hash() common.Hash { - var res [treeTypes.DefaultHeight]byte - t := make([]byte, 8) //nolint:mnd - binary.BigEndian.PutUint64(t, l.Timestamp) - copy(res[:], keccak256.Hash(l.globalExitRoot().Bytes(), l.PreviousBlockHash.Bytes(), t)) - return res -} - -// GlobalExitRoot returns the GER -func (l *L1InfoTreeLeaf) globalExitRoot() common.Hash { - var gerBytes [treeTypes.DefaultHeight]byte - hasher := sha3.NewLegacyKeccak256() - hasher.Write(l.MainnetExitRoot[:]) - hasher.Write(l.RollupExitRoot[:]) - copy(gerBytes[:], hasher.Sum(nil)) - - return gerBytes -} - -func newProcessor(dbPath string) (*processor, error) { - err := migrations.RunMigrations(dbPath) - if err != nil { - return nil, err - } - db, err := db.NewSQLiteDB(dbPath) - if err != nil { - return nil, err - } - return &processor{ - db: db, - l1InfoTree: tree.NewAppendOnlyTree(db, migrations.L1InfoTreePrefix), - rollupExitTree: tree.NewUpdatableTree(db, migrations.RollupExitTreePrefix), - log: log.WithFields("processor", "l1infotreesync"), - }, nil -} - -// GetL1InfoTreeMerkleProof creates a merkle proof for the L1 Info tree -func (p *processor) GetL1InfoTreeMerkleProof( - ctx context.Context, index uint32, -) (treeTypes.Proof, treeTypes.Root, error) { - root, err := p.l1InfoTree.GetRootByIndex(ctx, index) - if err != nil { - return treeTypes.Proof{}, treeTypes.Root{}, err - } - proof, err := p.l1InfoTree.GetProof(ctx, root.Index, root.Hash) - return proof, root, err -} - -// GetLatestInfoUntilBlock returns the most recent L1InfoTreeLeaf that occurred before or at blockNum. -// If the blockNum has not been processed yet the error ErrBlockNotProcessed will be returned -func (p *processor) GetLatestInfoUntilBlock(ctx context.Context, blockNum uint64) (*L1InfoTreeLeaf, error) { - if blockNum == 0 { - return nil, ErrNoBlock0 - } - tx, err := p.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) - if err != nil { - return nil, err - } - defer func() { - if err := tx.Rollback(); err != nil { - p.log.Warnf("error rolling back tx: %v", err) - } - }() - - lpb, err := p.getLastProcessedBlockWithTx(tx) - if err != nil { - return nil, err - } - if lpb < blockNum { - return nil, ErrBlockNotProcessed - } - - info := &L1InfoTreeLeaf{} - err = meddler.QueryRow( - tx, info, - `SELECT * FROM l1info_leaf ORDER BY block_num DESC, block_pos DESC LIMIT 1;`, - ) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, db.ErrNotFound - } - return nil, err - } - return info, nil -} - -// GetInfoByIndex returns the value of a leaf (not the hash) of the L1 info tree -func (p *processor) GetInfoByIndex(ctx context.Context, index uint32) (*L1InfoTreeLeaf, error) { - return p.getInfoByIndexWithTx(p.db, index) -} - -func (p *processor) getInfoByIndexWithTx(tx db.DBer, index uint32) (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - return info, meddler.QueryRow( - tx, info, - `SELECT * FROM l1info_leaf WHERE position = $1;`, index, - ) -} - -// GetLastProcessedBlock returns the last processed block -func (p *processor) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - return p.getLastProcessedBlockWithTx(p.db) -} - -func (p *processor) getLastProcessedBlockWithTx(tx db.Querier) (uint64, error) { - var lastProcessedBlock uint64 - row := tx.QueryRow("SELECT num FROM BLOCK ORDER BY num DESC LIMIT 1;") - err := row.Scan(&lastProcessedBlock) - if errors.Is(err, sql.ErrNoRows) { - return 0, nil - } - return lastProcessedBlock, err -} - -// Reorg triggers a purge and reset process on the processor to leaf it on a state -// as if the last block processed was firstReorgedBlock-1 -func (p *processor) Reorg(ctx context.Context, firstReorgedBlock uint64) error { - p.log.Infof("reorging to block %d", firstReorgedBlock) - - tx, err := db.NewTx(ctx, p.db) - if err != nil { - return err - } - shouldRollback := true - defer func() { - if shouldRollback { - if errRllbck := tx.Rollback(); errRllbck != nil { - p.log.Errorf("error while rolling back tx %v", errRllbck) - } - } - }() - - res, err := tx.Exec(`DELETE FROM block WHERE num >= $1;`, firstReorgedBlock) - if err != nil { - return err - } - - if err = p.l1InfoTree.Reorg(tx, firstReorgedBlock); err != nil { - return err - } - - if err = p.rollupExitTree.Reorg(tx, firstReorgedBlock); err != nil { - return err - } - rowsAffected, err := res.RowsAffected() - if err != nil { - return err - } - - if err := tx.Commit(); err != nil { - return err - } - - p.log.Infof("reorged to block %d, %d rows affected", firstReorgedBlock, rowsAffected) - - shouldRollback = false - - sync.UnhaltIfAffectedRows(&p.halted, &p.haltedReason, &p.mu, rowsAffected) - return nil -} - -// ProcessBlock process the events of the block to build the rollup exit tree and the l1 info tree -// and updates the last processed block (can be called without events for that purpose) -func (p *processor) ProcessBlock(ctx context.Context, block sync.Block) error { - if p.isHalted() { - p.log.Errorf("processor is halted due to: %s", p.haltedReason) - return sync.ErrInconsistentState - } - tx, err := db.NewTx(ctx, p.db) - if err != nil { - return err - } - p.log.Debugf("init block processing for block %d", block.Num) - shouldRollback := true - defer func() { - if shouldRollback { - p.log.Debugf("rolling back block processing for block %d", block.Num) - if errRllbck := tx.Rollback(); errRllbck != nil { - p.log.Errorf("error while rolling back tx %v", errRllbck) - } - } - }() - - if _, err := tx.Exec(`INSERT INTO block (num, hash) VALUES ($1, $2)`, block.Num, block.Hash.String()); err != nil { - return fmt.Errorf("insert Block. err: %w", err) - } - - var initialL1InfoIndex uint32 - var l1InfoLeavesAdded uint32 - lastIndex, err := p.getLastIndex(tx) - - switch { - case errors.Is(err, db.ErrNotFound): - initialL1InfoIndex = 0 - case err != nil: - return fmt.Errorf("getLastIndex err: %w", err) - default: - initialL1InfoIndex = lastIndex + 1 - } - - for _, e := range block.Events { - event, ok := e.(Event) - if !ok { - return errors.New("failed to convert from sync.Block.Event into Event") - } - if event.UpdateL1InfoTree != nil { - index := initialL1InfoIndex + l1InfoLeavesAdded - info := &L1InfoTreeLeaf{ - BlockNumber: block.Num, - BlockPosition: event.UpdateL1InfoTree.BlockPosition, - L1InfoTreeIndex: index, - PreviousBlockHash: event.UpdateL1InfoTree.ParentHash, - Timestamp: event.UpdateL1InfoTree.Timestamp, - MainnetExitRoot: event.UpdateL1InfoTree.MainnetExitRoot, - RollupExitRoot: event.UpdateL1InfoTree.RollupExitRoot, - } - info.GlobalExitRoot = info.globalExitRoot() - info.Hash = info.hash() - if err = meddler.Insert(tx, "l1info_leaf", info); err != nil { - return fmt.Errorf("insert l1info_leaf %s. err: %w", info.String(), err) - } - - err = p.l1InfoTree.AddLeaf(tx, info.BlockNumber, info.BlockPosition, treeTypes.Leaf{ - Index: info.L1InfoTreeIndex, - Hash: info.Hash, - }) - if err != nil { - return fmt.Errorf("AddLeaf(%s). err: %w", info.String(), err) - } - p.log.Infof("inserted L1InfoTreeLeaf %s", info.String()) - l1InfoLeavesAdded++ - } - if event.UpdateL1InfoTreeV2 != nil { - p.log.Infof("handle UpdateL1InfoTreeV2 event. Block: %d, block hash: %s. Event root: %s. Event leaf count: %d.", - block.Num, block.Hash, event.UpdateL1InfoTreeV2.CurrentL1InfoRoot.String(), event.UpdateL1InfoTreeV2.LeafCount) - - root, err := p.l1InfoTree.GetLastRoot(tx) - if err != nil { - return fmt.Errorf("GetLastRoot(). err: %w", err) - } - // If the sanity check fails, halt the syncer and rollback. The sanity check could have - // failed due to a reorg. Hopefully, this is the case, eventually the reorg will get detected, - // and the syncer will get unhalted. Otherwise, this means that the syncer has an inconsistent state - // compared to the contracts, and this will need manual intervention. - if root.Hash != event.UpdateL1InfoTreeV2.CurrentL1InfoRoot || root.Index+1 != event.UpdateL1InfoTreeV2.LeafCount { - errStr := fmt.Sprintf( - "failed to check UpdateL1InfoTreeV2. Root: %s vs event: %s. "+ - "Index: %d vs event.LeafCount: %d. Happened on block %d", - root.Hash, event.UpdateL1InfoTreeV2.CurrentL1InfoRoot.String(), - root.Index, event.UpdateL1InfoTreeV2.LeafCount, - block.Num, - ) - p.log.Error(errStr) - p.mu.Lock() - p.haltedReason = errStr - p.halted = true - p.mu.Unlock() - return sync.ErrInconsistentState - } - } - if event.VerifyBatches != nil { - p.log.Debugf("handle VerifyBatches event %s", event.VerifyBatches.String()) - err = p.processVerifyBatches(tx, block.Num, event.VerifyBatches) - if err != nil { - err = fmt.Errorf("processVerifyBatches. err: %w", err) - p.log.Errorf("error processing VerifyBatches: %v", err) - return err - } - } - - if event.InitL1InfoRootMap != nil { - p.log.Debugf("handle InitL1InfoRootMap event %s", event.InitL1InfoRootMap.String()) - err = processEventInitL1InfoRootMap(tx, block.Num, event.InitL1InfoRootMap) - if err != nil { - err = fmt.Errorf("initL1InfoRootMap. Err: %w", err) - p.log.Errorf("error processing InitL1InfoRootMap: %v", err) - return err - } - } - } - - if err := tx.Commit(); err != nil { - return fmt.Errorf("err: %w", err) - } - shouldRollback = false - logFunc := p.log.Debugf - if len(block.Events) > 0 { - logFunc = p.log.Infof - } - logFunc("block %d processed with %d events", block.Num, len(block.Events)) - return nil -} - -func (p *processor) getLastIndex(tx db.Querier) (uint32, error) { - var lastProcessedIndex uint32 - row := tx.QueryRow("SELECT position FROM l1info_leaf ORDER BY block_num DESC, block_pos DESC LIMIT 1;") - err := row.Scan(&lastProcessedIndex) - if errors.Is(err, sql.ErrNoRows) { - return 0, db.ErrNotFound - } - return lastProcessedIndex, err -} - -func (p *processor) GetFirstL1InfoWithRollupExitRoot(rollupExitRoot common.Hash) (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - err := meddler.QueryRow(p.db, info, ` - SELECT * FROM l1info_leaf - WHERE rollup_exit_root = $1 - ORDER BY block_num ASC, block_pos ASC - LIMIT 1; - `, rollupExitRoot.Hex()) - return info, db.ReturnErrNotFound(err) -} - -func (p *processor) GetLastInfo() (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - err := meddler.QueryRow(p.db, info, ` - SELECT * FROM l1info_leaf - ORDER BY block_num DESC, block_pos DESC - LIMIT 1; - `) - return info, db.ReturnErrNotFound(err) -} - -func (p *processor) GetFirstInfo() (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - err := meddler.QueryRow(p.db, info, ` - SELECT * FROM l1info_leaf - ORDER BY block_num ASC, block_pos ASC - LIMIT 1; - `) - return info, db.ReturnErrNotFound(err) -} - -func (p *processor) GetFirstInfoAfterBlock(blockNum uint64) (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - err := meddler.QueryRow(p.db, info, ` - SELECT * FROM l1info_leaf - WHERE block_num >= $1 - ORDER BY block_num ASC, block_pos ASC - LIMIT 1; - `, blockNum) - return info, db.ReturnErrNotFound(err) -} - -func (p *processor) GetInfoByGlobalExitRoot(ger common.Hash) (*L1InfoTreeLeaf, error) { - info := &L1InfoTreeLeaf{} - err := meddler.QueryRow(p.db, info, ` - SELECT * FROM l1info_leaf - WHERE global_exit_root = $1 - LIMIT 1; - `, ger.String()) - return info, db.ReturnErrNotFound(err) -} - -func (p *processor) getDBQuerier(tx db.Txer) db.Querier { - if tx != nil { - return tx - } - return p.db -} - -func (p *processor) isHalted() bool { - p.mu.RLock() - defer p.mu.RUnlock() - return p.halted -} diff --git a/l1infotreesync/processor_initl1inforootmap.go b/l1infotreesync/processor_initl1inforootmap.go deleted file mode 100644 index 92732cd94..000000000 --- a/l1infotreesync/processor_initl1inforootmap.go +++ /dev/null @@ -1,37 +0,0 @@ -package l1infotreesync - -import ( - "database/sql" - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/russross/meddler" -) - -func processEventInitL1InfoRootMap(tx db.Txer, blockNumber uint64, event *InitL1InfoRootMap) error { - if event == nil { - return nil - } - info := &L1InfoTreeInitial{ - BlockNumber: blockNumber, - LeafCount: event.LeafCount, - L1InfoRoot: event.CurrentL1InfoRoot, - } - log.Infof("insert InitL1InfoRootMap %s ", info.String()) - if err := meddler.Insert(tx, "l1info_initial", info); err != nil { - return fmt.Errorf("err: %w", err) - } - return nil -} - -// GetInitL1InfoRootMap returns the initial L1 info root map, nil if no root map has been set -func (p *processor) GetInitL1InfoRootMap(tx db.Txer) (*L1InfoTreeInitial, error) { - info := &L1InfoTreeInitial{} - err := meddler.QueryRow(p.getDBQuerier(tx), info, `SELECT block_num, leaf_count,l1_info_root FROM l1info_initial`) - if errors.Is(err, sql.ErrNoRows) { - return nil, nil - } - return info, err -} diff --git a/l1infotreesync/processor_initl1inforootmap_test.go b/l1infotreesync/processor_initl1inforootmap_test.go deleted file mode 100644 index 9d2284652..000000000 --- a/l1infotreesync/processor_initl1inforootmap_test.go +++ /dev/null @@ -1,68 +0,0 @@ -package l1infotreesync - -import ( - "context" - "path" - "testing" - - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestInitL1InfoRootMap(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestInitL1InfoRootMap.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - ctx := context.TODO() - event := InitL1InfoRootMap{ - LeafCount: 1, - CurrentL1InfoRoot: common.HexToHash("beef"), - } - block := sync.Block{ - Num: 1, - Events: []interface{}{ - Event{InitL1InfoRootMap: &event}, - }, - } - - err = sut.ProcessBlock(ctx, block) - require.NoError(t, err) - - info, err := sut.GetInitL1InfoRootMap(nil) - require.NoError(t, err) - require.NotNil(t, info) - require.Equal(t, event.LeafCount, info.LeafCount) - require.Equal(t, event.CurrentL1InfoRoot, info.L1InfoRoot) - require.Equal(t, block.Num, info.BlockNumber) -} - -func TestInitL1InfoRootMapDontAllow2Rows(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestInitL1InfoRootMapDontAllow2Rows.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - ctx := context.TODO() - block := sync.Block{ - Num: 1, - Events: []interface{}{ - Event{InitL1InfoRootMap: &InitL1InfoRootMap{ - LeafCount: 1, - CurrentL1InfoRoot: common.HexToHash("beef"), - }}, - }, - } - err = sut.ProcessBlock(ctx, block) - require.NoError(t, err) - block.Num = 2 - err = sut.ProcessBlock(ctx, block) - require.Error(t, err, "should not allow to insert a second row") -} - -func TestGetInitL1InfoRootMap(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestGetInitL1InfoRootMap.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - info, err := sut.GetInitL1InfoRootMap(nil) - require.NoError(t, err, "should return no error if no row is present, because it returns data=nil") - require.Nil(t, info, "should return nil if no row is present") -} diff --git a/l1infotreesync/processor_test.go b/l1infotreesync/processor_test.go deleted file mode 100644 index df0b8444e..000000000 --- a/l1infotreesync/processor_test.go +++ /dev/null @@ -1,384 +0,0 @@ -package l1infotreesync - -import ( - "fmt" - "path" - "testing" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/l1infotree" - "github.com/0xPolygon/cdk/l1infotreesync/migrations" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/0xPolygon/cdk/tree" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" - "golang.org/x/net/context" -) - -func TestGetInfo(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestGetInfo.sqlite") - p, err := newProcessor(dbPath) - require.NoError(t, err) - ctx := context.Background() - - // Test ErrNotFound returned correctly on all methods - _, err = p.GetFirstL1InfoWithRollupExitRoot(common.Hash{}) - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetLastInfo() - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetFirstInfo() - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetFirstInfoAfterBlock(0) - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetInfoByGlobalExitRoot(common.Hash{}) - require.Equal(t, db.ErrNotFound, err) - - // First insert - info1 := &UpdateL1InfoTree{ - MainnetExitRoot: common.HexToHash("beef"), - RollupExitRoot: common.HexToHash("5ca1e"), - ParentHash: common.HexToHash("1010101"), - Timestamp: 420, - } - expected1 := L1InfoTreeLeaf{ - BlockNumber: 1, - L1InfoTreeIndex: 0, - PreviousBlockHash: info1.ParentHash, - Timestamp: info1.Timestamp, - MainnetExitRoot: info1.MainnetExitRoot, - RollupExitRoot: info1.RollupExitRoot, - } - expected1.GlobalExitRoot = expected1.globalExitRoot() - expected1.Hash = expected1.hash() - err = p.ProcessBlock(ctx, sync.Block{ - Num: 1, - Events: []interface{}{ - Event{UpdateL1InfoTree: info1}, - }, - }) - require.NoError(t, err) - actual, err := p.GetFirstL1InfoWithRollupExitRoot(info1.RollupExitRoot) - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetLastInfo() - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetFirstInfo() - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetFirstInfoAfterBlock(0) - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetInfoByGlobalExitRoot(expected1.GlobalExitRoot) - require.NoError(t, err) - require.Equal(t, expected1, *actual) - - // Second insert - info2 := &UpdateL1InfoTree{ - MainnetExitRoot: common.HexToHash("b055"), - RollupExitRoot: common.HexToHash("5ca1e"), - ParentHash: common.HexToHash("1010101"), - Timestamp: 420, - } - expected2 := L1InfoTreeLeaf{ - BlockNumber: 2, - L1InfoTreeIndex: 1, - PreviousBlockHash: info2.ParentHash, - Timestamp: info2.Timestamp, - MainnetExitRoot: info2.MainnetExitRoot, - RollupExitRoot: info2.RollupExitRoot, - } - expected2.GlobalExitRoot = expected2.globalExitRoot() - expected2.Hash = expected2.hash() - err = p.ProcessBlock(ctx, sync.Block{ - Num: 2, - Events: []interface{}{ - Event{UpdateL1InfoTree: info2}, - }, - }) - require.NoError(t, err) - actual, err = p.GetFirstL1InfoWithRollupExitRoot(info2.RollupExitRoot) - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetLastInfo() - require.NoError(t, err) - require.Equal(t, expected2, *actual) - actual, err = p.GetFirstInfo() - require.NoError(t, err) - require.Equal(t, expected1, *actual) - actual, err = p.GetFirstInfoAfterBlock(2) - require.NoError(t, err) - require.Equal(t, expected2, *actual) - actual, err = p.GetInfoByGlobalExitRoot(expected2.GlobalExitRoot) - require.NoError(t, err) - require.Equal(t, expected2, *actual) -} - -func TestGetLatestInfoUntilBlockIfNotFoundReturnsErrNotFound(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestGetLatestInfoUntilBlockIfNotFoundReturnsErrNotFound.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - ctx := context.Background() - // Fake block 1 - _, err = sut.db.Exec(`INSERT INTO block (num) VALUES ($1)`, 1) - require.NoError(t, err) - - _, err = sut.GetLatestInfoUntilBlock(ctx, 1) - require.Equal(t, db.ErrNotFound, err) -} - -func Test_processor_GetL1InfoTreeMerkleProof(t *testing.T) { - testTable := []struct { - name string - getProcessor func(t *testing.T) *processor - idx uint32 - expectedRoot types.Root - expectedErr error - }{ - { - name: "empty tree", - getProcessor: func(t *testing.T) *processor { - t.Helper() - - p, err := newProcessor(path.Join(t.TempDir(), "l1infotreesyncTest_processor_GetL1InfoTreeMerkleProof_1.sqlite")) - require.NoError(t, err) - - return p - }, - idx: 0, - expectedErr: db.ErrNotFound, - }, - { - name: "single leaf tree", - getProcessor: func(t *testing.T) *processor { - t.Helper() - - p, err := newProcessor(path.Join(t.TempDir(), "l1infotreesyncTest_processor_GetL1InfoTreeMerkleProof_2.sqlite")) - require.NoError(t, err) - - info := &UpdateL1InfoTree{ - MainnetExitRoot: common.HexToHash("beef"), - RollupExitRoot: common.HexToHash("5ca1e"), - ParentHash: common.HexToHash("1010101"), - Timestamp: 420, - } - err = p.ProcessBlock(context.Background(), sync.Block{ - Num: 1, - Events: []interface{}{ - Event{UpdateL1InfoTree: info}, - }, - }) - require.NoError(t, err) - - return p - }, - idx: 0, - expectedRoot: types.Root{ - Hash: common.HexToHash("beef"), - Index: 0, - BlockNum: 1, - BlockPosition: 0, - }, - }, - } - - for _, tt := range testTable { - tt := tt - - t.Run(tt.name, func(t *testing.T) { - p := tt.getProcessor(t) - proof, root, err := p.GetL1InfoTreeMerkleProof(context.Background(), tt.idx) - if tt.expectedErr != nil { - require.Equal(t, tt.expectedErr, err) - } else { - require.NoError(t, err) - require.NotEmpty(t, proof) - require.NotEmpty(t, root.Hash) - require.Equal(t, tt.expectedRoot.Index, root.Index) - require.Equal(t, tt.expectedRoot.BlockNum, root.BlockNum) - require.Equal(t, tt.expectedRoot.BlockPosition, root.BlockPosition) - } - }) - } -} - -func Test_processor_Reorg(t *testing.T) { - t.Parallel() - - testTable := []struct { - name string - getProcessor func(t *testing.T) *processor - reorgBlock uint64 - expectedErr error - }{ - { - name: "empty tree", - getProcessor: func(t *testing.T) *processor { - t.Helper() - - p, err := newProcessor(path.Join(t.TempDir(), "l1infotreesyncTest_processor_Reorg_1.sqlite")) - require.NoError(t, err) - return p - }, - reorgBlock: 0, - expectedErr: nil, - }, - { - name: "single leaf tree", - getProcessor: func(t *testing.T) *processor { - t.Helper() - - p, err := newProcessor(path.Join(t.TempDir(), "l1infotreesyncTest_processor_Reorg_2.sqlite")) - require.NoError(t, err) - - info := &UpdateL1InfoTree{ - MainnetExitRoot: common.HexToHash("beef"), - RollupExitRoot: common.HexToHash("5ca1e"), - ParentHash: common.HexToHash("1010101"), - Timestamp: 420, - } - err = p.ProcessBlock(context.Background(), sync.Block{ - Num: 1, - Events: []interface{}{ - Event{UpdateL1InfoTree: info}, - }, - }) - require.NoError(t, err) - - return p - }, - reorgBlock: 1, - }, - } - - for _, tt := range testTable { - tt := tt - - t.Run(tt.name, func(t *testing.T) { - t.Parallel() - - p := tt.getProcessor(t) - err := p.Reorg(context.Background(), tt.reorgBlock) - if tt.expectedErr != nil { - require.Equal(t, tt.expectedErr, err) - } else { - require.NoError(t, err) - } - }) - } -} - -func TestProofsFromDifferentTrees(t *testing.T) { - fmt.Println("aggregator L1InfoTree ===============================================") - - l1Tree, err := l1infotree.NewL1InfoTree(log.WithFields("test"), types.DefaultHeight, [][32]byte{}) - require.NoError(t, err) - - leaves := createTestLeaves(t, 2) - - aLeaves := make([][32]byte, len(leaves)) - for i, leaf := range leaves { - aLeaves[i] = l1infotree.HashLeafData( - leaf.GlobalExitRoot, - leaf.PreviousBlockHash, - leaf.Timestamp) - } - - aggregatorL1InfoTree, aggregatorRoot, err := l1Tree.ComputeMerkleProof(leaves[0].L1InfoTreeIndex, aLeaves) - require.NoError(t, err) - - aggregatorProof := types.Proof{} - for i, p := range aggregatorL1InfoTree { - aggregatorProof[i] = common.BytesToHash(p[:]) - } - - fmt.Println(aggregatorRoot) - fmt.Println(aggregatorProof) - fmt.Println("l1 info tree syncer L1InfoTree ===============================================") - - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestProofsFromDifferentTrees.sqlite") - require.NoError(t, migrations.RunMigrations(dbPath)) - - dbe, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - - l1InfoTree := tree.NewAppendOnlyTree(dbe, migrations.L1InfoTreePrefix) - - tx, err := db.NewTx(context.Background(), dbe) - require.NoError(t, err) - - for _, leaf := range leaves { - err = l1InfoTree.AddLeaf(tx, leaf.BlockNumber, leaf.BlockPosition, types.Leaf{ - Index: leaf.L1InfoTreeIndex, - Hash: leaf.Hash, - }) - - require.NoError(t, err) - } - - require.NoError(t, tx.Commit()) - - l1InfoTreeSyncerRoot, err := l1InfoTree.GetRootByIndex(context.Background(), leaves[1].L1InfoTreeIndex) - require.NoError(t, err) - l1InfoTreeSyncerProof, err := l1InfoTree.GetProof(context.Background(), leaves[0].L1InfoTreeIndex, l1InfoTreeSyncerRoot.Hash) - require.NoError(t, err) - for i, l := range aggregatorL1InfoTree { - require.Equal(t, common.Hash(l), l1InfoTreeSyncerProof[i]) - } - - fmt.Println(leaves[0].GlobalExitRoot) - fmt.Println(l1InfoTreeSyncerProof) - - require.Equal(t, aggregatorRoot, l1InfoTreeSyncerRoot.Hash) - require.Equal(t, aggregatorProof, l1InfoTreeSyncerProof) -} - -func createTestLeaves(t *testing.T, numOfLeaves int) []*L1InfoTreeLeaf { - t.Helper() - - leaves := make([]*L1InfoTreeLeaf, 0, numOfLeaves) - - for i := 0; i < numOfLeaves; i++ { - leaf := &L1InfoTreeLeaf{ - L1InfoTreeIndex: uint32(i), - Timestamp: uint64(i), - BlockNumber: uint64(i), - BlockPosition: uint64(i), - PreviousBlockHash: common.HexToHash(fmt.Sprintf("0x%x", i)), - MainnetExitRoot: common.HexToHash(fmt.Sprintf("0x%x", i)), - RollupExitRoot: common.HexToHash(fmt.Sprintf("0x%x", i)), - } - - leaf.GlobalExitRoot = leaf.globalExitRoot() - leaf.Hash = leaf.hash() - - leaves = append(leaves, leaf) - } - - return leaves -} - -func TestProcessBlockUpdateL1InfoTreeV2DontMatchTree(t *testing.T) { - sut, err := newProcessor(path.Join(t.TempDir(), "l1infotreesyncTestProcessBlockUpdateL1InfoTreeV2DontMatchTree.sqlite")) - require.NoError(t, err) - block := sync.Block{ - Num: 10, - Events: []interface{}{ - Event{UpdateL1InfoTree: &UpdateL1InfoTree{ - MainnetExitRoot: common.HexToHash("beef"), - RollupExitRoot: common.HexToHash("5ca1e"), - ParentHash: common.HexToHash("1010101"), - Timestamp: 420, - }}, - Event{UpdateL1InfoTreeV2: &UpdateL1InfoTreeV2{ - CurrentL1InfoRoot: common.HexToHash("beef"), - LeafCount: 1, - }}, - }, - } - err = sut.ProcessBlock(context.Background(), block) - require.ErrorIs(t, err, sync.ErrInconsistentState) - require.True(t, sut.halted) -} diff --git a/l1infotreesync/processor_verifybatches.go b/l1infotreesync/processor_verifybatches.go deleted file mode 100644 index 9d1d0efba..000000000 --- a/l1infotreesync/processor_verifybatches.go +++ /dev/null @@ -1,104 +0,0 @@ -package l1infotreesync - -import ( - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - treeTypes "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/russross/meddler" -) - -func (p *processor) processVerifyBatches(tx db.Txer, blockNumber uint64, event *VerifyBatches) error { - if event == nil { - return fmt.Errorf("processVerifyBatches: event is nil") - } - if tx == nil { - return fmt.Errorf("processVerifyBatches: tx is nil, is mandatory to pass a tx") - } - log.Debugf("VerifyBatches: rollupExitTree.UpsertLeaf (blockNumber=%d, event=%s)", blockNumber, event.String()) - // If ExitRoot is zero if the leaf doesnt exists doesnt change the root of tree. - // if leaf already exists doesn't make sense to 'empty' the leaf, so we keep previous value - if event.ExitRoot == (common.Hash{}) { - log.Infof("skipping VerifyBatches event with empty ExitRoot (blockNumber=%d, event=%s)", blockNumber, event.String()) - return nil - } - isNewLeaf, err := p.isNewValueForRollupExitTree(tx, event) - if err != nil { - return fmt.Errorf("isNewValueForrollupExitTree. err: %w", err) - } - if !isNewLeaf { - log.Infof("skipping VerifyBatches event with same ExitRoot (blockNumber=%d, event=%s)", blockNumber, event.String()) - return nil - } - log.Infof("UpsertLeaf VerifyBatches event (blockNumber=%d, event=%s)", blockNumber, event.String()) - newRoot, err := p.rollupExitTree.UpsertLeaf(tx, blockNumber, event.BlockPosition, treeTypes.Leaf{ - Index: event.RollupID - 1, - Hash: event.ExitRoot, - }) - if err != nil { - return fmt.Errorf("error rollupExitTree.UpsertLeaf. err: %w", err) - } - verifyBatches := event - verifyBatches.BlockNumber = blockNumber - verifyBatches.RollupExitRoot = newRoot - if err = meddler.Insert(tx, "verify_batches", verifyBatches); err != nil { - return fmt.Errorf("error inserting verify_batches. err: %w", err) - } - return nil -} - -func (p *processor) isNewValueForRollupExitTree(tx db.Querier, event *VerifyBatches) (bool, error) { - currentRoot, err := p.rollupExitTree.GetLastRoot(tx) - if err != nil && errors.Is(err, db.ErrNotFound) { - // The tree is empty, so is a new value for sure - return true, nil - } - if err != nil { - return false, fmt.Errorf("error rollupExitTree.GetLastRoot. err: %w", err) - } - leaf, err := p.rollupExitTree.GetLeaf(tx, event.RollupID-1, currentRoot.Hash) - if err != nil && errors.Is(err, db.ErrNotFound) { - // The leaf doesn't exist, so is a new value - return true, nil - } - if err != nil { - return false, fmt.Errorf("error rollupExitTree.GetLeaf. err: %w", err) - } - return leaf != event.ExitRoot, nil -} - -func (p *processor) GetLastVerifiedBatches(rollupID uint32) (*VerifyBatches, error) { - verified := &VerifyBatches{} - err := meddler.QueryRow(p.db, verified, ` - SELECT * FROM verify_batches - WHERE rollup_id = $1 - ORDER BY block_num DESC, block_pos DESC - LIMIT 1; - `, rollupID) - return verified, db.ReturnErrNotFound(err) -} - -func (p *processor) GetFirstVerifiedBatches(rollupID uint32) (*VerifyBatches, error) { - verified := &VerifyBatches{} - err := meddler.QueryRow(p.db, verified, ` - SELECT * FROM verify_batches - WHERE rollup_id = $1 - ORDER BY block_num ASC, block_pos ASC - LIMIT 1; - `, rollupID) - return verified, db.ReturnErrNotFound(err) -} - -func (p *processor) GetFirstVerifiedBatchesAfterBlock(rollupID uint32, blockNum uint64) (*VerifyBatches, error) { - verified := &VerifyBatches{} - err := meddler.QueryRow(p.db, verified, ` - SELECT * FROM verify_batches - WHERE rollup_id = $1 AND block_num >= $2 - ORDER BY block_num ASC, block_pos ASC - LIMIT 1; - `, rollupID, blockNum) - return verified, db.ReturnErrNotFound(err) -} diff --git a/l1infotreesync/processor_verifybatches_test.go b/l1infotreesync/processor_verifybatches_test.go deleted file mode 100644 index f8150970d..000000000 --- a/l1infotreesync/processor_verifybatches_test.go +++ /dev/null @@ -1,128 +0,0 @@ -package l1infotreesync - -import ( - "context" - "path" - "testing" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestProcessVerifyBatchesNil(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestProcessVerifyBatchesNil.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - err = sut.processVerifyBatches(nil, 1, nil) - require.Error(t, err) -} - -func TestProcessVerifyBatchesOK(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestProcessVerifyBatchesOK.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - event := VerifyBatches{ - BlockPosition: 1, - RollupID: 1, - NumBatch: 1, - StateRoot: common.HexToHash("5ca1e"), - ExitRoot: common.HexToHash("b455"), - Aggregator: common.HexToAddress("beef"), - RollupExitRoot: common.HexToHash("b455"), - } - ctx := context.TODO() - tx, err := db.NewTx(ctx, sut.db) - require.NoError(t, err) - _, err = tx.Exec(`INSERT INTO block (num) VALUES ($1)`, 1) - require.NoError(t, err) - err = sut.processVerifyBatches(tx, 1, &event) - require.NoError(t, err) -} - -func TestProcessVerifyBatchesSkip0000(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestProcessVerifyBatchesSkip0000.sqlite") - sut, err := newProcessor(dbPath) - require.NoError(t, err) - event := VerifyBatches{ - BlockPosition: 1, - RollupID: 1, - NumBatch: 1, - StateRoot: common.HexToHash("5ca1e"), - ExitRoot: common.Hash{}, - Aggregator: common.HexToAddress("beef"), - RollupExitRoot: common.HexToHash("b455"), - } - ctx := context.TODO() - tx, err := db.NewTx(ctx, sut.db) - require.NoError(t, err) - err = sut.processVerifyBatches(tx, 1, &event) - require.NoError(t, err) -} - -func TestGetVerifiedBatches(t *testing.T) { - dbPath := path.Join(t.TempDir(), "l1infotreesyncTestGetVerifiedBatches.sqlite") - p, err := newProcessor(dbPath) - require.NoError(t, err) - ctx := context.Background() - - // Test ErrNotFound returned correctly on all methods - _, err = p.GetLastVerifiedBatches(0) - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetFirstVerifiedBatches(0) - require.Equal(t, db.ErrNotFound, err) - _, err = p.GetFirstVerifiedBatchesAfterBlock(0, 0) - require.Equal(t, db.ErrNotFound, err) - - // First insert - expected1 := &VerifyBatches{ - RollupID: 420, - NumBatch: 69, - StateRoot: common.HexToHash("5ca1e"), - ExitRoot: common.HexToHash("b455"), - Aggregator: common.HexToAddress("beef"), - } - err = p.ProcessBlock(ctx, sync.Block{ - Num: 1, - Events: []interface{}{ - Event{VerifyBatches: expected1}, - }, - }) - require.NoError(t, err) - _, err = p.GetLastVerifiedBatches(0) - require.Equal(t, db.ErrNotFound, err) - actual, err := p.GetLastVerifiedBatches(420) - require.NoError(t, err) - require.Equal(t, expected1, actual) - actual, err = p.GetFirstVerifiedBatches(420) - require.NoError(t, err) - require.Equal(t, expected1, actual) - - // Second insert - expected2 := &VerifyBatches{ - RollupID: 420, - NumBatch: 690, - StateRoot: common.HexToHash("5ca1e3"), - ExitRoot: common.HexToHash("ba55"), - Aggregator: common.HexToAddress("beef3"), - } - err = p.ProcessBlock(ctx, sync.Block{ - Num: 2, - Events: []interface{}{ - Event{VerifyBatches: expected2}, - }, - }) - require.NoError(t, err) - _, err = p.GetLastVerifiedBatches(0) - require.Equal(t, db.ErrNotFound, err) - actual, err = p.GetLastVerifiedBatches(420) - require.NoError(t, err) - require.Equal(t, expected2, actual) - actual, err = p.GetFirstVerifiedBatches(420) - require.NoError(t, err) - require.Equal(t, expected1, actual) - actual, err = p.GetFirstVerifiedBatchesAfterBlock(420, 2) - require.NoError(t, err) - require.Equal(t, expected2, actual) -} diff --git a/lastgersync/config.go b/lastgersync/config.go deleted file mode 100644 index 36b12ab60..000000000 --- a/lastgersync/config.go +++ /dev/null @@ -1,28 +0,0 @@ -package lastgersync - -import ( - "github.com/0xPolygon/cdk/config/types" - "github.com/ethereum/go-ethereum/common" -) - -type Config struct { - // DBPath path of the DB - DBPath string `mapstructure:"DBPath"` - // BlockFinality indicates the status of the blocks that will be queried in order to sync - BlockFinality string `jsonschema:"enum=LatestBlock, enum=SafeBlock, enum=PendingBlock, enum=FinalizedBlock, enum=EarliestBlock" mapstructure:"BlockFinality"` //nolint:lll - // InitialBlockNum is the first block that will be queried when starting the synchronization from scratch. - // It should be a number equal or bellow the creation of the bridge contract - InitialBlockNum uint64 `mapstructure:"InitialBlockNum"` - // GlobalExitRootL2Addr is the address of the GER smart contract on L2 - GlobalExitRootL2Addr common.Address `mapstructure:"GlobalExitRootL2Addr"` - // RetryAfterErrorPeriod is the time that will be waited when an unexpected error happens before retry - RetryAfterErrorPeriod types.Duration `mapstructure:"RetryAfterErrorPeriod"` - // MaxRetryAttemptsAfterError is the maximum number of consecutive attempts that will happen before panicing. - // Any number smaller than zero will be considered as unlimited retries - MaxRetryAttemptsAfterError int `mapstructure:"MaxRetryAttemptsAfterError"` - // WaitForNewBlocksPeriod time that will be waited when the synchronizer has reached the latest block - WaitForNewBlocksPeriod types.Duration `mapstructure:"WaitForNewBlocksPeriod"` - // DownloadBufferSize buffer of events to be porcessed. When the buffer limit is reached, - // downloading will stop until the processing catches up. - DownloadBufferSize int `mapstructure:"DownloadBufferSize"` -} diff --git a/lastgersync/e2e_test.go b/lastgersync/e2e_test.go deleted file mode 100644 index 2ec7eadfd..000000000 --- a/lastgersync/e2e_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package lastgersync_test - -import ( - "context" - "fmt" - "math/big" - "path" - "strconv" - "testing" - "time" - - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/lastgersync" - "github.com/0xPolygon/cdk/test/helpers" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestE2E(t *testing.T) { - ctx := context.Background() - l1Env, l2Env := helpers.NewL1EnvWithL2EVM(t) - dbPathSyncer := path.Join(t.TempDir(), "lastgersyncTestE2E.sqlite") - syncer, err := lastgersync.New( - ctx, - dbPathSyncer, - l2Env.ReorgDetector, - l2Env.SimBackend.Client(), - l2Env.GERAddr, - l1Env.InfoTreeSync, - 0, - 0, - etherman.LatestBlock, - time.Millisecond*30, - 10, - ) - require.NoError(t, err) - go syncer.Start(ctx) - - for i := 0; i < 10; i++ { - // Update GER on L1 - _, err := l1Env.GERContract.UpdateExitRoot(l1Env.Auth, common.HexToHash(strconv.Itoa(i))) - require.NoError(t, err) - l1Env.SimBackend.Commit() - time.Sleep(time.Millisecond * 150) - expectedGER, err := l1Env.GERContract.GetLastGlobalExitRoot(&bind.CallOpts{Pending: false}) - require.NoError(t, err) - _, err = l2Env.GERContract.InsertGlobalExitRoot(l2Env.Auth, expectedGER) - require.NoError(t, err) - l2Env.SimBackend.Commit() - gerIndex, err := l2Env.GERContract.GlobalExitRootMap(nil, expectedGER) - require.NoError(t, err) - require.Equal(t, big.NewInt(int64(i+1)), gerIndex, fmt.Sprintf("iteration %d, GER: %s is not updated on L2", i, common.Bytes2Hex(expectedGER[:]))) - - // Wait for syncer to catch up - lb, err := l2Env.SimBackend.Client().BlockNumber(ctx) - require.NoError(t, err) - helpers.RequireProcessorUpdated(t, syncer, lb) - - e, err := syncer.GetFirstGERAfterL1InfoTreeIndex(ctx, uint32(i)) - require.NoError(t, err, fmt.Sprint("iteration: ", i)) - require.Equal(t, common.Hash(expectedGER), e.GlobalExitRoot, fmt.Sprint("iteration: ", i)) - } -} diff --git a/lastgersync/evmdownloader.go b/lastgersync/evmdownloader.go deleted file mode 100644 index 9a203b596..000000000 --- a/lastgersync/evmdownloader.go +++ /dev/null @@ -1,180 +0,0 @@ -package lastgersync - -import ( - "context" - "errors" - "fmt" - "math/big" - "time" - - "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/globalexitrootmanagerl2sovereignchain" - cdkcommon "github.com/0xPolygon/cdk/common" - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" -) - -type EthClienter interface { - ethereum.LogFilterer - ethereum.BlockNumberReader - ethereum.ChainReader - bind.ContractBackend -} - -type downloader struct { - *sync.EVMDownloaderImplementation - l2GERManager *globalexitrootmanagerl2sovereignchain.Globalexitrootmanagerl2sovereignchain - l1InfoTreesync *l1infotreesync.L1InfoTreeSync - processor *processor - rh *sync.RetryHandler -} - -func newDownloader( - l2Client EthClienter, - l2GERAddr common.Address, - l1InfoTreeSync *l1infotreesync.L1InfoTreeSync, - processor *processor, - rh *sync.RetryHandler, - blockFinality *big.Int, - waitForNewBlocksPeriod time.Duration, -) (*downloader, error) { - gerContract, err := globalexitrootmanagerl2sovereignchain.NewGlobalexitrootmanagerl2sovereignchain( - l2GERAddr, l2Client) - if err != nil { - return nil, err - } - - return &downloader{ - EVMDownloaderImplementation: sync.NewEVMDownloaderImplementation( - "lastgersync", l2Client, blockFinality, waitForNewBlocksPeriod, nil, nil, nil, rh, - ), - l2GERManager: gerContract, - l1InfoTreesync: l1InfoTreeSync, - processor: processor, - rh: rh, - }, nil -} - -func (d *downloader) Download(ctx context.Context, fromBlock uint64, downloadedCh chan sync.EVMBlock) { - var ( - attempts int - nextIndex uint32 - err error - ) - for { - lastIndex, err := d.processor.getLastIndex() - if errors.Is(err, db.ErrNotFound) { - nextIndex = 0 - } else if err != nil { - log.Errorf("error getting last indes: %v", err) - attempts++ - d.rh.Handle("getLastIndex", attempts) - - continue - } - if lastIndex > 0 { - nextIndex = lastIndex + 1 - } - break - } - for { - select { - case <-ctx.Done(): - log.Debug("closing channel") - close(downloadedCh) - - return - default: - } - fromBlock = d.WaitForNewBlocks(ctx, fromBlock) - - attempts = 0 - var gers []Event - for { - gers, err = d.getGERsFromIndex(ctx, nextIndex) - if err != nil { - log.Errorf("error getting GERs: %v", err) - attempts++ - d.rh.Handle("getGERsFromIndex", attempts) - - continue - } - - break - } - - blockHeader, isCanceled := d.GetBlockHeader(ctx, fromBlock) - if isCanceled { - return - } - - block := &sync.EVMBlock{ - EVMBlockHeader: sync.EVMBlockHeader{ - Num: blockHeader.Num, - Hash: blockHeader.Hash, - ParentHash: blockHeader.ParentHash, - Timestamp: blockHeader.Timestamp, - }, - } - d.setGreatestGERInjectedFromList(block, gers) - - downloadedCh <- *block - if len(block.Events) > 0 { - event, ok := block.Events[0].(Event) - if !ok { - log.Errorf("unexpected type %T in events", block.Events[0]) - } - nextIndex = event.L1InfoTreeIndex + 1 - } - } -} - -func (d *downloader) getGERsFromIndex(ctx context.Context, fromL1InfoTreeIndex uint32) ([]Event, error) { - lastRoot, err := d.l1InfoTreesync.GetLastL1InfoTreeRoot(ctx) - if errors.Is(err, db.ErrNotFound) { - return nil, nil - } - if err != nil { - return nil, fmt.Errorf("error calling GetLastL1InfoTreeRoot: %w", err) - } - - gers := []Event{} - for i := fromL1InfoTreeIndex; i <= lastRoot.Index; i++ { - info, err := d.l1InfoTreesync.GetInfoByIndex(ctx, i) - if err != nil { - return nil, fmt.Errorf("error calling GetInfoByIndex: %w", err) - } - gers = append(gers, Event{ - L1InfoTreeIndex: i, - GlobalExitRoot: info.GlobalExitRoot, - }) - } - - return gers, nil -} - -func (d *downloader) setGreatestGERInjectedFromList(b *sync.EVMBlock, list []Event) { - for _, event := range list { - var attempts int - for { - blockHashBigInt, err := d.l2GERManager.GlobalExitRootMap(&bind.CallOpts{Pending: false}, event.GlobalExitRoot) - if err != nil { - attempts++ - log.Errorf("failed to check if global exit root %s is injected on L2: %s", event.GlobalExitRoot.Hex(), err) - d.rh.Handle("GlobalExitRootMap", attempts) - - continue - } - - if common.BigToHash(blockHashBigInt) != cdkcommon.ZeroHash { - b.Events = []interface{}{event} - } - - break - } - } -} diff --git a/lastgersync/lastgersync.go b/lastgersync/lastgersync.go deleted file mode 100644 index 6d8f3509f..000000000 --- a/lastgersync/lastgersync.go +++ /dev/null @@ -1,84 +0,0 @@ -package lastgersync - -import ( - "context" - "time" - - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/sync" - "github.com/ethereum/go-ethereum/common" -) - -const ( - reorgDetectorID = "lastGERSync" -) - -type LastGERSync struct { - driver *sync.EVMDriver - processor *processor -} - -func New( - ctx context.Context, - dbPath string, - rdL2 sync.ReorgDetector, - l2Client EthClienter, - globalExitRootL2 common.Address, - l1InfoTreesync *l1infotreesync.L1InfoTreeSync, - retryAfterErrorPeriod time.Duration, - maxRetryAttemptsAfterError int, - blockFinality etherman.BlockNumberFinality, - waitForNewBlocksPeriod time.Duration, - downloadBufferSize int, -) (*LastGERSync, error) { - processor, err := newProcessor(dbPath, "lastGERSync") - if err != nil { - return nil, err - } - - rh := &sync.RetryHandler{ - RetryAfterErrorPeriod: retryAfterErrorPeriod, - MaxRetryAttemptsAfterError: maxRetryAttemptsAfterError, - } - bf, err := blockFinality.ToBlockNum() - if err != nil { - return nil, err - } - downloader, err := newDownloader( - l2Client, - globalExitRootL2, - l1InfoTreesync, - processor, - rh, - bf, - waitForNewBlocksPeriod, - ) - if err != nil { - return nil, err - } - - driver, err := sync.NewEVMDriver(rdL2, processor, downloader, reorgDetectorID, downloadBufferSize, rh) - if err != nil { - return nil, err - } - - return &LastGERSync{ - driver: driver, - processor: processor, - }, nil -} - -func (s *LastGERSync) Start(ctx context.Context) { - s.driver.Sync(ctx) -} - -func (s *LastGERSync) GetFirstGERAfterL1InfoTreeIndex( - ctx context.Context, atOrAfterL1InfoTreeIndex uint32, -) (Event, error) { - return s.processor.GetFirstGERAfterL1InfoTreeIndex(ctx, atOrAfterL1InfoTreeIndex) -} - -func (s *LastGERSync) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - return s.processor.GetLastProcessedBlock(ctx) -} diff --git a/lastgersync/migrations/lastgersync0001.sql b/lastgersync/migrations/lastgersync0001.sql deleted file mode 100644 index 88021fa10..000000000 --- a/lastgersync/migrations/lastgersync0001.sql +++ /dev/null @@ -1,14 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS block; -DROP TABLE IF EXISTS global_exit_root; - --- +migrate Up -CREATE TABLE block ( - num BIGINT PRIMARY KEY -); - -CREATE TABLE imported_global_exit_root ( - block_num INTEGER PRIMARY KEY REFERENCES block(num) ON DELETE CASCADE, - global_exit_root VARCHAR NOT NULL, - l1_info_tree_index INTEGER NOT NULL -); \ No newline at end of file diff --git a/lastgersync/migrations/migrations.go b/lastgersync/migrations/migrations.go deleted file mode 100644 index d55dd4498..000000000 --- a/lastgersync/migrations/migrations.go +++ /dev/null @@ -1,21 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" -) - -//go:embed lastgersync0001.sql -var mig001 string - -func RunMigrations(dbPath string) error { - migrations := []types.Migration{ - { - ID: "lastgersync0001", - SQL: mig001, - }, - } - return db.RunMigrations(dbPath, migrations) -} diff --git a/lastgersync/processor.go b/lastgersync/processor.go deleted file mode 100644 index 545c2495b..000000000 --- a/lastgersync/processor.go +++ /dev/null @@ -1,138 +0,0 @@ -package lastgersync - -import ( - "context" - "database/sql" - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/lastgersync/migrations" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/sync" - ethCommon "github.com/ethereum/go-ethereum/common" - "github.com/russross/meddler" -) - -type Event struct { - GlobalExitRoot ethCommon.Hash `meddler:"global_exit_root,hash"` - L1InfoTreeIndex uint32 `meddler:"l1_info_tree_index"` -} - -type eventWithBlockNum struct { - GlobalExitRoot ethCommon.Hash `meddler:"global_exit_root,hash"` - L1InfoTreeIndex uint32 `meddler:"l1_info_tree_index"` - BlockNum uint64 `meddler:"block_num"` -} - -type processor struct { - db *sql.DB - log *log.Logger -} - -func newProcessor(dbPath string, loggerPrefix string) (*processor, error) { - err := migrations.RunMigrations(dbPath) - if err != nil { - return nil, err - } - db, err := db.NewSQLiteDB(dbPath) - if err != nil { - return nil, err - } - logger := log.WithFields("lastger-syncer", loggerPrefix) - return &processor{ - db: db, - log: logger, - }, nil -} - -// GetLastProcessedBlock returns the last processed block by the processor, including blocks -// that don't have events -func (p *processor) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - var lastProcessedBlock uint64 - row := p.db.QueryRow("SELECT num FROM BLOCK ORDER BY num DESC LIMIT 1;") - err := row.Scan(&lastProcessedBlock) - if errors.Is(err, sql.ErrNoRows) { - return 0, nil - } - return lastProcessedBlock, err -} - -func (p *processor) getLastIndex() (uint32, error) { - var lastIndex uint32 - row := p.db.QueryRow(` - SELECT l1_info_tree_index - FROM imported_global_exit_root - ORDER BY l1_info_tree_index DESC LIMIT 1; - `) - err := row.Scan(&lastIndex) - if errors.Is(err, sql.ErrNoRows) { - return 0, nil - } - return lastIndex, err -} - -func (p *processor) ProcessBlock(ctx context.Context, block sync.Block) error { - tx, err := db.NewTx(ctx, p.db) - if err != nil { - return err - } - shouldRollback := true - defer func() { - if shouldRollback { - if errRollback := tx.Rollback(); errRollback != nil { - log.Errorf("error while rolling back tx %v", errRollback) - } - } - }() - - if _, err := tx.Exec(`INSERT INTO block (num) VALUES ($1)`, block.Num); err != nil { - return err - } - for _, e := range block.Events { - event, ok := e.(Event) - if !ok { - return errors.New("failed to convert sync.Block.Event to Event") - } - if err = meddler.Insert(tx, "imported_global_exit_root", &eventWithBlockNum{ - GlobalExitRoot: event.GlobalExitRoot, - L1InfoTreeIndex: event.L1InfoTreeIndex, - BlockNum: block.Num, - }); err != nil { - return err - } - } - - if err := tx.Commit(); err != nil { - return err - } - shouldRollback = false - p.log.Debugf("processed %d events until block %d", len(block.Events), block.Num) - return nil -} - -func (p *processor) Reorg(ctx context.Context, firstReorgedBlock uint64) error { - _, err := p.db.Exec(`DELETE FROM block WHERE num >= $1;`, firstReorgedBlock) - return fmt.Errorf("error processing reorg: %w", err) -} - -// GetFirstGERAfterL1InfoTreeIndex returns the first GER injected on the chain that is related to l1InfoTreeIndex -// or greater -func (p *processor) GetFirstGERAfterL1InfoTreeIndex( - ctx context.Context, l1InfoTreeIndex uint32, -) (Event, error) { - e := Event{} - err := meddler.QueryRow(p.db, &e, ` - SELECT l1_info_tree_index, global_exit_root - FROM imported_global_exit_root - WHERE l1_info_tree_index >= $1 - ORDER BY l1_info_tree_index ASC LIMIT 1; - `, l1InfoTreeIndex) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return e, db.ErrNotFound - } - return e, err - } - return e, nil -} diff --git a/log/config.go b/log/config.go deleted file mode 100644 index 4ebbf5020..000000000 --- a/log/config.go +++ /dev/null @@ -1,15 +0,0 @@ -package log - -// Config for log -type Config struct { - // Environment defining the log format ("production" or "development"). - // In development mode enables development mode (which makes DPanicLevel logs panic), - // uses a console encoder, writes to standard error, and disables sampling. - // Stacktraces are automatically included on logs of WarnLevel and above. - // Check [here](https://pkg.go.dev/go.uber.org/zap@v1.24.0#NewDevelopmentConfig) - Environment LogEnvironment `mapstructure:"Environment" jsonschema:"enum=production,enum=development"` - // Level of log. As lower value more logs are going to be generated - Level string `mapstructure:"Level" jsonschema:"enum=debug,enum=info,enum=warn,enum=error,enum=dpanic,enum=panic,enum=fatal"` //nolint:lll - // Outputs - Outputs []string `mapstructure:"Outputs"` -} diff --git a/log/log.go b/log/log.go deleted file mode 100644 index b6d9d1cc4..000000000 --- a/log/log.go +++ /dev/null @@ -1,330 +0,0 @@ -package log - -import ( - "fmt" - "os" - "strings" - "sync/atomic" - - zkevm "github.com/0xPolygon/cdk" - "github.com/hermeznetwork/tracerr" - "go.uber.org/zap" - "go.uber.org/zap/zapcore" -) - -// LogEnvironment represents the possible log environments. -type LogEnvironment string - -const ( - // EnvironmentProduction production log environment. - EnvironmentProduction = LogEnvironment("production") - // EnvironmentDevelopment development log environment. - EnvironmentDevelopment = LogEnvironment("development") -) - -// Logger is a wrapper providing logging facilities. -type Logger struct { - x *zap.SugaredLogger -} - -// root logger -var log atomic.Pointer[Logger] - -func GetDefaultLogger() *Logger { - l := log.Load() - if l != nil { - return l - } - // default level: debug - zapLogger, _, err := NewLogger( - Config{ - Environment: EnvironmentDevelopment, - Level: "debug", - Outputs: []string{"stderr"}, - }) - if err != nil { - panic(err) - } - log.Store(&Logger{x: zapLogger}) - return log.Load() -} - -// Init the logger with defined level. outputs defines the outputs where the -// logs will be sent. By default outputs contains "stdout", which prints the -// logs at the output of the process. To add a log file as output, the path -// should be added at the outputs array. To avoid printing the logs but storing -// them on a file, can use []string{"pathtofile.log"} -func Init(cfg Config) { - zapLogger, _, err := NewLogger(cfg) - if err != nil { - panic(err) - } - log.Store(&Logger{x: zapLogger}) -} - -// NewLogger creates the logger with defined level. outputs defines the outputs where the -// logs will be sent. By default, outputs contains "stdout", which prints the -// logs at the output of the process. To add a log file as output, the path -// should be added at the outputs array. To avoid printing the logs but storing -// them on a file, can use []string{"pathtofile.log"} -func NewLogger(cfg Config) (*zap.SugaredLogger, *zap.AtomicLevel, error) { - var level zap.AtomicLevel - err := level.UnmarshalText([]byte(cfg.Level)) - if err != nil { - return nil, nil, fmt.Errorf("error on setting log level: %w", err) - } - - var zapCfg zap.Config - - switch cfg.Environment { - case EnvironmentProduction: - zapCfg = zap.NewProductionConfig() - default: - zapCfg = zap.NewDevelopmentConfig() - zapCfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder - } - zapCfg.Level = level - zapCfg.OutputPaths = cfg.Outputs - zapCfg.InitialFields = map[string]interface{}{ - "version": zkevm.Version, - "pid": os.Getpid(), - } - - logger, err := zapCfg.Build() - if err != nil { - return nil, nil, err - } - defer logger.Sync() //nolint:errcheck - - // skip 2 callers: one for our wrapper methods and one for the package functions - withOptions := logger.WithOptions(zap.AddCallerSkip(2)) //nolint:mnd - return withOptions.Sugar(), &level, nil -} - -// WithFields returns a new Logger (derived from the root one) with additional -// fields as per keyValuePairs. The root Logger instance is not affected. -func WithFields(keyValuePairs ...interface{}) *Logger { - l := GetDefaultLogger().WithFields(keyValuePairs...) - - // since we are returning a new instance, remove one caller from the - // stack, because we'll be calling the retruned Logger methods - // directly, not the package functions. - x := l.x.WithOptions(zap.AddCallerSkip(-1)) - l.x = x - return l -} - -// WithFields returns a new Logger with additional fields as per keyValuePairs. -// The original Logger instance is not affected. -func (l *Logger) WithFields(keyValuePairs ...interface{}) *Logger { - return &Logger{ - x: l.x.With(keyValuePairs...), - } -} - -// GetSugaredLogger is a getter function that returns instance of already built zap.SugaredLogger. -func (l *Logger) GetSugaredLogger() *zap.SugaredLogger { - return l.x -} - -func sprintStackTrace(st []tracerr.Frame) string { - builder := strings.Builder{} - // Skip deepest frame because it belongs to the go runtime and we don't - // care about it. - if len(st) > 0 { - st = st[:len(st)-1] - } - for _, f := range st { - builder.WriteString(fmt.Sprintf("\n%s:%d %s()", f.Path, f.Line, f.Func)) - } - builder.WriteString("\n") - return builder.String() -} - -// appendStackTraceMaybeArgs will append the stacktrace to the args -func appendStackTraceMaybeArgs(args []interface{}) []interface{} { - for i := range args { - if err, ok := args[i].(error); ok { - err = tracerr.Wrap(err) - st := tracerr.StackTrace(err) - return append(args, sprintStackTrace(st)) - } - } - return args -} - -// Debug calls log.Debug -func (l *Logger) Debug(args ...interface{}) { - l.x.Debug(args...) -} - -// Info calls log.Info -func (l *Logger) Info(args ...interface{}) { - l.x.Info(args...) -} - -// Warn calls log.Warn -func (l *Logger) Warn(args ...interface{}) { - l.x.Warn(args...) -} - -// Error calls log.Error -func (l *Logger) Error(args ...interface{}) { - l.x.Error(args...) -} - -// Fatal calls log.Fatal -func (l *Logger) Fatal(args ...interface{}) { - l.x.Fatal(args...) -} - -// Debugf calls log.Debugf -func (l *Logger) Debugf(template string, args ...interface{}) { - l.x.Debugf(template, args...) -} - -// Infof calls log.Infof -func (l *Logger) Infof(template string, args ...interface{}) { - l.x.Infof(template, args...) -} - -// Warnf calls log.Warnf -func (l *Logger) Warnf(template string, args ...interface{}) { - l.x.Warnf(template, args...) -} - -// Fatalf calls log.Fatalf -func (l *Logger) Fatalf(template string, args ...interface{}) { - l.x.Fatalf(template, args...) -} - -// Errorf calls log.Errorf and stores the error message into the ErrorFile -func (l *Logger) Errorf(template string, args ...interface{}) { - l.x.Errorf(template, args...) -} - -// Debug calls log.Debug on the root Logger. -func Debug(args ...interface{}) { - GetDefaultLogger().Debug(args...) -} - -// Info calls log.Info on the root Logger. -func Info(args ...interface{}) { - GetDefaultLogger().Info(args...) -} - -// Warn calls log.Warn on the root Logger. -func Warn(args ...interface{}) { - GetDefaultLogger().Warn(args...) -} - -// Error calls log.Error on the root Logger. -func Error(args ...interface{}) { - args = appendStackTraceMaybeArgs(args) - GetDefaultLogger().Error(args...) -} - -// Fatal calls log.Fatal on the root Logger. -func Fatal(args ...interface{}) { - args = appendStackTraceMaybeArgs(args) - GetDefaultLogger().Fatal(args...) -} - -// Debugf calls log.Debugf on the root Logger. -func Debugf(template string, args ...interface{}) { - GetDefaultLogger().Debugf(template, args...) -} - -// Infof calls log.Infof on the root Logger. -func Infof(template string, args ...interface{}) { - GetDefaultLogger().Infof(template, args...) -} - -// Warnf calls log.Warnf on the root Logger. -func Warnf(template string, args ...interface{}) { - GetDefaultLogger().Warnf(template, args...) -} - -// Fatalf calls log.Fatalf on the root Logger. -func Fatalf(template string, args ...interface{}) { - args = appendStackTraceMaybeArgs(args) - GetDefaultLogger().Fatalf(template, args...) -} - -// Errorf calls log.Errorf on the root logger and stores the error message into -// the ErrorFile. -func Errorf(template string, args ...interface{}) { - args = appendStackTraceMaybeArgs(args) - GetDefaultLogger().Errorf(template, args...) -} - -// Debugw calls log.Debugw -func (l *Logger) Debugw(msg string, kv ...interface{}) { - l.x.Debugw(msg, kv...) -} - -// Infow calls log.Infow -func (l *Logger) Infow(msg string, kv ...interface{}) { - l.x.Infow(msg, kv...) -} - -// Warnw calls log.Warnw -func (l *Logger) Warnw(msg string, kv ...interface{}) { - l.x.Warnw(msg, kv...) -} - -// Errorw calls log.Errorw -func (l *Logger) Errorw(msg string, kv ...interface{}) { - l.x.Errorw(msg, kv...) -} - -// Fatalw calls log.Fatalw -func (l *Logger) Fatalw(msg string, kv ...interface{}) { - l.x.Fatalw(msg, kv...) -} - -// Debugw calls log.Debugw on the root Logger. -func Debugw(msg string, kv ...interface{}) { - GetDefaultLogger().Debugw(msg, kv...) -} - -// Infow calls log.Infow on the root Logger. -func Infow(msg string, kv ...interface{}) { - GetDefaultLogger().Infow(msg, kv...) -} - -// Warnw calls log.Warnw on the root Logger. -func Warnw(msg string, kv ...interface{}) { - GetDefaultLogger().Warnw(msg, kv...) -} - -// Errorw calls log.Errorw on the root Logger. -func Errorw(msg string, kv ...interface{}) { - msg = appendStackTraceMaybeKV(msg, kv) - GetDefaultLogger().Errorw(msg, kv...) -} - -// Fatalw calls log.Fatalw on the root Logger. -func Fatalw(msg string, kv ...interface{}) { - msg = appendStackTraceMaybeKV(msg, kv) - GetDefaultLogger().Fatalw(msg, kv...) -} - -// appendStackTraceMaybeKV will append the stacktrace to the KV -func appendStackTraceMaybeKV(msg string, kv []interface{}) string { - for i := range kv { - if i%2 == 0 { - continue - } - if err, ok := kv[i].(error); ok { - err = tracerr.Wrap(err) - st := tracerr.StackTrace(err) - return fmt.Sprintf("%v: %v%v\n", msg, err, sprintStackTrace(st)) - } - } - return msg -} - -func (l *Logger) IsEnabledLogLevel(lvl zapcore.Level) bool { - return l.x.Level().Enabled(lvl) -} diff --git a/log/log_test.go b/log/log_test.go deleted file mode 100644 index 9a596608d..000000000 --- a/log/log_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package log - -import ( - "testing" -) - -func TestLogNotInitialized(t *testing.T) { - Info("Test log.Info", " value is ", 10) - Infof("Test log.Infof %d", 10) - Infow("Test log.Infow", "value", 10) - Debugf("Test log.Debugf %d", 10) - Error("Test log.Error", " value is ", 10) - Errorf("Test log.Errorf %d", 10) - Errorw("Test log.Errorw", "value", 10) - Warnf("Test log.Warnf %d", 10) - Warnw("Test log.Warnw", "value", 10) -} - -func TestLog(t *testing.T) { - cfg := Config{ - Environment: EnvironmentDevelopment, - Level: "debug", - Outputs: []string{"stderr"}, // []string{"stdout", "test.log"} - } - - Init(cfg) - - Info("Test log.Info", " value is ", 10) - Infof("Test log.Infof %d", 10) - Infow("Test log.Infow", "value", 10) - Debugf("Test log.Debugf %d", 10) - Error("Test log.Error", " value is ", 10) - Errorf("Test log.Errorf %d", 10) - Errorw("Test log.Errorw", "value", 10) - Warnf("Test log.Warnf %d", 10) - Warnw("Test log.Warnw", "value", 10) -} diff --git a/logerror b/logerror deleted file mode 100644 index cf3e44c15..000000000 --- a/logerror +++ /dev/null @@ -1 +0,0 @@ -ok github.com/0xPolygon/cdk/l1infotreesync 2.438s diff --git a/merkletree/key.go b/merkletree/key.go deleted file mode 100644 index 7926df60a..000000000 --- a/merkletree/key.go +++ /dev/null @@ -1,207 +0,0 @@ -package merkletree - -import ( - "math" - "math/big" - - "github.com/ethereum/go-ethereum/common" - poseidon "github.com/iden3/go-iden3-crypto/goldenposeidon" -) - -// Key stores key of the leaf -type Key [32]byte - -const ( - // HashPoseidonAllZeroes represents the poseidon hash for an input with all - // bits set to zero. - HashPoseidonAllZeroes = "0xc71603f33a1144ca7953db0ab48808f4c4055e3364a246c33c18a9786cb0b359" -) - -// keyEthAddr is the common code for all the keys related to ethereum addresses. -func keyEthAddr(ethAddr common.Address, leafType leafType, key1Capacity [4]uint64) ([]byte, error) { - ethAddrBI := new(big.Int).SetBytes(ethAddr.Bytes()) - ethAddrArr := scalar2fea(ethAddrBI) - - key1 := [8]uint64{ - ethAddrArr[0], - ethAddrArr[1], - ethAddrArr[2], - ethAddrArr[3], - ethAddrArr[4], - 0, - uint64(leafType), - 0, - } - - result, err := poseidon.Hash(key1, key1Capacity) - if err != nil { - return nil, err - } - - return h4ToFilledByteSlice(result[:]), nil -} - -func defaultCapIn() ([4]uint64, error) { - capIn, err := StringToh4(HashPoseidonAllZeroes) - if err != nil { - return [4]uint64{}, err - } - - return [4]uint64{capIn[0], capIn[1], capIn[2], capIn[3]}, nil -} - -// KeyEthAddrBalance returns the key of balance leaf: -// hk0: H([0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0]) -// key: H([ethAddr[0:4], ethAddr[4:8], ethAddr[8:12], ethAddr[12:16], ethAddr[16:20], 0, 0, 0], -// [hk0[0], hk0[1], hk0[2], hk0[3]]) -func KeyEthAddrBalance(ethAddr common.Address) ([]byte, error) { - capIn, err := defaultCapIn() - if err != nil { - return nil, err - } - - return keyEthAddr(ethAddr, LeafTypeBalance, capIn) -} - -// KeyEthAddrNonce returns the key of nonce leaf: -// hk0: H([0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0]) -// key: H([ethAddr[0:4], ethAddr[4:8], ethAddr[8:12], ethAddr[12:16], ethAddr[16:20], 0, 1, 0], -// [hk0[0], hk0[1], hk0[2], hk0[3]] -func KeyEthAddrNonce(ethAddr common.Address) ([]byte, error) { - capIn, err := defaultCapIn() - if err != nil { - return nil, err - } - - return keyEthAddr(ethAddr, LeafTypeNonce, capIn) -} - -// KeyContractCode returns the key of contract code leaf: -// hk0: H([0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0]) -// key: H([ethAddr[0:4], ethAddr[4:8], ethAddr[8:12], ethAddr[12:16], ethAddr[16:20], 0, 2, 0], -// [hk0[0], hk0[1], hk0[2], hk0[3]] -func KeyContractCode(ethAddr common.Address) ([]byte, error) { - capIn, err := defaultCapIn() - if err != nil { - return nil, err - } - - return keyEthAddr(ethAddr, LeafTypeCode, capIn) -} - -// KeyContractStorage returns the key of contract storage position leaf: -// hk0: H([stoPos[0:4], stoPos[4:8], stoPos[8:12], stoPos[12:16], stoPos[16:20], stoPos[20:24], -// stoPos[24:28], stoPos[28:32], [0, 0, 0, 0]) -// key: H([ethAddr[0:4], ethAddr[4:8], ethAddr[8:12], ethAddr[12:16], ethAddr[16:20], 0, 3, 0], -// [hk0[0], hk0[1], hk0[2], hk0[3]) -func KeyContractStorage(ethAddr common.Address, storagePos []byte) ([]byte, error) { - storageBI := new(big.Int).SetBytes(storagePos) - - storageArr := scalar2fea(storageBI) - - hk0, err := poseidon.Hash([8]uint64{ - storageArr[0], - storageArr[1], - storageArr[2], - storageArr[3], - storageArr[4], - storageArr[5], - storageArr[6], - storageArr[7], - }, [4]uint64{}) - if err != nil { - return nil, err - } - - return keyEthAddr(ethAddr, LeafTypeStorage, hk0) -} - -// HashContractBytecode computes the bytecode hash in order to add it to the -// state-tree. -func HashContractBytecode(code []byte) ([]uint64, error) { - const ( - bytecodeElementsHash = 8 - bytecodeBytesElement = 7 - - maxBytesToAdd = bytecodeElementsHash * bytecodeBytesElement - ) - - // add 0x01 - code = append(code, 0x01) //nolint:mnd - - // add padding - for len(code)%(56) != 0 { - code = append(code, 0x00) //nolint:mnd - } - - code[len(code)-1] = code[len(code)-1] | 0x80 //nolint:mnd - - numHashes := int(math.Ceil(float64(len(code)) / float64(maxBytesToAdd))) - - tmpHash := [4]uint64{} - var err error - - bytesPointer := 0 - for i := 0; i < numHashes; i++ { - elementsToHash := [12]uint64{} - - for j := 0; j < 4; j++ { - elementsToHash[j] = tmpHash[j] - } - - subsetBytecode := code[bytesPointer : int(math.Min(float64(len(code)-1), float64(bytesPointer+maxBytesToAdd)))+1] - bytesPointer += maxBytesToAdd - tmpElem := [7]byte{} - counter := 0 - index := 4 - for j := 0; j < maxBytesToAdd; j++ { - byteToAdd := []byte{0} - - if j < len(subsetBytecode) { - byteToAdd = subsetBytecode[j : j+1] - } - - tmpElem[bytecodeBytesElement-1-counter] = byteToAdd[0] - counter++ - - if counter == bytecodeBytesElement { - elementsToHash[index] = new(big.Int).SetBytes(tmpElem[:]).Uint64() - index++ - tmpElem = [7]byte{} - counter = 0 - } - } - tmpHash, err = poseidon.Hash([8]uint64{ - elementsToHash[4], - elementsToHash[5], - elementsToHash[6], - elementsToHash[7], - elementsToHash[8], - elementsToHash[9], - elementsToHash[10], - elementsToHash[11], - }, [4]uint64{ - elementsToHash[0], - elementsToHash[1], - elementsToHash[2], - elementsToHash[3], - }) - if err != nil { - return nil, err - } - } - return tmpHash[:], nil -} - -// KeyCodeLength returns the key of code length leaf: -// hk0: H([0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0]) -// key: H([ethAddr[0:4], ethAddr[4:8], ethAddr[8:12], ethAddr[12:16], ethAddr[16:20], 0, 4, 0], -// [hk0[0], hk0[1], hk0[2], hk0[3]] -func KeyCodeLength(ethAddr common.Address) ([]byte, error) { - capIn, err := defaultCapIn() - if err != nil { - return nil, err - } - - return keyEthAddr(ethAddr, LeafTypeSCLength, capIn) -} diff --git a/merkletree/key_test.go b/merkletree/key_test.go deleted file mode 100644 index fab056f95..000000000 --- a/merkletree/key_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package merkletree - -import ( - "encoding/hex" - "encoding/json" - "fmt" - "math/big" - "os" - "path" - "runtime" - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" -) - -type testVectorKey struct { - EthAddr string `json:"ethAddr"` - StoragePosition string `json:"storagePosition"` - ExpectedKey string `json:"expectedKey"` -} - -type bytecodeTest struct { - Bytecode string `json:"bytecode"` - ExpectedHash string `json:"expectedHash"` -} - -func init() { - // Change dir to project root - // This is important because we have relative paths to files containing test vectors - _, filename, _, _ := runtime.Caller(0) //nolint:dogsled - dir := path.Join(path.Dir(filename), "../") - - if err := os.Chdir(dir); err != nil { - panic(err) - } -} - -func Test_CommonKeys(t *testing.T) { - tcs := []struct { - description string - testVectorFile string - keyFunc func(common.Address) ([]byte, error) - }{ - { - description: "keyEthAddressBalance", - testVectorFile: "test/vectors/src/merkle-tree/smt-key-eth-balance.json", - keyFunc: KeyEthAddrBalance, - }, - { - description: "keyEthAddressNonce", - testVectorFile: "test/vectors/src/merkle-tree/smt-key-eth-nonce.json", - keyFunc: KeyEthAddrNonce, - }, - { - description: "keyContractCode", - testVectorFile: "test/vectors/src/merkle-tree/smt-key-contract-code.json", - keyFunc: KeyContractCode, - }, - { - description: "keyCodeLength", - testVectorFile: "test/vectors/src/merkle-tree/smt-key-contract-length.json", - keyFunc: KeyCodeLength, - }, - } - for _, tc := range tcs { - tc := tc - - data, err := os.ReadFile(tc.testVectorFile) - require.NoError(t, err) - - var testVectors []testVectorKey - err = json.Unmarshal(data, &testVectors) - require.NoError(t, err) - - for ti, testVector := range testVectors { - t.Run(fmt.Sprintf("%s, test vector %d", tc.description, ti), func(t *testing.T) { - key, err := tc.keyFunc(common.HexToAddress(testVector.EthAddr)) - require.NoError(t, err) - require.Equal(t, len(key), maxBigIntLen) - - expected, _ := new(big.Int).SetString(testVector.ExpectedKey, 10) - assert.Equal(t, hex.EncodeToString(expected.Bytes()), hex.EncodeToString(key)) - }) - } - } -} - -func Test_KeyContractStorage(t *testing.T) { - data, err := os.ReadFile("test/vectors/src/merkle-tree/smt-key-contract-storage.json") - require.NoError(t, err) - - var testVectors []testVectorKey - err = json.Unmarshal(data, &testVectors) - require.NoError(t, err) - - for ti, testVector := range testVectors { - t.Run(fmt.Sprintf("Test vector %d", ti), func(t *testing.T) { - storagePosition, ok := new(big.Int).SetString(testVector.StoragePosition, 10) - require.True(t, ok) - key, err := KeyContractStorage(common.HexToAddress(testVector.EthAddr), storagePosition.Bytes()) - require.NoError(t, err) - require.Equal(t, len(key), maxBigIntLen) - - expected, _ := new(big.Int).SetString(testVector.ExpectedKey, 10) - assert.Equal(t, hex.EncodeToString(expected.Bytes()), hex.EncodeToString(key)) - }) - } -} - -func Test_byteCodeHash(t *testing.T) { - data, err := os.ReadFile("test/vectors/src/merkle-tree/smt-hash-bytecode.json") - require.NoError(t, err) - - var testVectors []bytecodeTest - err = json.Unmarshal(data, &testVectors) - require.NoError(t, err) - - for ti, testVector := range testVectors { - t.Run(fmt.Sprintf("Test vector %d", ti), func(t *testing.T) { - hash, err := HashContractBytecode(common.Hex2Bytes(testVector.Bytecode)) - require.NoError(t, err) - assert.Equal(t, common.HexToHash(testVector.ExpectedHash), common.HexToHash(H4ToString(hash))) - }) - } -} diff --git a/merkletree/leaf.go b/merkletree/leaf.go deleted file mode 100644 index 5321f69ac..000000000 --- a/merkletree/leaf.go +++ /dev/null @@ -1,17 +0,0 @@ -package merkletree - -// leafType specifies type of the leaf -type leafType uint8 - -const ( - // LeafTypeBalance specifies that leaf stores Balance - LeafTypeBalance leafType = 0 - // LeafTypeNonce specifies that leaf stores Nonce - LeafTypeNonce leafType = 1 - // LeafTypeCode specifies that leaf stores Code - LeafTypeCode leafType = 2 - // LeafTypeStorage specifies that leaf stores Storage Value - LeafTypeStorage leafType = 3 - // LeafTypeSCLength specifies that leaf stores Storage Value - LeafTypeSCLength leafType = 4 -) diff --git a/merkletree/split.go b/merkletree/split.go deleted file mode 100644 index e264807a5..000000000 --- a/merkletree/split.go +++ /dev/null @@ -1,96 +0,0 @@ -package merkletree - -import ( - "encoding/binary" - "fmt" - "math/big" - "strings" - - "github.com/0xPolygon/cdk/hex" -) - -// maxBigIntLen is 256 bits (32 bytes) -const maxBigIntLen = 32 - -// wordLength is the number of bits of each ff limb -const wordLength = 64 - -// scalar2fea splits a *big.Int into array of 32bit uint64 values. -func scalar2fea(value *big.Int) []uint64 { - val := make([]uint64, 8) //nolint:mnd - mask, _ := new(big.Int).SetString("FFFFFFFF", 16) //nolint:mnd - val[0] = new(big.Int).And(value, mask).Uint64() - val[1] = new(big.Int).And(new(big.Int).Rsh(value, 32), mask).Uint64() //nolint:mnd - val[2] = new(big.Int).And(new(big.Int).Rsh(value, 64), mask).Uint64() //nolint:mnd - val[3] = new(big.Int).And(new(big.Int).Rsh(value, 96), mask).Uint64() //nolint:mnd - val[4] = new(big.Int).And(new(big.Int).Rsh(value, 128), mask).Uint64() //nolint:mnd - val[5] = new(big.Int).And(new(big.Int).Rsh(value, 160), mask).Uint64() //nolint:mnd - val[6] = new(big.Int).And(new(big.Int).Rsh(value, 192), mask).Uint64() //nolint:mnd - val[7] = new(big.Int).And(new(big.Int).Rsh(value, 224), mask).Uint64() //nolint:mnd - return val -} - -// h4ToScalar converts array of 4 uint64 into a unique 256 bits scalar. -func h4ToScalar(h4 []uint64) *big.Int { - if len(h4) == 0 { - return new(big.Int) - } - result := new(big.Int).SetUint64(h4[0]) - - for i := 1; i < 4; i++ { - b2 := new(big.Int).SetUint64(h4[i]) - b2.Lsh(b2, uint(wordLength*i)) - result = result.Add(result, b2) - } - - return result -} - -// H4ToString converts array of 4 Scalars of 64 bits into an hex string. -func H4ToString(h4 []uint64) string { - sc := h4ToScalar(h4) - - return fmt.Sprintf("0x%064s", hex.EncodeToString(sc.Bytes())) -} - -// StringToh4 converts an hex string into array of 4 Scalars of 64 bits. -func StringToh4(str string) ([]uint64, error) { - str = strings.TrimPrefix(str, "0x") - - bi, ok := new(big.Int).SetString(str, hex.Base) - if !ok { - return nil, fmt.Errorf("could not convert %q into big int", str) - } - - return scalarToh4(bi), nil -} - -// scalarToh4 converts a *big.Int into an array of 4 uint64 -func scalarToh4(s *big.Int) []uint64 { - b := ScalarToFilledByteSlice(s) - - r := make([]uint64, 4) //nolint:mnd - - f, _ := hex.DecodeHex("0xFFFFFFFFFFFFFFFF") - fbe := binary.BigEndian.Uint64(f) - - r[3] = binary.BigEndian.Uint64(b[0:8]) & fbe - r[2] = binary.BigEndian.Uint64(b[8:16]) & fbe - r[1] = binary.BigEndian.Uint64(b[16:24]) & fbe - r[0] = binary.BigEndian.Uint64(b[24:]) & fbe - - return r -} - -// ScalarToFilledByteSlice converts a *big.Int into an array of maxBigIntLen -// bytes. -func ScalarToFilledByteSlice(s *big.Int) []byte { - buf := make([]byte, maxBigIntLen) - return s.FillBytes(buf) -} - -// h4ToFilledByteSlice converts an array of 4 uint64 into an array of -// maxBigIntLen bytes. -func h4ToFilledByteSlice(h4 []uint64) []byte { - return ScalarToFilledByteSlice(h4ToScalar(h4)) -} diff --git a/merkletree/split_test.go b/merkletree/split_test.go deleted file mode 100644 index eff615db7..000000000 --- a/merkletree/split_test.go +++ /dev/null @@ -1,276 +0,0 @@ -package merkletree - -import ( - "fmt" - "math/big" - "reflect" - "testing" - - "github.com/0xPolygon/cdk/hex" - "github.com/0xPolygon/cdk/test/testutils" - "github.com/stretchr/testify/require" -) - -func TestScalar2Fea(t *testing.T) { - tests := []struct { - name string - input string - expected []uint64 - }{ - { - name: "Zero value", - input: "0", - expected: []uint64{0, 0, 0, 0, 0, 0, 0, 0}, - }, - { - name: "Single 32-bit value", - input: "FFFFFFFF", - expected: []uint64{0xFFFFFFFF, 0, 0, 0, 0, 0, 0, 0}, - }, - { - name: "Mixed bits across chunks (128-bit)", - input: "1234567890ABCDEF1234567890ABCDEF", - expected: []uint64{0x90ABCDEF, 0x12345678, 0x90ABCDEF, 0x12345678, 0, 0, 0, 0}, - }, - { - name: "All bits set in each 32-bit chunk (256-bit)", - input: "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", - expected: []uint64{0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF}, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - inputVal, success := new(big.Int).SetString(tt.input, 16) - if !success { - t.Fatalf("Invalid input value: %s", tt.input) - } - - result := scalar2fea(inputVal) - - if !reflect.DeepEqual(result, tt.expected) { - t.Errorf("scalar2fea(%s) = %v, want %v", tt.input, result, tt.expected) - } - }) - } -} - -func Test_h4ToScalar(t *testing.T) { - tcs := []struct { - input []uint64 - expected string - }{ - { - input: []uint64{0, 0, 0, 0}, - expected: "0", - }, - { - input: []uint64{0, 1, 2, 3}, - expected: "18831305206160042292187933003464876175252262292329349513216", - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - actual := h4ToScalar(tc.input) - expected, ok := new(big.Int).SetString(tc.expected, 10) - require.True(t, ok) - require.Equal(t, expected, actual) - }) - } -} - -func Test_scalarToh4(t *testing.T) { - tcs := []struct { - input string - expected []uint64 - }{ - { - input: "0", - expected: []uint64{0, 0, 0, 0}, - }, - { - input: "18831305206160042292187933003464876175252262292329349513216", - expected: []uint64{0, 1, 2, 3}, - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - bi, ok := new(big.Int).SetString(tc.input, 10) - require.True(t, ok) - - actual := scalarToh4(bi) - require.Equal(t, tc.expected, actual) - }) - } -} - -func Test_h4ToString(t *testing.T) { - tcs := []struct { - input []uint64 - expected string - }{ - { - input: []uint64{0, 0, 0, 0}, - expected: "0x0000000000000000000000000000000000000000000000000000000000000000", - }, - { - input: []uint64{0, 1, 2, 3}, - expected: "0x0000000000000003000000000000000200000000000000010000000000000000", - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - actual := H4ToString(tc.input) - require.Equal(t, tc.expected, actual) - }) - } -} - -func Test_Conversions(t *testing.T) { - tcs := []struct { - input []uint64 - }{ - { - input: []uint64{0, 0, 0, 0}, - }, - { - input: []uint64{0, 1, 2, 3}, - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("case %d", i), func(t *testing.T) { - resScalar := h4ToScalar(tc.input) - init := scalarToh4(resScalar) - require.Equal(t, tc.input, init) - }) - } -} - -func Test_stringToh4(t *testing.T) { - tcs := []struct { - description string - input string - expected []uint64 - expectedErr bool - expectedErrMsg string - }{ - { - description: "happy path", - input: "cafe", - expected: []uint64{51966, 0, 0, 0}, - }, - { - description: "0x prefix is allowed", - input: "0xcafe", - expected: []uint64{51966, 0, 0, 0}, - }, - - { - description: "non hex input causes error", - input: "yu74", - expectedErr: true, - expectedErrMsg: "could not convert \"yu74\" into big int", - }, - { - description: "empty input causes error", - input: "", - expectedErr: true, - expectedErrMsg: "could not convert \"\" into big int", - }, - } - - for _, tc := range tcs { - tc := tc - t.Run(tc.description, func(t *testing.T) { - actual, err := StringToh4(tc.input) - require.NoError(t, testutils.CheckError(err, tc.expectedErr, tc.expectedErrMsg)) - - require.Equal(t, tc.expected, actual) - }) - } -} - -func Test_ScalarToFilledByteSlice(t *testing.T) { - tcs := []struct { - input string - expected string - }{ - { - input: "0", - expected: "0x0000000000000000000000000000000000000000000000000000000000000000", - }, - { - input: "256", - expected: "0x0000000000000000000000000000000000000000000000000000000000000100", - }, - { - input: "235938498573495379548793890390932048239042839490238", - expected: "0x0000000000000000000000a16f882ee8972432c0a71c5e309ad5f7215690aebe", - }, - { - input: "4309593458485959083095843905390485089430985490434080439904305093450934509490", - expected: "0x098724b9a1bc97eee674cf5b6b56b8fafd83ac49c3da1f2c87c822548bbfdfb2", - }, - { - input: "98999023430240239049320492430858334093493024832984092384902398409234090932489", - expected: "0xdadf762a31e865f150a1456d7db7963c91361b771c8381a3fb879cf5bf91b909", - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("test case %d", i), func(t *testing.T) { - input, ok := big.NewInt(0).SetString(tc.input, 10) - require.True(t, ok) - - actualSlice := ScalarToFilledByteSlice(input) - - actual := hex.EncodeToHex(actualSlice) - - require.Equal(t, tc.expected, actual) - }) - } -} - -func Test_h4ToFilledByteSlice(t *testing.T) { - tcs := []struct { - input []uint64 - expected string - }{ - { - input: []uint64{0, 0, 0, 0}, - expected: "0x0000000000000000000000000000000000000000000000000000000000000000", - }, - { - input: []uint64{0, 1, 2, 3}, - expected: "0x0000000000000003000000000000000200000000000000010000000000000000", - }, - { - input: []uint64{55345354959, 991992992929, 2, 3}, - expected: "0x00000000000000030000000000000002000000e6f763d4a10000000ce2d718cf", - }, - { - input: []uint64{8398349845894398543, 3485942349435495945, 734034022234249459, 5490434584389534589}, - expected: "0x4c31f12a390ec37d0a2fd00ddc52d8f330608e18f597e609748ceeb03ffe024f", - }, - } - - for i, tc := range tcs { - tc := tc - t.Run(fmt.Sprintf("test case %d", i), func(t *testing.T) { - actualSlice := h4ToFilledByteSlice(tc.input) - - actual := hex.EncodeToHex(actualSlice) - - require.Equal(t, tc.expected, actual) - }) - } -} diff --git a/reorgdetector/config.go b/reorgdetector/config.go deleted file mode 100644 index c9a904153..000000000 --- a/reorgdetector/config.go +++ /dev/null @@ -1,29 +0,0 @@ -package reorgdetector - -import ( - "time" - - "github.com/0xPolygon/cdk/config/types" -) - -const ( - defaultCheckReorgsInterval = 2 * time.Second -) - -// Config is the configuration for the reorg detector -type Config struct { - // DBPath is the path to the database - DBPath string `mapstructure:"DBPath"` - - // CheckReorgsInterval is the interval to check for reorgs in tracked blocks - CheckReorgsInterval types.Duration `mapstructure:"CheckReorgsInterval"` -} - -// GetCheckReorgsInterval returns the interval to check for reorgs in tracked blocks -func (c *Config) GetCheckReorgsInterval() time.Duration { - if c.CheckReorgsInterval.Duration == 0 { - return defaultCheckReorgsInterval - } - - return c.CheckReorgsInterval.Duration -} diff --git a/reorgdetector/migrations/migrations.go b/reorgdetector/migrations/migrations.go deleted file mode 100644 index ba619cde6..000000000 --- a/reorgdetector/migrations/migrations.go +++ /dev/null @@ -1,21 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" -) - -//go:embed reorgdetector0001.sql -var mig001 string - -func RunMigrations(dbPath string) error { - migrations := []types.Migration{ - { - ID: "reorgdetector0001", - SQL: mig001, - }, - } - return db.RunMigrations(dbPath, migrations) -} diff --git a/reorgdetector/migrations/reorgdetector0001.sql b/reorgdetector/migrations/reorgdetector0001.sql deleted file mode 100644 index 8b5092baf..000000000 --- a/reorgdetector/migrations/reorgdetector0001.sql +++ /dev/null @@ -1,11 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS block; -DROP TABLE IF EXISTS claim; -DROP TABLE IF EXISTS bridge; - --- +migrate Up -CREATE TABLE tracked_block ( - subscriber_id VARCHAR NOT NULL, - num BIGINT NOT NULL, - hash VARCHAR NOT NULL -); \ No newline at end of file diff --git a/reorgdetector/mock_eth_client.go b/reorgdetector/mock_eth_client.go deleted file mode 100644 index 1a42104be..000000000 --- a/reorgdetector/mock_eth_client.go +++ /dev/null @@ -1,220 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package reorgdetector - -import ( - context "context" - big "math/big" - - common "github.com/ethereum/go-ethereum/common" - - ethereum "github.com/ethereum/go-ethereum" - - mock "github.com/stretchr/testify/mock" - - types "github.com/ethereum/go-ethereum/core/types" -) - -// EthClientMock is an autogenerated mock type for the EthClient type -type EthClientMock struct { - mock.Mock -} - -type EthClientMock_Expecter struct { - mock *mock.Mock -} - -func (_m *EthClientMock) EXPECT() *EthClientMock_Expecter { - return &EthClientMock_Expecter{mock: &_m.Mock} -} - -// HeaderByHash provides a mock function with given fields: ctx, hash -func (_m *EthClientMock) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for HeaderByHash") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Header, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Header); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClientMock_HeaderByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByHash' -type EthClientMock_HeaderByHash_Call struct { - *mock.Call -} - -// HeaderByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *EthClientMock_Expecter) HeaderByHash(ctx interface{}, hash interface{}) *EthClientMock_HeaderByHash_Call { - return &EthClientMock_HeaderByHash_Call{Call: _e.mock.On("HeaderByHash", ctx, hash)} -} - -func (_c *EthClientMock_HeaderByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *EthClientMock_HeaderByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *EthClientMock_HeaderByHash_Call) Return(_a0 *types.Header, _a1 error) *EthClientMock_HeaderByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClientMock_HeaderByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Header, error)) *EthClientMock_HeaderByHash_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByNumber provides a mock function with given fields: ctx, number -func (_m *EthClientMock) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for HeaderByNumber") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClientMock_HeaderByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByNumber' -type EthClientMock_HeaderByNumber_Call struct { - *mock.Call -} - -// HeaderByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *EthClientMock_Expecter) HeaderByNumber(ctx interface{}, number interface{}) *EthClientMock_HeaderByNumber_Call { - return &EthClientMock_HeaderByNumber_Call{Call: _e.mock.On("HeaderByNumber", ctx, number)} -} - -func (_c *EthClientMock_HeaderByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *EthClientMock_HeaderByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *EthClientMock_HeaderByNumber_Call) Return(_a0 *types.Header, _a1 error) *EthClientMock_HeaderByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClientMock_HeaderByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Header, error)) *EthClientMock_HeaderByNumber_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeNewHead provides a mock function with given fields: ctx, ch -func (_m *EthClientMock) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { - ret := _m.Called(ctx, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeNewHead") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)); ok { - return rf(ctx, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) ethereum.Subscription); ok { - r0 = rf(ctx, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, chan<- *types.Header) error); ok { - r1 = rf(ctx, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// EthClientMock_SubscribeNewHead_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeNewHead' -type EthClientMock_SubscribeNewHead_Call struct { - *mock.Call -} - -// SubscribeNewHead is a helper method to define mock.On call -// - ctx context.Context -// - ch chan<- *types.Header -func (_e *EthClientMock_Expecter) SubscribeNewHead(ctx interface{}, ch interface{}) *EthClientMock_SubscribeNewHead_Call { - return &EthClientMock_SubscribeNewHead_Call{Call: _e.mock.On("SubscribeNewHead", ctx, ch)} -} - -func (_c *EthClientMock_SubscribeNewHead_Call) Run(run func(ctx context.Context, ch chan<- *types.Header)) *EthClientMock_SubscribeNewHead_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(chan<- *types.Header)) - }) - return _c -} - -func (_c *EthClientMock_SubscribeNewHead_Call) Return(_a0 ethereum.Subscription, _a1 error) *EthClientMock_SubscribeNewHead_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EthClientMock_SubscribeNewHead_Call) RunAndReturn(run func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)) *EthClientMock_SubscribeNewHead_Call { - _c.Call.Return(run) - return _c -} - -// NewEthClientMock creates a new instance of EthClientMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEthClientMock(t interface { - mock.TestingT - Cleanup(func()) -}) *EthClientMock { - mock := &EthClientMock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/reorgdetector/reorgdetector.go b/reorgdetector/reorgdetector.go deleted file mode 100644 index a25495914..000000000 --- a/reorgdetector/reorgdetector.go +++ /dev/null @@ -1,227 +0,0 @@ -package reorgdetector - -import ( - "context" - "database/sql" - "fmt" - "math/big" - "sync" - "time" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/reorgdetector/migrations" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/rpc" - "golang.org/x/sync/errgroup" -) - -type Network string - -const ( - L1 Network = "l1" - L2 Network = "l2" -) - -func (n Network) String() string { - return string(n) -} - -type EthClient interface { - SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) - HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) - HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) -} - -type ReorgDetector struct { - client EthClient - db *sql.DB - checkReorgInterval time.Duration - - trackedBlocksLock sync.RWMutex - trackedBlocks map[string]*headersList - - subscriptionsLock sync.RWMutex - subscriptions map[string]*Subscription - - log *log.Logger -} - -func New(client EthClient, cfg Config, network Network) (*ReorgDetector, error) { - err := migrations.RunMigrations(cfg.DBPath) - if err != nil { - return nil, err - } - db, err := db.NewSQLiteDB(cfg.DBPath) - if err != nil { - return nil, err - } - - return &ReorgDetector{ - client: client, - db: db, - checkReorgInterval: cfg.GetCheckReorgsInterval(), - trackedBlocks: make(map[string]*headersList), - subscriptions: make(map[string]*Subscription), - log: log.WithFields("reorg-detector", network.String()), - }, nil -} - -// Start starts the reorg detector -func (rd *ReorgDetector) Start(ctx context.Context) (err error) { - // Load tracked blocks from the DB - if err = rd.loadTrackedHeaders(); err != nil { - return fmt.Errorf("failed to load tracked headers: %w", err) - } - - // Continuously check reorgs in tracked by subscribers blocks - go func() { - ticker := time.NewTicker(rd.checkReorgInterval) - for { - select { - case <-ctx.Done(): - ticker.Stop() - return - case <-ticker.C: - if err = rd.detectReorgInTrackedList(ctx); err != nil { - log.Errorf("failed to detect reorg in tracked list: %v", err) - } - } - } - }() - - return nil -} - -// AddBlockToTrack adds a block to the tracked list for a subscriber -func (rd *ReorgDetector) AddBlockToTrack(ctx context.Context, id string, num uint64, hash common.Hash) error { - // Skip if the given block has already been stored - rd.trackedBlocksLock.RLock() - trackedBlocks, ok := rd.trackedBlocks[id] - if !ok { - rd.trackedBlocksLock.RUnlock() - return fmt.Errorf("subscriber %s is not subscribed", id) - } - rd.trackedBlocksLock.RUnlock() - - if existingHeader, err := trackedBlocks.get(num); err == nil && existingHeader.Hash == hash { - return nil - } - - // Store the given header to the tracked list - hdr := newHeader(num, hash) - if err := rd.saveTrackedBlock(id, hdr); err != nil { - return fmt.Errorf("failed to save tracked block: %w", err) - } - - return nil -} - -// detectReorgInTrackedList detects reorgs in the tracked blocks. -// Notifies subscribers if reorg has happened -func (rd *ReorgDetector) detectReorgInTrackedList(ctx context.Context) error { - // Get the latest finalized block - lastFinalisedBlock, err := rd.client.HeaderByNumber(ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))) - if err != nil { - return fmt.Errorf("failed to get the latest finalized block: %w", err) - } - - var ( - headersCacheLock sync.Mutex - headersCache = map[uint64]*types.Header{ - lastFinalisedBlock.Number.Uint64(): lastFinalisedBlock, - } - errGroup errgroup.Group - ) - - subscriberIDs := rd.getSubscriberIDs() - - for _, id := range subscriberIDs { - id := id - - // This is done like this because of a possible deadlock - // between AddBlocksToTrack and detectReorgInTrackedList - rd.trackedBlocksLock.RLock() - hdrs, ok := rd.trackedBlocks[id] - rd.trackedBlocksLock.RUnlock() - - if !ok { - continue - } - - rd.log.Debugf("Checking reorgs in tracked blocks up to block %d", lastFinalisedBlock.Number.Uint64()) - - errGroup.Go(func() error { - headers := hdrs.getSorted() - for _, hdr := range headers { - // Get the actual header from the network or from the cache - var err error - headersCacheLock.Lock() - currentHeader, ok := headersCache[hdr.Num] - if !ok || currentHeader == nil { - if currentHeader, err = rd.client.HeaderByNumber(ctx, new(big.Int).SetUint64(hdr.Num)); err != nil { - headersCacheLock.Unlock() - return fmt.Errorf("failed to get the header %d: %w", hdr.Num, err) - } - headersCache[hdr.Num] = currentHeader - } - headersCacheLock.Unlock() - - // Check if the block hash matches with the actual block hash - if hdr.Hash == currentHeader.Hash() { - // Delete block from the tracked blocks list if it is less than or equal to the last finalized block - // and hashes matches. If higher than finalized block, we assume a reorg still might happen. - if hdr.Num <= lastFinalisedBlock.Number.Uint64() { - hdrs.removeRange(hdr.Num, hdr.Num) - - if err := rd.removeTrackedBlockRange(id, hdr.Num, hdr.Num); err != nil { - return fmt.Errorf("error removing blocks from DB for subscriber %s between blocks %d and %d: %w", - id, hdr.Num, hdr.Num, err) - } - } - - continue - } - - // Notify the subscriber about the reorg - rd.notifySubscriber(id, hdr) - - // Remove the reorged block and all the following blocks from DB - if err := rd.removeTrackedBlockRange(id, hdr.Num, headers[len(headers)-1].Num); err != nil { - return fmt.Errorf("error removing blocks from DB for subscriber %s between blocks %d and %d: %w", - id, hdr.Num, headers[len(headers)-1].Num, err) - } - // Remove the reorged block and all the following blocks from memory - hdrs.removeRange(hdr.Num, headers[len(headers)-1].Num) - - break - } - return nil - }) - } - - return errGroup.Wait() -} - -// loadTrackedHeaders loads tracked headers from the DB and stores them in memory -func (rd *ReorgDetector) loadTrackedHeaders() (err error) { - rd.trackedBlocksLock.Lock() - defer rd.trackedBlocksLock.Unlock() - - // Load tracked blocks for all subscribers from the DB - if rd.trackedBlocks, err = rd.getTrackedBlocks(); err != nil { - return fmt.Errorf("failed to get tracked blocks: %w", err) - } - - // Go over tracked blocks and create subscription for each tracker - for id := range rd.trackedBlocks { - rd.subscriptions[id] = &Subscription{ - ReorgedBlock: make(chan uint64), - ReorgProcessed: make(chan bool), - } - } - - return nil -} diff --git a/reorgdetector/reorgdetector_db.go b/reorgdetector/reorgdetector_db.go deleted file mode 100644 index 72bc40a7c..000000000 --- a/reorgdetector/reorgdetector_db.go +++ /dev/null @@ -1,80 +0,0 @@ -package reorgdetector - -import ( - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/russross/meddler" -) - -// getTrackedBlocks returns a list of tracked blocks for each subscriber from db -func (rd *ReorgDetector) getTrackedBlocks() (map[string]*headersList, error) { - trackedBlocks := make(map[string]*headersList, 0) - var headersWithID []*headerWithSubscriberID - err := meddler.QueryAll(rd.db, &headersWithID, "SELECT * FROM tracked_block ORDER BY subscriber_id;") - if err != nil { - if errors.Is(err, db.ErrNotFound) { - return trackedBlocks, nil - } - return nil, fmt.Errorf("error queryng tracked_block: %w", err) - } - if len(headersWithID) == 0 { - return trackedBlocks, nil - } - currentID := headersWithID[0].SubscriberID - currentHeaders := []header{} - for i := 0; i < len(headersWithID); i++ { - if i == len(headersWithID)-1 { - currentHeaders = append(currentHeaders, header{ - Num: headersWithID[i].Num, - Hash: headersWithID[i].Hash, - }) - trackedBlocks[currentID] = newHeadersList(currentHeaders...) - } else if headersWithID[i].SubscriberID != currentID { - trackedBlocks[currentID] = newHeadersList(currentHeaders...) - currentHeaders = []header{{ - Num: headersWithID[i].Num, - Hash: headersWithID[i].Hash, - }} - currentID = headersWithID[i].SubscriberID - } else { - currentHeaders = append(currentHeaders, header{ - Num: headersWithID[i].Num, - Hash: headersWithID[i].Hash, - }) - } - } - - return trackedBlocks, nil -} - -// saveTrackedBlock saves the tracked block for a subscriber in db and in memory -func (rd *ReorgDetector) saveTrackedBlock(id string, b header) error { - rd.trackedBlocksLock.Lock() - hdrs, ok := rd.trackedBlocks[id] - if !ok || hdrs.isEmpty() { - hdrs = newHeadersList(b) - rd.trackedBlocks[id] = hdrs - } else { - hdrs.add(b) - } - - rd.log.Debugf("Tracking block %d for subscriber %s", b.Num, id) - - rd.trackedBlocksLock.Unlock() - return meddler.Insert(rd.db, "tracked_block", &headerWithSubscriberID{ - SubscriberID: id, - Num: b.Num, - Hash: b.Hash, - }) -} - -// updateTrackedBlocksDB updates the tracked blocks for a subscriber in db -func (rd *ReorgDetector) removeTrackedBlockRange(id string, fromBlock, toBlock uint64) error { - _, err := rd.db.Exec( - "DELETE FROM tracked_block WHERE num >= $1 AND num <= $2 AND subscriber_id = $3;", - fromBlock, toBlock, id, - ) - return err -} diff --git a/reorgdetector/reorgdetector_sub.go b/reorgdetector/reorgdetector_sub.go deleted file mode 100644 index 7ff04aea9..000000000 --- a/reorgdetector/reorgdetector_sub.go +++ /dev/null @@ -1,58 +0,0 @@ -package reorgdetector - -// Subscription is a subscription to reorg events -type Subscription struct { - ReorgedBlock chan uint64 - ReorgProcessed chan bool -} - -// Subscribe subscribes to reorg events -func (rd *ReorgDetector) Subscribe(id string) (*Subscription, error) { - rd.subscriptionsLock.Lock() - defer rd.subscriptionsLock.Unlock() - - if sub, ok := rd.subscriptions[id]; ok { - return sub, nil - } - - // Create a new subscription - sub := &Subscription{ - ReorgedBlock: make(chan uint64), - ReorgProcessed: make(chan bool), - } - rd.subscriptions[id] = sub - - // Create a new tracked blocks list for the subscriber - rd.trackedBlocksLock.Lock() - rd.trackedBlocks[id] = newHeadersList() - rd.trackedBlocksLock.Unlock() - - return sub, nil -} - -// notifySubscriber notifies the subscriber with the block of the reorg -func (rd *ReorgDetector) notifySubscriber(id string, startingBlock header) { - // Notify subscriber about this particular reorg - rd.subscriptionsLock.RLock() - sub, ok := rd.subscriptions[id] - rd.subscriptionsLock.RUnlock() - - if ok { - rd.log.Infof("Reorg detected for subscriber %s at block %d", id, startingBlock.Num) - sub.ReorgedBlock <- startingBlock.Num - <-sub.ReorgProcessed - } -} - -// getSubscriberIDs returns a list of subscriber IDs -func (rd *ReorgDetector) getSubscriberIDs() []string { - rd.subscriptionsLock.RLock() - defer rd.subscriptionsLock.RUnlock() - - ids := make([]string, 0, len(rd.subscriptions)) - for id := range rd.subscriptions { - ids = append(ids, id) - } - - return ids -} diff --git a/reorgdetector/reorgdetector_test.go b/reorgdetector/reorgdetector_test.go deleted file mode 100644 index 788cf85a7..000000000 --- a/reorgdetector/reorgdetector_test.go +++ /dev/null @@ -1,259 +0,0 @@ -package reorgdetector - -import ( - "context" - big "math/big" - "path" - "strings" - "sync" - "testing" - "time" - - cdktypes "github.com/0xPolygon/cdk/config/types" - common "github.com/ethereum/go-ethereum/common" - types "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/ethclient/simulated" - "github.com/ethereum/go-ethereum/rpc" - "github.com/stretchr/testify/require" -) - -func Test_ReorgDetector(t *testing.T) { - const subID = "test" - - ctx := context.Background() - - // Simulated L1 - clientL1 := simulated.NewBackend(nil, simulated.WithBlockGasLimit(10000000)) - - // Create test DB dir - testDir := path.Join(t.TempDir(), "reorgdetectorTest_ReorgDetector.sqlite") - - reorgDetector, err := New(clientL1.Client(), Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - - err = reorgDetector.Start(ctx) - require.NoError(t, err) - - reorgSub, err := reorgDetector.Subscribe(subID) - require.NoError(t, err) - - // Block 1 - header1, err := clientL1.Client().HeaderByHash(ctx, clientL1.Commit()) - require.NoError(t, err) - require.Equal(t, uint64(1), header1.Number.Uint64()) - err = reorgDetector.AddBlockToTrack(ctx, subID, header1.Number.Uint64(), header1.Hash()) // Adding block 1 - require.NoError(t, err) - - // Block 2 - header2, err := clientL1.Client().HeaderByHash(ctx, clientL1.Commit()) - require.NoError(t, err) - require.Equal(t, uint64(2), header2.Number.Uint64()) - err = reorgDetector.AddBlockToTrack(ctx, subID, header2.Number.Uint64(), header2.Hash()) // Adding block 1 - require.NoError(t, err) - - // Block 3 - header3Reorged, err := clientL1.Client().HeaderByHash(ctx, clientL1.Commit()) - require.NoError(t, err) - require.Equal(t, uint64(3), header3Reorged.Number.Uint64()) - err = reorgDetector.AddBlockToTrack(ctx, subID, header3Reorged.Number.Uint64(), header3Reorged.Hash()) // Adding block 3 - require.NoError(t, err) - - // Block 4 - header4Reorged, err := clientL1.Client().HeaderByHash(ctx, clientL1.Commit()) - require.Equal(t, uint64(4), header4Reorged.Number.Uint64()) - require.NoError(t, err) - err = reorgDetector.AddBlockToTrack(ctx, subID, header4Reorged.Number.Uint64(), header4Reorged.Hash()) // Adding block 4 - require.NoError(t, err) - - err = clientL1.Fork(header2.Hash()) // Reorg on block 2 (block 2 is still valid) - require.NoError(t, err) - - // Make sure that the new canonical chain is longer than the previous one so the reorg is visible to the detector - header3AfterReorg := clientL1.Commit() // Next block 3 after reorg on block 2 - require.NotEqual(t, header3Reorged.Hash(), header3AfterReorg) - header4AfterReorg := clientL1.Commit() // Block 4 - require.NotEqual(t, header4Reorged.Hash(), header4AfterReorg) - clientL1.Commit() // Block 5 - - // Expect reorg on added blocks 3 -> all further blocks should be removed - select { - case firstReorgedBlock := <-reorgSub.ReorgedBlock: - reorgSub.ReorgProcessed <- true - require.Equal(t, header3Reorged.Number.Uint64(), firstReorgedBlock) - case <-time.After(5 * time.Second): - t.Fatal("timeout waiting for reorg") - } - - // just wait a little for completion - time.Sleep(time.Second / 5) - - reorgDetector.trackedBlocksLock.Lock() - headersList, ok := reorgDetector.trackedBlocks[subID] - reorgDetector.trackedBlocksLock.Unlock() - require.True(t, ok) - require.Equal(t, 2, headersList.len()) // Only blocks 1 and 2 left - actualHeader1, err := headersList.get(1) - require.NoError(t, err) - require.Equal(t, header1.Hash(), actualHeader1.Hash) - actualHeader2, err := headersList.get(2) - require.NoError(t, err) - require.Equal(t, header2.Hash(), actualHeader2.Hash) -} - -func TestGetTrackedBlocks(t *testing.T) { - clientL1 := simulated.NewBackend(nil, simulated.WithBlockGasLimit(10000000)) - testDir := path.Join(t.TempDir(), "reorgdetector_TestGetTrackedBlocks.sqlite") - reorgDetector, err := New(clientL1.Client(), Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - list, err := reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, len(list), 0) - - expectedList := make(map[string]*headersList) - headersMapFoo := make(map[uint64]header) - headerFoo2 := header{ - Num: 2, - Hash: common.HexToHash("foofoo"), - } - err = reorgDetector.saveTrackedBlock("foo", headerFoo2) - require.NoError(t, err) - headersMapFoo[2] = headerFoo2 - headerFoo3 := header{ - Num: 3, - Hash: common.HexToHash("foofoofoo"), - } - err = reorgDetector.saveTrackedBlock("foo", headerFoo3) - require.NoError(t, err) - headersMapFoo[3] = headerFoo3 - expectedList["foo"] = &headersList{ - headers: headersMapFoo, - } - list, err = reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, expectedList, list) - - headersMapBar := make(map[uint64]header) - headerBar2 := header{ - Num: 2, - Hash: common.HexToHash("BarBar"), - } - err = reorgDetector.saveTrackedBlock("Bar", headerBar2) - require.NoError(t, err) - headersMapBar[2] = headerBar2 - expectedList["Bar"] = &headersList{ - headers: headersMapBar, - } - list, err = reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, expectedList, list) - - require.NoError(t, reorgDetector.loadTrackedHeaders()) - _, ok := reorgDetector.subscriptions["foo"] - require.True(t, ok) - _, ok = reorgDetector.subscriptions["Bar"] - require.True(t, ok) -} - -func TestNotSubscribed(t *testing.T) { - clientL1 := simulated.NewBackend(nil, simulated.WithBlockGasLimit(10000000)) - testDir := path.Join(t.TempDir(), "reorgdetectorTestNotSubscribed.sqlite") - reorgDetector, err := New(clientL1.Client(), Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - err = reorgDetector.AddBlockToTrack(context.Background(), "foo", 1, common.Hash{}) - require.True(t, strings.Contains(err.Error(), "is not subscribed")) -} - -func TestDetectReorgs(t *testing.T) { - t.Parallel() - - ctx := context.Background() - syncerID := "test-syncer" - trackedBlock := &types.Header{Number: big.NewInt(9)} - - t.Run("Block not finalized", func(t *testing.T) { - t.Parallel() - - lastFinalizedBlock := &types.Header{Number: big.NewInt(8)} - client := NewEthClientMock(t) - client.On("HeaderByNumber", ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))).Return(lastFinalizedBlock, nil) - client.On("HeaderByNumber", ctx, trackedBlock.Number).Return(trackedBlock, nil) - - testDir := path.Join(t.TempDir(), "reorgdetectorTestDetectReorgs.sqlite") - reorgDetector, err := New(client, Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - - _, err = reorgDetector.Subscribe(syncerID) - require.NoError(t, err) - require.NoError(t, reorgDetector.AddBlockToTrack(ctx, syncerID, trackedBlock.Number.Uint64(), trackedBlock.Hash())) - - require.NoError(t, reorgDetector.detectReorgInTrackedList(ctx)) - - trackedBlocks, err := reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, 1, len(trackedBlocks)) - - syncerTrackedBlocks, ok := trackedBlocks[syncerID] - require.True(t, ok) - require.Equal(t, 1, syncerTrackedBlocks.len()) - }) - - t.Run("Block finalized", func(t *testing.T) { - t.Parallel() - - lastFinalizedBlock := trackedBlock - client := NewEthClientMock(t) - client.On("HeaderByNumber", ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))).Return(lastFinalizedBlock, nil) - - testDir := path.Join(t.TempDir(), "reorgdetectorTestDetectReorgs.sqlite") - reorgDetector, err := New(client, Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - - _, err = reorgDetector.Subscribe(syncerID) - require.NoError(t, err) - require.NoError(t, reorgDetector.AddBlockToTrack(ctx, syncerID, trackedBlock.Number.Uint64(), trackedBlock.Hash())) - - require.NoError(t, reorgDetector.detectReorgInTrackedList(ctx)) - - trackedBlocks, err := reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, 0, len(trackedBlocks)) - }) - - t.Run("Reorg happened", func(t *testing.T) { - t.Parallel() - - lastFinalizedBlock := &types.Header{Number: big.NewInt(5)} - reorgedTrackedBlock := &types.Header{Number: trackedBlock.Number, Extra: []byte("reorged")} // Different hash - - client := NewEthClientMock(t) - client.On("HeaderByNumber", ctx, big.NewInt(int64(rpc.FinalizedBlockNumber))).Return(lastFinalizedBlock, nil) - client.On("HeaderByNumber", ctx, trackedBlock.Number).Return(reorgedTrackedBlock, nil) - - testDir := path.Join(t.TempDir(), "reorgdetectorTestDetectReorgs.sqlite") - reorgDetector, err := New(client, Config{DBPath: testDir, CheckReorgsInterval: cdktypes.NewDuration(time.Millisecond * 100)}, L1) - require.NoError(t, err) - - subscription, err := reorgDetector.Subscribe(syncerID) - require.NoError(t, err) - - var wg sync.WaitGroup - - wg.Add(1) - go func() { - <-subscription.ReorgedBlock - subscription.ReorgProcessed <- true - - wg.Done() - }() - - require.NoError(t, reorgDetector.AddBlockToTrack(ctx, syncerID, trackedBlock.Number.Uint64(), trackedBlock.Hash())) - - require.NoError(t, reorgDetector.detectReorgInTrackedList(ctx)) - - wg.Wait() // we wait here to make sure the reorg is processed - - trackedBlocks, err := reorgDetector.getTrackedBlocks() - require.NoError(t, err) - require.Equal(t, 0, len(trackedBlocks)) // shouldn't be any since a reorg happened on that block - }) -} diff --git a/reorgdetector/types.go b/reorgdetector/types.go deleted file mode 100644 index 35a73513a..000000000 --- a/reorgdetector/types.go +++ /dev/null @@ -1,119 +0,0 @@ -package reorgdetector - -import ( - "sort" - "sync" - - "github.com/0xPolygon/cdk/db" - "github.com/ethereum/go-ethereum/common" -) - -type header struct { - Num uint64 `meddler:"num"` - Hash common.Hash `meddler:"hash,hash"` -} - -type headerWithSubscriberID struct { - SubscriberID string `meddler:"subscriber_id"` - Num uint64 `meddler:"num"` - Hash common.Hash `meddler:"hash,hash"` -} - -// newHeader returns a new instance of header -func newHeader(num uint64, hash common.Hash) header { - return header{ - Num: num, - Hash: hash, - } -} - -type headersList struct { - sync.RWMutex - headers map[uint64]header -} - -// newHeadersList returns a new instance of headersList -func newHeadersList(headers ...header) *headersList { - headersMap := make(map[uint64]header, len(headers)) - - for _, b := range headers { - headersMap[b.Num] = b - } - - return &headersList{ - headers: headersMap, - } -} - -// len returns the number of headers in the headers list -func (hl *headersList) len() int { - hl.RLock() - ln := len(hl.headers) - hl.RUnlock() - return ln -} - -// isEmpty returns true if the headers list is empty -func (hl *headersList) isEmpty() bool { - return hl.len() == 0 -} - -// add adds a header to the headers list -func (hl *headersList) add(h header) { - hl.Lock() - hl.headers[h.Num] = h - hl.Unlock() -} - -// copy returns a copy of the headers list -func (hl *headersList) copy() *headersList { - hl.RLock() - defer hl.RUnlock() - - headersMap := make(map[uint64]header, len(hl.headers)) - for k, v := range hl.headers { - headersMap[k] = v - } - - return &headersList{ - headers: headersMap, - } -} - -// get returns a header by block number -func (hl *headersList) get(num uint64) (*header, error) { - hl.RLock() - defer hl.RUnlock() - - if b, ok := hl.headers[num]; ok { - return &b, nil - } - - return nil, db.ErrNotFound -} - -// getSorted returns headers in sorted order -func (hl *headersList) getSorted() []header { - hl.RLock() - sortedBlocks := make([]header, 0, len(hl.headers)) - - for _, b := range hl.headers { - sortedBlocks = append(sortedBlocks, b) - } - hl.RUnlock() - - sort.Slice(sortedBlocks, func(i, j int) bool { - return sortedBlocks[i].Num < sortedBlocks[j].Num - }) - - return sortedBlocks -} - -// removeRange removes headers from "from" to "to" -func (hl *headersList) removeRange(from, to uint64) { - hl.Lock() - for i := from; i <= to; i++ { - delete(hl.headers, i) - } - hl.Unlock() -} diff --git a/reorgdetector/types_test.go b/reorgdetector/types_test.go deleted file mode 100644 index d2562078c..000000000 --- a/reorgdetector/types_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package reorgdetector - -import ( - "reflect" - "testing" - - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestBlockMap(t *testing.T) { - t.Parallel() - - // Create a new block map - bm := newHeadersList( - header{Num: 1, Hash: common.HexToHash("0x123")}, - header{Num: 2, Hash: common.HexToHash("0x456")}, - header{Num: 3, Hash: common.HexToHash("0x789")}, - ) - - t.Run("len", func(t *testing.T) { - t.Parallel() - - actualLen := bm.len() - expectedLen := 3 - if !reflect.DeepEqual(expectedLen, actualLen) { - t.Errorf("len() returned incorrect result, expected: %v, got: %v", expectedLen, actualLen) - } - }) - - t.Run("isEmpty", func(t *testing.T) { - t.Parallel() - - if bm.isEmpty() { - t.Error("isEmpty() returned incorrect result, expected: false, got: true") - } - }) - - t.Run("add", func(t *testing.T) { - t.Parallel() - - bm := bm.copy() - tba := header{Num: 4, Hash: common.HexToHash("0xabc")} - bm.add(tba) - if !reflect.DeepEqual(tba, bm.headers[4]) { - t.Errorf("add() returned incorrect result, expected: %v, got: %v", tba, bm.headers[4]) - } - }) - - t.Run("copy", func(t *testing.T) { - t.Parallel() - - copiedBm := bm.copy() - for i, header := range bm.headers { - copiedHeader, exists := copiedBm.headers[i] - require.True(t, exists) - if !reflect.DeepEqual(header, copiedHeader) { - t.Errorf("copy() returned incorrect result, expected: %v, got: %v", header, copiedHeader) - } - } - }) - - t.Run("get", func(t *testing.T) { - t.Parallel() - - header, err := bm.get(3) - require.NoError(t, err) - if !reflect.DeepEqual(*header, bm.headers[3]) { - t.Errorf("get() returned incorrect result, expected: %v, got: %v", header, bm.headers[3]) - } - }) - - t.Run("getSorted", func(t *testing.T) { - t.Parallel() - - sortedBlocks := bm.getSorted() - expectedSortedBlocks := []header{ - {Num: 1, Hash: common.HexToHash("0x123")}, - {Num: 2, Hash: common.HexToHash("0x456")}, - {Num: 3, Hash: common.HexToHash("0x789")}, - } - if !reflect.DeepEqual(sortedBlocks, expectedSortedBlocks) { - t.Errorf("getSorted() returned incorrect result, expected: %v, got: %v", expectedSortedBlocks, sortedBlocks) - } - }) - - t.Run("removeRange", func(t *testing.T) { - t.Parallel() - - bm := newHeadersList( - header{Num: 1, Hash: common.HexToHash("0x123")}, - header{Num: 2, Hash: common.HexToHash("0x456")}, - header{Num: 3, Hash: common.HexToHash("0x789")}, - header{Num: 4, Hash: common.HexToHash("0xabc")}, - header{Num: 5, Hash: common.HexToHash("0xdef")}, - ) - - bm.removeRange(3, 5) - - expectedBlocks := []header{ - {Num: 1, Hash: common.HexToHash("0x123")}, - {Num: 2, Hash: common.HexToHash("0x456")}, - } - - sortedBlocks := bm.getSorted() - - if !reflect.DeepEqual(sortedBlocks, expectedBlocks) { - t.Errorf("removeRange() failed, expected: %v, got: %v", expectedBlocks, sortedBlocks) - } - }) -} diff --git a/rpc/batch.go b/rpc/batch.go index bd75a3748..6ee4eeb3d 100644 --- a/rpc/batch.go +++ b/rpc/batch.go @@ -7,9 +7,9 @@ import ( "math/big" "github.com/0xPolygon/cdk-rpc/rpc" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/rpc/types" "github.com/0xPolygon/cdk/state" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ) diff --git a/rpc/bridge.go b/rpc/bridge.go deleted file mode 100644 index 65d949710..000000000 --- a/rpc/bridge.go +++ /dev/null @@ -1,364 +0,0 @@ -package rpc - -import ( - "context" - "errors" - "fmt" - "math/big" - "time" - - "github.com/0xPolygon/cdk-rpc/rpc" - "github.com/0xPolygon/cdk/claimsponsor" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/rpc/types" - tree "github.com/0xPolygon/cdk/tree/types" - "go.opentelemetry.io/otel" - "go.opentelemetry.io/otel/metric" -) - -const ( - // BRIDGE is the namespace of the bridge service - BRIDGE = "bridge" - meterName = "github.com/0xPolygon/cdk/rpc" - - zeroHex = "0x0" - binnarySearchDivider = 2 -) - -var ( - ErrNotOnL1Info = errors.New("this bridge has not been included on the L1 Info Tree yet") -) - -// BridgeEndpoints contains implementations for the "bridge" RPC endpoints -type BridgeEndpoints struct { - logger *log.Logger - meter metric.Meter - readTimeout time.Duration - writeTimeout time.Duration - networkID uint32 - sponsor ClaimSponsorer - l1InfoTree L1InfoTreer - injectedGERs LastGERer - bridgeL1 Bridger - bridgeL2 Bridger -} - -// NewBridgeEndpoints returns InteropEndpoints -func NewBridgeEndpoints( - logger *log.Logger, - writeTimeout time.Duration, - readTimeout time.Duration, - networkID uint32, - sponsor ClaimSponsorer, - l1InfoTree L1InfoTreer, - injectedGERs LastGERer, - bridgeL1 Bridger, - bridgeL2 Bridger, -) *BridgeEndpoints { - meter := otel.Meter(meterName) - return &BridgeEndpoints{ - logger: logger, - meter: meter, - readTimeout: readTimeout, - writeTimeout: writeTimeout, - networkID: networkID, - sponsor: sponsor, - l1InfoTree: l1InfoTree, - injectedGERs: injectedGERs, - bridgeL1: bridgeL1, - bridgeL2: bridgeL2, - } -} - -// L1InfoTreeIndexForBridge returns the first L1 Info Tree index in which the bridge was included. -// networkID represents the origin network. -// This call needs to be done to a client of the same network were the bridge tx was sent -func (b *BridgeEndpoints) L1InfoTreeIndexForBridge(networkID uint32, depositCount uint32) (interface{}, rpc.Error) { - ctx, cancel := context.WithTimeout(context.Background(), b.readTimeout) - defer cancel() - - c, merr := b.meter.Int64Counter("l1_info_tree_index_for_bridge") - if merr != nil { - b.logger.Warnf("failed to create l1_info_tree_index_for_bridge counter: %s", merr) - } - c.Add(ctx, 1) - - if networkID == 0 { - l1InfoTreeIndex, err := b.getFirstL1InfoTreeIndexForL1Bridge(ctx, depositCount) - // TODO: special treatment of the error when not found, - // as it's expected that it will take some time for the L1 Info tree to be updated - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf( - "failed to get l1InfoTreeIndex for networkID %d and deposit count %d, error: %s", networkID, depositCount, err), - ) - } - return l1InfoTreeIndex, nil - } - if networkID == b.networkID { - l1InfoTreeIndex, err := b.getFirstL1InfoTreeIndexForL2Bridge(ctx, depositCount) - // TODO: special treatment of the error when not found, - // as it's expected that it will take some time for the L1 Info tree to be updated - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf( - "failed to get l1InfoTreeIndex for networkID %d and deposit count %d, error: %s", networkID, depositCount, err), - ) - } - return l1InfoTreeIndex, nil - } - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("this client does not support network %d", networkID), - ) -} - -// InjectedInfoAfterIndex return the first GER injected onto the network that is linked -// to the given index or greater. This call is useful to understand when a bridge is ready to be claimed -// on its destination network -func (b *BridgeEndpoints) InjectedInfoAfterIndex(networkID uint32, l1InfoTreeIndex uint32) (interface{}, rpc.Error) { - ctx, cancel := context.WithTimeout(context.Background(), b.readTimeout) - defer cancel() - - c, merr := b.meter.Int64Counter("injected_info_after_index") - if merr != nil { - b.logger.Warnf("failed to create injected_info_after_index counter: %s", merr) - } - c.Add(ctx, 1) - - if networkID == 0 { - info, err := b.l1InfoTree.GetInfoByIndex(ctx, l1InfoTreeIndex) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get global exit root, error: %s", err)) - } - return info, nil - } - if networkID == b.networkID { - e, err := b.injectedGERs.GetFirstGERAfterL1InfoTreeIndex(ctx, l1InfoTreeIndex) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get global exit root, error: %s", err)) - } - info, err := b.l1InfoTree.GetInfoByIndex(ctx, e.L1InfoTreeIndex) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get global exit root, error: %s", err)) - } - return info, nil - } - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("this client does not support network %d", networkID), - ) -} - -// GetProof returns the proofs needed to claim a bridge. NetworkID and depositCount refere to the bridge origin -// while globalExitRoot should be already injected on the destination network. -// This call needs to be done to a client of the same network were the bridge tx was sent -func (b *BridgeEndpoints) GetProof( - networkID uint32, depositCount uint32, l1InfoTreeIndex uint32, -) (interface{}, rpc.Error) { - ctx, cancel := context.WithTimeout(context.Background(), b.readTimeout) - defer cancel() - - c, merr := b.meter.Int64Counter("claim_proof") - if merr != nil { - b.logger.Warnf("failed to create claim_proof counter: %s", merr) - } - c.Add(ctx, 1) - - info, err := b.l1InfoTree.GetInfoByIndex(ctx, l1InfoTreeIndex) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get info from the tree: %s", err)) - } - proofRollupExitRoot, err := b.l1InfoTree.GetRollupExitTreeMerkleProof(ctx, networkID, info.GlobalExitRoot) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get rollup exit proof, error: %s", err)) - } - var proofLocalExitRoot tree.Proof - switch { - case networkID == 0: - proofLocalExitRoot, err = b.bridgeL1.GetProof(ctx, depositCount, info.MainnetExitRoot) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get local exit proof, error: %s", err)) - } - - case networkID == b.networkID: - localExitRoot, err := b.l1InfoTree.GetLocalExitRoot(ctx, networkID, info.RollupExitRoot) - if err != nil { - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("failed to get local exit root from rollup exit tree, error: %s", err), - ) - } - proofLocalExitRoot, err = b.bridgeL2.GetProof(ctx, depositCount, localExitRoot) - if err != nil { - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("failed to get local exit proof, error: %s", err), - ) - } - - default: - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("this client does not support network %d", networkID), - ) - } - return types.ClaimProof{ - ProofLocalExitRoot: proofLocalExitRoot, - ProofRollupExitRoot: proofRollupExitRoot, - L1InfoTreeLeaf: *info, - }, nil -} - -// SponsorClaim sends a claim tx on behalf of the user. -// This call needs to be done to a client of the same network were the claim is going to be sent (bridge destination) -func (b *BridgeEndpoints) SponsorClaim(claim claimsponsor.Claim) (interface{}, rpc.Error) { - ctx, cancel := context.WithTimeout(context.Background(), b.writeTimeout) - defer cancel() - - c, merr := b.meter.Int64Counter("sponsor_claim") - if merr != nil { - b.logger.Warnf("failed to create sponsor_claim counter: %s", merr) - } - c.Add(ctx, 1) - - if b.sponsor == nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, "this client does not support claim sponsoring") - } - if claim.DestinationNetwork != b.networkID { - return zeroHex, rpc.NewRPCError( - rpc.DefaultErrorCode, - fmt.Sprintf("this client only sponsors claims for network %d", b.networkID), - ) - } - if err := b.sponsor.AddClaimToQueue(&claim); err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("error adding claim to the queue %s", err)) - } - return nil, nil -} - -// GetSponsoredClaimStatus returns the status of a claim that has been previously requested to be sponsored. -// This call needs to be done to the same client were it was requested to be sponsored -func (b *BridgeEndpoints) GetSponsoredClaimStatus(globalIndex *big.Int) (interface{}, rpc.Error) { - ctx, cancel := context.WithTimeout(context.Background(), b.readTimeout) - defer cancel() - - c, merr := b.meter.Int64Counter("get_sponsored_claim_status") - if merr != nil { - b.logger.Warnf("failed to create get_sponsored_claim_status counter: %s", merr) - } - c.Add(ctx, 1) - - if b.sponsor == nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, "this client does not support claim sponsoring") - } - claim, err := b.sponsor.GetClaim(globalIndex) - if err != nil { - return zeroHex, rpc.NewRPCError(rpc.DefaultErrorCode, fmt.Sprintf("failed to get claim status, error: %s", err)) - } - return claim.Status, nil -} - -func (b *BridgeEndpoints) getFirstL1InfoTreeIndexForL1Bridge(ctx context.Context, depositCount uint32) (uint32, error) { - lastInfo, err := b.l1InfoTree.GetLastInfo() - if err != nil { - return 0, err - } - - root, err := b.bridgeL1.GetRootByLER(ctx, lastInfo.MainnetExitRoot) - if err != nil { - return 0, err - } - if root.Index < depositCount { - return 0, ErrNotOnL1Info - } - - firstInfo, err := b.l1InfoTree.GetFirstInfo() - if err != nil { - return 0, err - } - - // Binary search between the first and last blcoks where L1 info tree was updated. - // Find the smallest l1 info tree index that is greater than depositCount and matches with - // a MER that is included on the l1 info tree - bestResult := lastInfo - lowerLimit := firstInfo.BlockNumber - upperLimit := lastInfo.BlockNumber - for lowerLimit <= upperLimit { - targetBlock := lowerLimit + ((upperLimit - lowerLimit) / binnarySearchDivider) - targetInfo, err := b.l1InfoTree.GetFirstInfoAfterBlock(targetBlock) - if err != nil { - return 0, err - } - root, err := b.bridgeL1.GetRootByLER(ctx, targetInfo.MainnetExitRoot) - if err != nil { - return 0, err - } - if root.Index < depositCount { - lowerLimit = targetBlock + 1 - } else if root.Index == depositCount { - bestResult = targetInfo - break - } else { - bestResult = targetInfo - upperLimit = targetBlock - 1 - } - } - - return bestResult.L1InfoTreeIndex, nil -} - -func (b *BridgeEndpoints) getFirstL1InfoTreeIndexForL2Bridge(ctx context.Context, depositCount uint32) (uint32, error) { - // NOTE: this code assumes that all the rollup exit roots - // (produced by the smart contract call verifyBatches / verifyBatchesTrustedAggregator) - // are included in the L1 info tree. As per the current implementation (smart contracts) of the protocol - // this is true. This could change in the future - lastVerified, err := b.l1InfoTree.GetLastVerifiedBatches(b.networkID - 1) - if err != nil { - return 0, err - } - - root, err := b.bridgeL2.GetRootByLER(ctx, lastVerified.ExitRoot) - if err != nil { - return 0, err - } - if root.Index < depositCount { - return 0, ErrNotOnL1Info - } - - firstVerified, err := b.l1InfoTree.GetFirstVerifiedBatches(b.networkID - 1) - if err != nil { - return 0, err - } - - // Binary search between the first and last blcoks where batches were verified. - // Find the smallest deposit count that is greater than depositCount and matches with - // a LER that is verified - bestResult := lastVerified - lowerLimit := firstVerified.BlockNumber - upperLimit := lastVerified.BlockNumber - for lowerLimit <= upperLimit { - targetBlock := lowerLimit + ((upperLimit - lowerLimit) / binnarySearchDivider) - targetVerified, err := b.l1InfoTree.GetFirstVerifiedBatchesAfterBlock(b.networkID-1, targetBlock) - if err != nil { - return 0, err - } - root, err = b.bridgeL2.GetRootByLER(ctx, targetVerified.ExitRoot) - if err != nil { - return 0, err - } - if root.Index < depositCount { - lowerLimit = targetBlock + 1 - } else if root.Index == depositCount { - bestResult = targetVerified - break - } else { - bestResult = targetVerified - upperLimit = targetBlock - 1 - } - } - - info, err := b.l1InfoTree.GetFirstL1InfoWithRollupExitRoot(bestResult.RollupExitRoot) - if err != nil { - return 0, err - } - return info.L1InfoTreeIndex, nil -} diff --git a/rpc/bridge_interfaces.go b/rpc/bridge_interfaces.go deleted file mode 100644 index bf6721ea7..000000000 --- a/rpc/bridge_interfaces.go +++ /dev/null @@ -1,41 +0,0 @@ -package rpc - -import ( - "context" - "math/big" - - "github.com/0xPolygon/cdk/claimsponsor" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/lastgersync" - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" -) - -type Bridger interface { - GetProof(ctx context.Context, depositCount uint32, localExitRoot common.Hash) (tree.Proof, error) - GetRootByLER(ctx context.Context, ler common.Hash) (*tree.Root, error) -} - -type LastGERer interface { - GetFirstGERAfterL1InfoTreeIndex( - ctx context.Context, atOrAfterL1InfoTreeIndex uint32, - ) (lastgersync.Event, error) -} - -type L1InfoTreer interface { - GetInfoByIndex(ctx context.Context, index uint32) (*l1infotreesync.L1InfoTreeLeaf, error) - GetRollupExitTreeMerkleProof(ctx context.Context, networkID uint32, root common.Hash) (tree.Proof, error) - GetLocalExitRoot(ctx context.Context, networkID uint32, rollupExitRoot common.Hash) (common.Hash, error) - GetLastInfo() (*l1infotreesync.L1InfoTreeLeaf, error) - GetFirstInfo() (*l1infotreesync.L1InfoTreeLeaf, error) - GetFirstInfoAfterBlock(blockNum uint64) (*l1infotreesync.L1InfoTreeLeaf, error) - GetLastVerifiedBatches(rollupID uint32) (*l1infotreesync.VerifyBatches, error) - GetFirstVerifiedBatches(rollupID uint32) (*l1infotreesync.VerifyBatches, error) - GetFirstVerifiedBatchesAfterBlock(rollupID uint32, blockNum uint64) (*l1infotreesync.VerifyBatches, error) - GetFirstL1InfoWithRollupExitRoot(rollupExitRoot common.Hash) (*l1infotreesync.L1InfoTreeLeaf, error) -} - -type ClaimSponsorer interface { - AddClaimToQueue(claim *claimsponsor.Claim) error - GetClaim(globalIndex *big.Int) (*claimsponsor.Claim, error) -} diff --git a/rpc/bridge_test.go b/rpc/bridge_test.go deleted file mode 100644 index 9d461a50a..000000000 --- a/rpc/bridge_test.go +++ /dev/null @@ -1,443 +0,0 @@ -package rpc - -import ( - "context" - "errors" - "testing" - - cdkCommon "github.com/0xPolygon/cdk/common" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" - mocks "github.com/0xPolygon/cdk/rpc/mocks" - tree "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -func TestGetFirstL1InfoTreeIndexForL1Bridge(t *testing.T) { - type testCase struct { - description string - setupMocks func() - depositCount uint32 - expectedIndex uint32 - expectedErr error - } - ctx := context.Background() - b := newBridgeWithMocks(t) - fooErr := errors.New("foo") - firstL1Info := &l1infotreesync.L1InfoTreeLeaf{ - BlockNumber: 10, - MainnetExitRoot: common.HexToHash("alfa"), - } - lastL1Info := &l1infotreesync.L1InfoTreeLeaf{ - BlockNumber: 1000, - MainnetExitRoot: common.HexToHash("alfa"), - } - mockHappyPath := func() { - // to make this work, assume that block number == l1 info tree index == deposit count - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.l1InfoTree.On("GetFirstInfo"). - Return(firstL1Info, nil). - Once() - infoAfterBlock := &l1infotreesync.L1InfoTreeLeaf{} - b.l1InfoTree.On("GetFirstInfoAfterBlock", mock.Anything). - Run(func(args mock.Arguments) { - blockNum, ok := args.Get(0).(uint64) - require.True(t, ok) - infoAfterBlock.L1InfoTreeIndex = uint32(blockNum) - infoAfterBlock.BlockNumber = blockNum - infoAfterBlock.MainnetExitRoot = common.BytesToHash(cdkCommon.Uint32ToBytes(uint32(blockNum))) - }). - Return(infoAfterBlock, nil) - rootByLER := &tree.Root{} - b.bridgeL1.On("GetRootByLER", ctx, mock.Anything). - Run(func(args mock.Arguments) { - ler, ok := args.Get(1).(common.Hash) - require.True(t, ok) - index := cdkCommon.BytesToUint32(ler.Bytes()[28:]) // hash is 32 bytes, uint32 is just 4 - if ler == common.HexToHash("alfa") { - index = uint32(lastL1Info.BlockNumber) - } - rootByLER.Index = index - }). - Return(rootByLER, nil) - } - testCases := []testCase{ - { - description: "error on GetLastInfo", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on first GetRootByLER", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, lastL1Info.MainnetExitRoot). - Return(&tree.Root{}, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "not included yet", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, lastL1Info.MainnetExitRoot). - Return(&tree.Root{Index: 10}, nil). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: ErrNotOnL1Info, - }, - { - description: "error on GetFirstInfo", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, lastL1Info.MainnetExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstInfo"). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on GetFirstInfoAfterBlock", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, lastL1Info.MainnetExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstInfo"). - Return(firstL1Info, nil). - Once() - b.l1InfoTree.On("GetFirstInfoAfterBlock", mock.Anything). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on GetRootByLER (inside binnary search)", - setupMocks: func() { - b.l1InfoTree.On("GetLastInfo"). - Return(lastL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, lastL1Info.MainnetExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstInfo"). - Return(firstL1Info, nil). - Once() - b.l1InfoTree.On("GetFirstInfoAfterBlock", mock.Anything). - Return(firstL1Info, nil). - Once() - b.bridgeL1.On("GetRootByLER", ctx, mock.Anything). - Return(&tree.Root{}, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "happy path 1", - setupMocks: mockHappyPath, - depositCount: 10, - expectedIndex: 10, - expectedErr: nil, - }, - { - description: "happy path 2", - setupMocks: mockHappyPath, - depositCount: 11, - expectedIndex: 11, - expectedErr: nil, - }, - { - description: "happy path 3", - setupMocks: mockHappyPath, - depositCount: 333, - expectedIndex: 333, - expectedErr: nil, - }, - { - description: "happy path 4", - setupMocks: mockHappyPath, - depositCount: 420, - expectedIndex: 420, - expectedErr: nil, - }, - { - description: "happy path 5", - setupMocks: mockHappyPath, - depositCount: 69, - expectedIndex: 69, - expectedErr: nil, - }, - } - - for _, tc := range testCases { - log.Debugf("running test case: %s", tc.description) - tc.setupMocks() - actualIndex, err := b.bridge.getFirstL1InfoTreeIndexForL1Bridge(ctx, tc.depositCount) - require.Equal(t, tc.expectedErr, err) - require.Equal(t, tc.expectedIndex, actualIndex) - } -} - -func TestGetFirstL1InfoTreeIndexForL2Bridge(t *testing.T) { - type testCase struct { - description string - setupMocks func() - depositCount uint32 - expectedIndex uint32 - expectedErr error - } - ctx := context.Background() - b := newBridgeWithMocks(t) - fooErr := errors.New("foo") - firstVerified := &l1infotreesync.VerifyBatches{ - BlockNumber: 10, - ExitRoot: common.HexToHash("alfa"), - } - lastVerified := &l1infotreesync.VerifyBatches{ - BlockNumber: 1000, - ExitRoot: common.HexToHash("alfa"), - } - mockHappyPath := func() { - // to make this work, assume that block number == l1 info tree index == deposit count - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatches", uint32(1)). - Return(firstVerified, nil). - Once() - verifiedAfterBlock := &l1infotreesync.VerifyBatches{} - b.l1InfoTree.On("GetFirstVerifiedBatchesAfterBlock", uint32(1), mock.Anything). - Run(func(args mock.Arguments) { - blockNum, ok := args.Get(1).(uint64) - require.True(t, ok) - verifiedAfterBlock.BlockNumber = blockNum - verifiedAfterBlock.ExitRoot = common.BytesToHash(cdkCommon.Uint32ToBytes(uint32(blockNum))) - verifiedAfterBlock.RollupExitRoot = common.BytesToHash(cdkCommon.Uint32ToBytes(uint32(blockNum))) - }). - Return(verifiedAfterBlock, nil) - rootByLER := &tree.Root{} - b.bridgeL2.On("GetRootByLER", ctx, mock.Anything). - Run(func(args mock.Arguments) { - ler, ok := args.Get(1).(common.Hash) - require.True(t, ok) - index := cdkCommon.BytesToUint32(ler.Bytes()[28:]) // hash is 32 bytes, uint32 is just 4 - if ler == common.HexToHash("alfa") { - index = uint32(lastVerified.BlockNumber) - } - rootByLER.Index = index - }). - Return(rootByLER, nil) - info := &l1infotreesync.L1InfoTreeLeaf{} - b.l1InfoTree.On("GetFirstL1InfoWithRollupExitRoot", mock.Anything). - Run(func(args mock.Arguments) { - exitRoot, ok := args.Get(0).(common.Hash) - require.True(t, ok) - index := cdkCommon.BytesToUint32(exitRoot.Bytes()[28:]) // hash is 32 bytes, uint32 is just 4 - info.L1InfoTreeIndex = index - }). - Return(info, nil). - Once() - } - testCases := []testCase{ - { - description: "error on GetLastVerified", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on first GetRootByLER", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, lastVerified.ExitRoot). - Return(&tree.Root{}, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "not included yet", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, lastVerified.ExitRoot). - Return(&tree.Root{Index: 10}, nil). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: ErrNotOnL1Info, - }, - { - description: "error on GetFirstVerified", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, lastVerified.ExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatches", uint32(1)). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on GetFirstVerifiedBatchesAfterBlock", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, lastVerified.ExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatches", uint32(1)). - Return(firstVerified, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatchesAfterBlock", uint32(1), mock.Anything). - Return(nil, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "error on GetRootByLER (inside binnary search)", - setupMocks: func() { - b.l1InfoTree.On("GetLastVerifiedBatches", uint32(1)). - Return(lastVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, lastVerified.ExitRoot). - Return(&tree.Root{Index: 13}, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatches", uint32(1)). - Return(firstVerified, nil). - Once() - b.l1InfoTree.On("GetFirstVerifiedBatchesAfterBlock", uint32(1), mock.Anything). - Return(firstVerified, nil). - Once() - b.bridgeL2.On("GetRootByLER", ctx, mock.Anything). - Return(&tree.Root{}, fooErr). - Once() - }, - depositCount: 11, - expectedIndex: 0, - expectedErr: fooErr, - }, - { - description: "happy path 1", - setupMocks: mockHappyPath, - depositCount: 10, - expectedIndex: 10, - expectedErr: nil, - }, - { - description: "happy path 2", - setupMocks: mockHappyPath, - depositCount: 11, - expectedIndex: 11, - expectedErr: nil, - }, - { - description: "happy path 3", - setupMocks: mockHappyPath, - depositCount: 333, - expectedIndex: 333, - expectedErr: nil, - }, - { - description: "happy path 4", - setupMocks: mockHappyPath, - depositCount: 420, - expectedIndex: 420, - expectedErr: nil, - }, - { - description: "happy path 5", - setupMocks: mockHappyPath, - depositCount: 69, - expectedIndex: 69, - expectedErr: nil, - }, - } - - for _, tc := range testCases { - log.Debugf("running test case: %s", tc.description) - tc.setupMocks() - actualIndex, err := b.bridge.getFirstL1InfoTreeIndexForL2Bridge(ctx, tc.depositCount) - require.Equal(t, tc.expectedErr, err) - require.Equal(t, tc.expectedIndex, actualIndex) - } -} - -type bridgeWithMocks struct { - bridge *BridgeEndpoints - sponsor *mocks.ClaimSponsorer - l1InfoTree *mocks.L1InfoTreer - injectedGERs *mocks.LastGERer - bridgeL1 *mocks.Bridger - bridgeL2 *mocks.Bridger -} - -func newBridgeWithMocks(t *testing.T) bridgeWithMocks { - t.Helper() - b := bridgeWithMocks{ - sponsor: mocks.NewClaimSponsorer(t), - l1InfoTree: mocks.NewL1InfoTreer(t), - injectedGERs: mocks.NewLastGERer(t), - bridgeL1: mocks.NewBridger(t), - bridgeL2: mocks.NewBridger(t), - } - logger := log.WithFields("module", "bridgerpc") - b.bridge = NewBridgeEndpoints( - logger, 0, 0, 2, b.sponsor, b.l1InfoTree, b.injectedGERs, b.bridgeL1, b.bridgeL2, - ) - return b -} diff --git a/rpc/client/bridge.go b/rpc/client/bridge.go deleted file mode 100644 index f67907f27..000000000 --- a/rpc/client/bridge.go +++ /dev/null @@ -1,94 +0,0 @@ -package rpc - -import ( - "encoding/json" - "fmt" - "math/big" - - "github.com/0xPolygon/cdk-rpc/rpc" - "github.com/0xPolygon/cdk/claimsponsor" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/rpc/types" -) - -type BridgeClientInterface interface { - L1InfoTreeIndexForBridge(networkID uint32, depositCount uint32) (uint32, error) - InjectedInfoAfterIndex(networkID uint32, l1InfoTreeIndex uint32) (*l1infotreesync.L1InfoTreeLeaf, error) - ClaimProof(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32) (*types.ClaimProof, error) - SponsorClaim(claim claimsponsor.Claim) error - GetSponsoredClaimStatus(globalIndex *big.Int) (claimsponsor.ClaimStatus, error) -} - -// L1InfoTreeIndexForBridge returns the first L1 Info Tree index in which the bridge was included. -// networkID represents the origin network. -// This call needs to be done to a client of the same network were the bridge tx was sent -func (c *Client) L1InfoTreeIndexForBridge(networkID uint32, depositCount uint32) (uint32, error) { - response, err := rpc.JSONRPCCall(c.url, "bridge_l1InfoTreeIndexForBridge", networkID, depositCount) - if err != nil { - return 0, err - } - if response.Error != nil { - return 0, fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) - } - var result uint32 - return result, json.Unmarshal(response.Result, &result) -} - -// InjectedInfoAfterIndex return the first GER injected onto the network that is linked -// to the given index or greater. This call is useful to understand when a bridge is ready to be claimed -// on its destination network -func (c *Client) InjectedInfoAfterIndex( - networkID uint32, l1InfoTreeIndex uint32, -) (*l1infotreesync.L1InfoTreeLeaf, error) { - response, err := rpc.JSONRPCCall(c.url, "bridge_injectedInfoAfterIndex", networkID, l1InfoTreeIndex) - if err != nil { - return nil, err - } - if response.Error != nil { - return nil, fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) - } - var result l1infotreesync.L1InfoTreeLeaf - return &result, json.Unmarshal(response.Result, &result) -} - -// ClaimProof returns the proofs needed to claim a bridge. NetworkID and depositCount refere to the bridge origin -// while globalExitRoot should be already injected on the destination network. -// This call needs to be done to a client of the same network were the bridge tx was sent -func (c *Client) ClaimProof(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32) (*types.ClaimProof, error) { - response, err := rpc.JSONRPCCall(c.url, "bridge_claimProof", networkID, depositCount, l1InfoTreeIndex) - if err != nil { - return nil, err - } - if response.Error != nil { - return nil, fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) - } - var result types.ClaimProof - return &result, json.Unmarshal(response.Result, &result) -} - -// SponsorClaim sends a claim tx on behalf of the user. -// This call needs to be done to a client of the same network were the claim is going to be sent (bridge destination) -func (c *Client) SponsorClaim(claim claimsponsor.Claim) error { - response, err := rpc.JSONRPCCall(c.url, "bridge_sponsorClaim", claim) - if err != nil { - return err - } - if response.Error != nil { - return fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) - } - return nil -} - -// GetSponsoredClaimStatus returns the status of a claim that has been previously requested to be sponsored. -// This call needs to be done to the same client were it was requested to be sponsored -func (c *Client) GetSponsoredClaimStatus(globalIndex *big.Int) (claimsponsor.ClaimStatus, error) { - response, err := rpc.JSONRPCCall(c.url, "bridge_getSponsoredClaimStatus", globalIndex) - if err != nil { - return "", err - } - if response.Error != nil { - return "", fmt.Errorf("%v %v", response.Error.Code, response.Error.Message) - } - var result claimsponsor.ClaimStatus - return result, json.Unmarshal(response.Result, &result) -} diff --git a/rpc/client/client.go b/rpc/client/client.go deleted file mode 100644 index b48fca519..000000000 --- a/rpc/client/client.go +++ /dev/null @@ -1,31 +0,0 @@ -package rpc - -// ClientInterface is the interface that defines the implementation of all the endpoints -type ClientInterface interface { - BridgeClientInterface -} - -// ClientFactoryInterface interface for the client factory -type ClientFactoryInterface interface { - NewClient(url string) ClientInterface -} - -// ClientFactory is the implementation of the data committee client factory -type ClientFactory struct{} - -// NewClient returns an implementation of the data committee node client -func (f *ClientFactory) NewClient(url string) ClientInterface { - return NewClient(url) -} - -// Client wraps all the available endpoints of the data abailability committee node server -type Client struct { - url string -} - -// NewClient returns a client ready to be used -func NewClient(url string) *Client { - return &Client{ - url: url, - } -} diff --git a/rpc/mocks/mock_bridge_client_interface.go b/rpc/mocks/mock_bridge_client_interface.go deleted file mode 100644 index 4c5200e4d..000000000 --- a/rpc/mocks/mock_bridge_client_interface.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - big "math/big" - - claimsponsor "github.com/0xPolygon/cdk/claimsponsor" - l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync" - - mock "github.com/stretchr/testify/mock" - - types "github.com/0xPolygon/cdk/rpc/types" -) - -// BridgeClientInterface is an autogenerated mock type for the BridgeClientInterface type -type BridgeClientInterface struct { - mock.Mock -} - -type BridgeClientInterface_Expecter struct { - mock *mock.Mock -} - -func (_m *BridgeClientInterface) EXPECT() *BridgeClientInterface_Expecter { - return &BridgeClientInterface_Expecter{mock: &_m.Mock} -} - -// ClaimProof provides a mock function with given fields: networkID, depositCount, l1InfoTreeIndex -func (_m *BridgeClientInterface) ClaimProof(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32) (*types.ClaimProof, error) { - ret := _m.Called(networkID, depositCount, l1InfoTreeIndex) - - if len(ret) == 0 { - panic("no return value specified for ClaimProof") - } - - var r0 *types.ClaimProof - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32, uint32) (*types.ClaimProof, error)); ok { - return rf(networkID, depositCount, l1InfoTreeIndex) - } - if rf, ok := ret.Get(0).(func(uint32, uint32, uint32) *types.ClaimProof); ok { - r0 = rf(networkID, depositCount, l1InfoTreeIndex) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.ClaimProof) - } - } - - if rf, ok := ret.Get(1).(func(uint32, uint32, uint32) error); ok { - r1 = rf(networkID, depositCount, l1InfoTreeIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// BridgeClientInterface_ClaimProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClaimProof' -type BridgeClientInterface_ClaimProof_Call struct { - *mock.Call -} - -// ClaimProof is a helper method to define mock.On call -// - networkID uint32 -// - depositCount uint32 -// - l1InfoTreeIndex uint32 -func (_e *BridgeClientInterface_Expecter) ClaimProof(networkID interface{}, depositCount interface{}, l1InfoTreeIndex interface{}) *BridgeClientInterface_ClaimProof_Call { - return &BridgeClientInterface_ClaimProof_Call{Call: _e.mock.On("ClaimProof", networkID, depositCount, l1InfoTreeIndex)} -} - -func (_c *BridgeClientInterface_ClaimProof_Call) Run(run func(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32)) *BridgeClientInterface_ClaimProof_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32), args[2].(uint32)) - }) - return _c -} - -func (_c *BridgeClientInterface_ClaimProof_Call) Return(_a0 *types.ClaimProof, _a1 error) *BridgeClientInterface_ClaimProof_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *BridgeClientInterface_ClaimProof_Call) RunAndReturn(run func(uint32, uint32, uint32) (*types.ClaimProof, error)) *BridgeClientInterface_ClaimProof_Call { - _c.Call.Return(run) - return _c -} - -// GetSponsoredClaimStatus provides a mock function with given fields: globalIndex -func (_m *BridgeClientInterface) GetSponsoredClaimStatus(globalIndex *big.Int) (claimsponsor.ClaimStatus, error) { - ret := _m.Called(globalIndex) - - if len(ret) == 0 { - panic("no return value specified for GetSponsoredClaimStatus") - } - - var r0 claimsponsor.ClaimStatus - var r1 error - if rf, ok := ret.Get(0).(func(*big.Int) (claimsponsor.ClaimStatus, error)); ok { - return rf(globalIndex) - } - if rf, ok := ret.Get(0).(func(*big.Int) claimsponsor.ClaimStatus); ok { - r0 = rf(globalIndex) - } else { - r0 = ret.Get(0).(claimsponsor.ClaimStatus) - } - - if rf, ok := ret.Get(1).(func(*big.Int) error); ok { - r1 = rf(globalIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// BridgeClientInterface_GetSponsoredClaimStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSponsoredClaimStatus' -type BridgeClientInterface_GetSponsoredClaimStatus_Call struct { - *mock.Call -} - -// GetSponsoredClaimStatus is a helper method to define mock.On call -// - globalIndex *big.Int -func (_e *BridgeClientInterface_Expecter) GetSponsoredClaimStatus(globalIndex interface{}) *BridgeClientInterface_GetSponsoredClaimStatus_Call { - return &BridgeClientInterface_GetSponsoredClaimStatus_Call{Call: _e.mock.On("GetSponsoredClaimStatus", globalIndex)} -} - -func (_c *BridgeClientInterface_GetSponsoredClaimStatus_Call) Run(run func(globalIndex *big.Int)) *BridgeClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(*big.Int)) - }) - return _c -} - -func (_c *BridgeClientInterface_GetSponsoredClaimStatus_Call) Return(_a0 claimsponsor.ClaimStatus, _a1 error) *BridgeClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *BridgeClientInterface_GetSponsoredClaimStatus_Call) RunAndReturn(run func(*big.Int) (claimsponsor.ClaimStatus, error)) *BridgeClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Return(run) - return _c -} - -// InjectedInfoAfterIndex provides a mock function with given fields: networkID, l1InfoTreeIndex -func (_m *BridgeClientInterface) InjectedInfoAfterIndex(networkID uint32, l1InfoTreeIndex uint32) (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called(networkID, l1InfoTreeIndex) - - if len(ret) == 0 { - panic("no return value specified for InjectedInfoAfterIndex") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf(networkID, l1InfoTreeIndex) - } - if rf, ok := ret.Get(0).(func(uint32, uint32) *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf(networkID, l1InfoTreeIndex) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func(uint32, uint32) error); ok { - r1 = rf(networkID, l1InfoTreeIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// BridgeClientInterface_InjectedInfoAfterIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InjectedInfoAfterIndex' -type BridgeClientInterface_InjectedInfoAfterIndex_Call struct { - *mock.Call -} - -// InjectedInfoAfterIndex is a helper method to define mock.On call -// - networkID uint32 -// - l1InfoTreeIndex uint32 -func (_e *BridgeClientInterface_Expecter) InjectedInfoAfterIndex(networkID interface{}, l1InfoTreeIndex interface{}) *BridgeClientInterface_InjectedInfoAfterIndex_Call { - return &BridgeClientInterface_InjectedInfoAfterIndex_Call{Call: _e.mock.On("InjectedInfoAfterIndex", networkID, l1InfoTreeIndex)} -} - -func (_c *BridgeClientInterface_InjectedInfoAfterIndex_Call) Run(run func(networkID uint32, l1InfoTreeIndex uint32)) *BridgeClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32)) - }) - return _c -} - -func (_c *BridgeClientInterface_InjectedInfoAfterIndex_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *BridgeClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *BridgeClientInterface_InjectedInfoAfterIndex_Call) RunAndReturn(run func(uint32, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)) *BridgeClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Return(run) - return _c -} - -// L1InfoTreeIndexForBridge provides a mock function with given fields: networkID, depositCount -func (_m *BridgeClientInterface) L1InfoTreeIndexForBridge(networkID uint32, depositCount uint32) (uint32, error) { - ret := _m.Called(networkID, depositCount) - - if len(ret) == 0 { - panic("no return value specified for L1InfoTreeIndexForBridge") - } - - var r0 uint32 - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32) (uint32, error)); ok { - return rf(networkID, depositCount) - } - if rf, ok := ret.Get(0).(func(uint32, uint32) uint32); ok { - r0 = rf(networkID, depositCount) - } else { - r0 = ret.Get(0).(uint32) - } - - if rf, ok := ret.Get(1).(func(uint32, uint32) error); ok { - r1 = rf(networkID, depositCount) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// BridgeClientInterface_L1InfoTreeIndexForBridge_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'L1InfoTreeIndexForBridge' -type BridgeClientInterface_L1InfoTreeIndexForBridge_Call struct { - *mock.Call -} - -// L1InfoTreeIndexForBridge is a helper method to define mock.On call -// - networkID uint32 -// - depositCount uint32 -func (_e *BridgeClientInterface_Expecter) L1InfoTreeIndexForBridge(networkID interface{}, depositCount interface{}) *BridgeClientInterface_L1InfoTreeIndexForBridge_Call { - return &BridgeClientInterface_L1InfoTreeIndexForBridge_Call{Call: _e.mock.On("L1InfoTreeIndexForBridge", networkID, depositCount)} -} - -func (_c *BridgeClientInterface_L1InfoTreeIndexForBridge_Call) Run(run func(networkID uint32, depositCount uint32)) *BridgeClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32)) - }) - return _c -} - -func (_c *BridgeClientInterface_L1InfoTreeIndexForBridge_Call) Return(_a0 uint32, _a1 error) *BridgeClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *BridgeClientInterface_L1InfoTreeIndexForBridge_Call) RunAndReturn(run func(uint32, uint32) (uint32, error)) *BridgeClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Return(run) - return _c -} - -// SponsorClaim provides a mock function with given fields: claim -func (_m *BridgeClientInterface) SponsorClaim(claim claimsponsor.Claim) error { - ret := _m.Called(claim) - - if len(ret) == 0 { - panic("no return value specified for SponsorClaim") - } - - var r0 error - if rf, ok := ret.Get(0).(func(claimsponsor.Claim) error); ok { - r0 = rf(claim) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// BridgeClientInterface_SponsorClaim_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SponsorClaim' -type BridgeClientInterface_SponsorClaim_Call struct { - *mock.Call -} - -// SponsorClaim is a helper method to define mock.On call -// - claim claimsponsor.Claim -func (_e *BridgeClientInterface_Expecter) SponsorClaim(claim interface{}) *BridgeClientInterface_SponsorClaim_Call { - return &BridgeClientInterface_SponsorClaim_Call{Call: _e.mock.On("SponsorClaim", claim)} -} - -func (_c *BridgeClientInterface_SponsorClaim_Call) Run(run func(claim claimsponsor.Claim)) *BridgeClientInterface_SponsorClaim_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(claimsponsor.Claim)) - }) - return _c -} - -func (_c *BridgeClientInterface_SponsorClaim_Call) Return(_a0 error) *BridgeClientInterface_SponsorClaim_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *BridgeClientInterface_SponsorClaim_Call) RunAndReturn(run func(claimsponsor.Claim) error) *BridgeClientInterface_SponsorClaim_Call { - _c.Call.Return(run) - return _c -} - -// NewBridgeClientInterface creates a new instance of BridgeClientInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBridgeClientInterface(t interface { - mock.TestingT - Cleanup(func()) -}) *BridgeClientInterface { - mock := &BridgeClientInterface{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_bridger.go b/rpc/mocks/mock_bridger.go deleted file mode 100644 index d0344c294..000000000 --- a/rpc/mocks/mock_bridger.go +++ /dev/null @@ -1,159 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - - common "github.com/ethereum/go-ethereum/common" - - mock "github.com/stretchr/testify/mock" - - types "github.com/0xPolygon/cdk/tree/types" -) - -// Bridger is an autogenerated mock type for the Bridger type -type Bridger struct { - mock.Mock -} - -type Bridger_Expecter struct { - mock *mock.Mock -} - -func (_m *Bridger) EXPECT() *Bridger_Expecter { - return &Bridger_Expecter{mock: &_m.Mock} -} - -// GetProof provides a mock function with given fields: ctx, depositCount, localExitRoot -func (_m *Bridger) GetProof(ctx context.Context, depositCount uint32, localExitRoot common.Hash) (types.Proof, error) { - ret := _m.Called(ctx, depositCount, localExitRoot) - - if len(ret) == 0 { - panic("no return value specified for GetProof") - } - - var r0 types.Proof - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) (types.Proof, error)); ok { - return rf(ctx, depositCount, localExitRoot) - } - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) types.Proof); ok { - r0 = rf(ctx, depositCount, localExitRoot) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Proof) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint32, common.Hash) error); ok { - r1 = rf(ctx, depositCount, localExitRoot) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Bridger_GetProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetProof' -type Bridger_GetProof_Call struct { - *mock.Call -} - -// GetProof is a helper method to define mock.On call -// - ctx context.Context -// - depositCount uint32 -// - localExitRoot common.Hash -func (_e *Bridger_Expecter) GetProof(ctx interface{}, depositCount interface{}, localExitRoot interface{}) *Bridger_GetProof_Call { - return &Bridger_GetProof_Call{Call: _e.mock.On("GetProof", ctx, depositCount, localExitRoot)} -} - -func (_c *Bridger_GetProof_Call) Run(run func(ctx context.Context, depositCount uint32, localExitRoot common.Hash)) *Bridger_GetProof_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint32), args[2].(common.Hash)) - }) - return _c -} - -func (_c *Bridger_GetProof_Call) Return(_a0 types.Proof, _a1 error) *Bridger_GetProof_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *Bridger_GetProof_Call) RunAndReturn(run func(context.Context, uint32, common.Hash) (types.Proof, error)) *Bridger_GetProof_Call { - _c.Call.Return(run) - return _c -} - -// GetRootByLER provides a mock function with given fields: ctx, ler -func (_m *Bridger) GetRootByLER(ctx context.Context, ler common.Hash) (*types.Root, error) { - ret := _m.Called(ctx, ler) - - if len(ret) == 0 { - panic("no return value specified for GetRootByLER") - } - - var r0 *types.Root - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Root, error)); ok { - return rf(ctx, ler) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Root); ok { - r0 = rf(ctx, ler) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Root) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, ler) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// Bridger_GetRootByLER_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRootByLER' -type Bridger_GetRootByLER_Call struct { - *mock.Call -} - -// GetRootByLER is a helper method to define mock.On call -// - ctx context.Context -// - ler common.Hash -func (_e *Bridger_Expecter) GetRootByLER(ctx interface{}, ler interface{}) *Bridger_GetRootByLER_Call { - return &Bridger_GetRootByLER_Call{Call: _e.mock.On("GetRootByLER", ctx, ler)} -} - -func (_c *Bridger_GetRootByLER_Call) Run(run func(ctx context.Context, ler common.Hash)) *Bridger_GetRootByLER_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *Bridger_GetRootByLER_Call) Return(_a0 *types.Root, _a1 error) *Bridger_GetRootByLER_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *Bridger_GetRootByLER_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Root, error)) *Bridger_GetRootByLER_Call { - _c.Call.Return(run) - return _c -} - -// NewBridger creates a new instance of Bridger. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewBridger(t interface { - mock.TestingT - Cleanup(func()) -}) *Bridger { - mock := &Bridger{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_claim_sponsorer.go b/rpc/mocks/mock_claim_sponsorer.go deleted file mode 100644 index 9a9ef9b5e..000000000 --- a/rpc/mocks/mock_claim_sponsorer.go +++ /dev/null @@ -1,141 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - big "math/big" - - claimsponsor "github.com/0xPolygon/cdk/claimsponsor" - mock "github.com/stretchr/testify/mock" -) - -// ClaimSponsorer is an autogenerated mock type for the ClaimSponsorer type -type ClaimSponsorer struct { - mock.Mock -} - -type ClaimSponsorer_Expecter struct { - mock *mock.Mock -} - -func (_m *ClaimSponsorer) EXPECT() *ClaimSponsorer_Expecter { - return &ClaimSponsorer_Expecter{mock: &_m.Mock} -} - -// AddClaimToQueue provides a mock function with given fields: claim -func (_m *ClaimSponsorer) AddClaimToQueue(claim *claimsponsor.Claim) error { - ret := _m.Called(claim) - - if len(ret) == 0 { - panic("no return value specified for AddClaimToQueue") - } - - var r0 error - if rf, ok := ret.Get(0).(func(*claimsponsor.Claim) error); ok { - r0 = rf(claim) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ClaimSponsorer_AddClaimToQueue_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddClaimToQueue' -type ClaimSponsorer_AddClaimToQueue_Call struct { - *mock.Call -} - -// AddClaimToQueue is a helper method to define mock.On call -// - claim *claimsponsor.Claim -func (_e *ClaimSponsorer_Expecter) AddClaimToQueue(claim interface{}) *ClaimSponsorer_AddClaimToQueue_Call { - return &ClaimSponsorer_AddClaimToQueue_Call{Call: _e.mock.On("AddClaimToQueue", claim)} -} - -func (_c *ClaimSponsorer_AddClaimToQueue_Call) Run(run func(claim *claimsponsor.Claim)) *ClaimSponsorer_AddClaimToQueue_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(*claimsponsor.Claim)) - }) - return _c -} - -func (_c *ClaimSponsorer_AddClaimToQueue_Call) Return(_a0 error) *ClaimSponsorer_AddClaimToQueue_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ClaimSponsorer_AddClaimToQueue_Call) RunAndReturn(run func(*claimsponsor.Claim) error) *ClaimSponsorer_AddClaimToQueue_Call { - _c.Call.Return(run) - return _c -} - -// GetClaim provides a mock function with given fields: globalIndex -func (_m *ClaimSponsorer) GetClaim(globalIndex *big.Int) (*claimsponsor.Claim, error) { - ret := _m.Called(globalIndex) - - if len(ret) == 0 { - panic("no return value specified for GetClaim") - } - - var r0 *claimsponsor.Claim - var r1 error - if rf, ok := ret.Get(0).(func(*big.Int) (*claimsponsor.Claim, error)); ok { - return rf(globalIndex) - } - if rf, ok := ret.Get(0).(func(*big.Int) *claimsponsor.Claim); ok { - r0 = rf(globalIndex) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*claimsponsor.Claim) - } - } - - if rf, ok := ret.Get(1).(func(*big.Int) error); ok { - r1 = rf(globalIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ClaimSponsorer_GetClaim_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetClaim' -type ClaimSponsorer_GetClaim_Call struct { - *mock.Call -} - -// GetClaim is a helper method to define mock.On call -// - globalIndex *big.Int -func (_e *ClaimSponsorer_Expecter) GetClaim(globalIndex interface{}) *ClaimSponsorer_GetClaim_Call { - return &ClaimSponsorer_GetClaim_Call{Call: _e.mock.On("GetClaim", globalIndex)} -} - -func (_c *ClaimSponsorer_GetClaim_Call) Run(run func(globalIndex *big.Int)) *ClaimSponsorer_GetClaim_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(*big.Int)) - }) - return _c -} - -func (_c *ClaimSponsorer_GetClaim_Call) Return(_a0 *claimsponsor.Claim, _a1 error) *ClaimSponsorer_GetClaim_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ClaimSponsorer_GetClaim_Call) RunAndReturn(run func(*big.Int) (*claimsponsor.Claim, error)) *ClaimSponsorer_GetClaim_Call { - _c.Call.Return(run) - return _c -} - -// NewClaimSponsorer creates a new instance of ClaimSponsorer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClaimSponsorer(t interface { - mock.TestingT - Cleanup(func()) -}) *ClaimSponsorer { - mock := &ClaimSponsorer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_client_factory_interface.go b/rpc/mocks/mock_client_factory_interface.go deleted file mode 100644 index aca7aed02..000000000 --- a/rpc/mocks/mock_client_factory_interface.go +++ /dev/null @@ -1,83 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - rpc "github.com/0xPolygon/cdk/rpc/client" - mock "github.com/stretchr/testify/mock" -) - -// ClientFactoryInterface is an autogenerated mock type for the ClientFactoryInterface type -type ClientFactoryInterface struct { - mock.Mock -} - -type ClientFactoryInterface_Expecter struct { - mock *mock.Mock -} - -func (_m *ClientFactoryInterface) EXPECT() *ClientFactoryInterface_Expecter { - return &ClientFactoryInterface_Expecter{mock: &_m.Mock} -} - -// NewClient provides a mock function with given fields: url -func (_m *ClientFactoryInterface) NewClient(url string) rpc.ClientInterface { - ret := _m.Called(url) - - if len(ret) == 0 { - panic("no return value specified for NewClient") - } - - var r0 rpc.ClientInterface - if rf, ok := ret.Get(0).(func(string) rpc.ClientInterface); ok { - r0 = rf(url) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(rpc.ClientInterface) - } - } - - return r0 -} - -// ClientFactoryInterface_NewClient_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'NewClient' -type ClientFactoryInterface_NewClient_Call struct { - *mock.Call -} - -// NewClient is a helper method to define mock.On call -// - url string -func (_e *ClientFactoryInterface_Expecter) NewClient(url interface{}) *ClientFactoryInterface_NewClient_Call { - return &ClientFactoryInterface_NewClient_Call{Call: _e.mock.On("NewClient", url)} -} - -func (_c *ClientFactoryInterface_NewClient_Call) Run(run func(url string)) *ClientFactoryInterface_NewClient_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(string)) - }) - return _c -} - -func (_c *ClientFactoryInterface_NewClient_Call) Return(_a0 rpc.ClientInterface) *ClientFactoryInterface_NewClient_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ClientFactoryInterface_NewClient_Call) RunAndReturn(run func(string) rpc.ClientInterface) *ClientFactoryInterface_NewClient_Call { - _c.Call.Return(run) - return _c -} - -// NewClientFactoryInterface creates a new instance of ClientFactoryInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClientFactoryInterface(t interface { - mock.TestingT - Cleanup(func()) -}) *ClientFactoryInterface { - mock := &ClientFactoryInterface{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_client_interface.go b/rpc/mocks/mock_client_interface.go deleted file mode 100644 index 28b877755..000000000 --- a/rpc/mocks/mock_client_interface.go +++ /dev/null @@ -1,319 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - big "math/big" - - claimsponsor "github.com/0xPolygon/cdk/claimsponsor" - l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync" - - mock "github.com/stretchr/testify/mock" - - types "github.com/0xPolygon/cdk/rpc/types" -) - -// ClientInterface is an autogenerated mock type for the ClientInterface type -type ClientInterface struct { - mock.Mock -} - -type ClientInterface_Expecter struct { - mock *mock.Mock -} - -func (_m *ClientInterface) EXPECT() *ClientInterface_Expecter { - return &ClientInterface_Expecter{mock: &_m.Mock} -} - -// ClaimProof provides a mock function with given fields: networkID, depositCount, l1InfoTreeIndex -func (_m *ClientInterface) ClaimProof(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32) (*types.ClaimProof, error) { - ret := _m.Called(networkID, depositCount, l1InfoTreeIndex) - - if len(ret) == 0 { - panic("no return value specified for ClaimProof") - } - - var r0 *types.ClaimProof - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32, uint32) (*types.ClaimProof, error)); ok { - return rf(networkID, depositCount, l1InfoTreeIndex) - } - if rf, ok := ret.Get(0).(func(uint32, uint32, uint32) *types.ClaimProof); ok { - r0 = rf(networkID, depositCount, l1InfoTreeIndex) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.ClaimProof) - } - } - - if rf, ok := ret.Get(1).(func(uint32, uint32, uint32) error); ok { - r1 = rf(networkID, depositCount, l1InfoTreeIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ClientInterface_ClaimProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ClaimProof' -type ClientInterface_ClaimProof_Call struct { - *mock.Call -} - -// ClaimProof is a helper method to define mock.On call -// - networkID uint32 -// - depositCount uint32 -// - l1InfoTreeIndex uint32 -func (_e *ClientInterface_Expecter) ClaimProof(networkID interface{}, depositCount interface{}, l1InfoTreeIndex interface{}) *ClientInterface_ClaimProof_Call { - return &ClientInterface_ClaimProof_Call{Call: _e.mock.On("ClaimProof", networkID, depositCount, l1InfoTreeIndex)} -} - -func (_c *ClientInterface_ClaimProof_Call) Run(run func(networkID uint32, depositCount uint32, l1InfoTreeIndex uint32)) *ClientInterface_ClaimProof_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32), args[2].(uint32)) - }) - return _c -} - -func (_c *ClientInterface_ClaimProof_Call) Return(_a0 *types.ClaimProof, _a1 error) *ClientInterface_ClaimProof_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ClientInterface_ClaimProof_Call) RunAndReturn(run func(uint32, uint32, uint32) (*types.ClaimProof, error)) *ClientInterface_ClaimProof_Call { - _c.Call.Return(run) - return _c -} - -// GetSponsoredClaimStatus provides a mock function with given fields: globalIndex -func (_m *ClientInterface) GetSponsoredClaimStatus(globalIndex *big.Int) (claimsponsor.ClaimStatus, error) { - ret := _m.Called(globalIndex) - - if len(ret) == 0 { - panic("no return value specified for GetSponsoredClaimStatus") - } - - var r0 claimsponsor.ClaimStatus - var r1 error - if rf, ok := ret.Get(0).(func(*big.Int) (claimsponsor.ClaimStatus, error)); ok { - return rf(globalIndex) - } - if rf, ok := ret.Get(0).(func(*big.Int) claimsponsor.ClaimStatus); ok { - r0 = rf(globalIndex) - } else { - r0 = ret.Get(0).(claimsponsor.ClaimStatus) - } - - if rf, ok := ret.Get(1).(func(*big.Int) error); ok { - r1 = rf(globalIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ClientInterface_GetSponsoredClaimStatus_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetSponsoredClaimStatus' -type ClientInterface_GetSponsoredClaimStatus_Call struct { - *mock.Call -} - -// GetSponsoredClaimStatus is a helper method to define mock.On call -// - globalIndex *big.Int -func (_e *ClientInterface_Expecter) GetSponsoredClaimStatus(globalIndex interface{}) *ClientInterface_GetSponsoredClaimStatus_Call { - return &ClientInterface_GetSponsoredClaimStatus_Call{Call: _e.mock.On("GetSponsoredClaimStatus", globalIndex)} -} - -func (_c *ClientInterface_GetSponsoredClaimStatus_Call) Run(run func(globalIndex *big.Int)) *ClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(*big.Int)) - }) - return _c -} - -func (_c *ClientInterface_GetSponsoredClaimStatus_Call) Return(_a0 claimsponsor.ClaimStatus, _a1 error) *ClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ClientInterface_GetSponsoredClaimStatus_Call) RunAndReturn(run func(*big.Int) (claimsponsor.ClaimStatus, error)) *ClientInterface_GetSponsoredClaimStatus_Call { - _c.Call.Return(run) - return _c -} - -// InjectedInfoAfterIndex provides a mock function with given fields: networkID, l1InfoTreeIndex -func (_m *ClientInterface) InjectedInfoAfterIndex(networkID uint32, l1InfoTreeIndex uint32) (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called(networkID, l1InfoTreeIndex) - - if len(ret) == 0 { - panic("no return value specified for InjectedInfoAfterIndex") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf(networkID, l1InfoTreeIndex) - } - if rf, ok := ret.Get(0).(func(uint32, uint32) *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf(networkID, l1InfoTreeIndex) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func(uint32, uint32) error); ok { - r1 = rf(networkID, l1InfoTreeIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ClientInterface_InjectedInfoAfterIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'InjectedInfoAfterIndex' -type ClientInterface_InjectedInfoAfterIndex_Call struct { - *mock.Call -} - -// InjectedInfoAfterIndex is a helper method to define mock.On call -// - networkID uint32 -// - l1InfoTreeIndex uint32 -func (_e *ClientInterface_Expecter) InjectedInfoAfterIndex(networkID interface{}, l1InfoTreeIndex interface{}) *ClientInterface_InjectedInfoAfterIndex_Call { - return &ClientInterface_InjectedInfoAfterIndex_Call{Call: _e.mock.On("InjectedInfoAfterIndex", networkID, l1InfoTreeIndex)} -} - -func (_c *ClientInterface_InjectedInfoAfterIndex_Call) Run(run func(networkID uint32, l1InfoTreeIndex uint32)) *ClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32)) - }) - return _c -} - -func (_c *ClientInterface_InjectedInfoAfterIndex_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *ClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ClientInterface_InjectedInfoAfterIndex_Call) RunAndReturn(run func(uint32, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)) *ClientInterface_InjectedInfoAfterIndex_Call { - _c.Call.Return(run) - return _c -} - -// L1InfoTreeIndexForBridge provides a mock function with given fields: networkID, depositCount -func (_m *ClientInterface) L1InfoTreeIndexForBridge(networkID uint32, depositCount uint32) (uint32, error) { - ret := _m.Called(networkID, depositCount) - - if len(ret) == 0 { - panic("no return value specified for L1InfoTreeIndexForBridge") - } - - var r0 uint32 - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint32) (uint32, error)); ok { - return rf(networkID, depositCount) - } - if rf, ok := ret.Get(0).(func(uint32, uint32) uint32); ok { - r0 = rf(networkID, depositCount) - } else { - r0 = ret.Get(0).(uint32) - } - - if rf, ok := ret.Get(1).(func(uint32, uint32) error); ok { - r1 = rf(networkID, depositCount) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ClientInterface_L1InfoTreeIndexForBridge_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'L1InfoTreeIndexForBridge' -type ClientInterface_L1InfoTreeIndexForBridge_Call struct { - *mock.Call -} - -// L1InfoTreeIndexForBridge is a helper method to define mock.On call -// - networkID uint32 -// - depositCount uint32 -func (_e *ClientInterface_Expecter) L1InfoTreeIndexForBridge(networkID interface{}, depositCount interface{}) *ClientInterface_L1InfoTreeIndexForBridge_Call { - return &ClientInterface_L1InfoTreeIndexForBridge_Call{Call: _e.mock.On("L1InfoTreeIndexForBridge", networkID, depositCount)} -} - -func (_c *ClientInterface_L1InfoTreeIndexForBridge_Call) Run(run func(networkID uint32, depositCount uint32)) *ClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint32)) - }) - return _c -} - -func (_c *ClientInterface_L1InfoTreeIndexForBridge_Call) Return(_a0 uint32, _a1 error) *ClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ClientInterface_L1InfoTreeIndexForBridge_Call) RunAndReturn(run func(uint32, uint32) (uint32, error)) *ClientInterface_L1InfoTreeIndexForBridge_Call { - _c.Call.Return(run) - return _c -} - -// SponsorClaim provides a mock function with given fields: claim -func (_m *ClientInterface) SponsorClaim(claim claimsponsor.Claim) error { - ret := _m.Called(claim) - - if len(ret) == 0 { - panic("no return value specified for SponsorClaim") - } - - var r0 error - if rf, ok := ret.Get(0).(func(claimsponsor.Claim) error); ok { - r0 = rf(claim) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ClientInterface_SponsorClaim_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SponsorClaim' -type ClientInterface_SponsorClaim_Call struct { - *mock.Call -} - -// SponsorClaim is a helper method to define mock.On call -// - claim claimsponsor.Claim -func (_e *ClientInterface_Expecter) SponsorClaim(claim interface{}) *ClientInterface_SponsorClaim_Call { - return &ClientInterface_SponsorClaim_Call{Call: _e.mock.On("SponsorClaim", claim)} -} - -func (_c *ClientInterface_SponsorClaim_Call) Run(run func(claim claimsponsor.Claim)) *ClientInterface_SponsorClaim_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(claimsponsor.Claim)) - }) - return _c -} - -func (_c *ClientInterface_SponsorClaim_Call) Return(_a0 error) *ClientInterface_SponsorClaim_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ClientInterface_SponsorClaim_Call) RunAndReturn(run func(claimsponsor.Claim) error) *ClientInterface_SponsorClaim_Call { - _c.Call.Return(run) - return _c -} - -// NewClientInterface creates a new instance of ClientInterface. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewClientInterface(t interface { - mock.TestingT - Cleanup(func()) -}) *ClientInterface { - mock := &ClientInterface{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_l1_info_treer.go b/rpc/mocks/mock_l1_info_treer.go deleted file mode 100644 index b8a9682c5..000000000 --- a/rpc/mocks/mock_l1_info_treer.go +++ /dev/null @@ -1,626 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - - common "github.com/ethereum/go-ethereum/common" - - l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync" - - mock "github.com/stretchr/testify/mock" - - types "github.com/0xPolygon/cdk/tree/types" -) - -// L1InfoTreer is an autogenerated mock type for the L1InfoTreer type -type L1InfoTreer struct { - mock.Mock -} - -type L1InfoTreer_Expecter struct { - mock *mock.Mock -} - -func (_m *L1InfoTreer) EXPECT() *L1InfoTreer_Expecter { - return &L1InfoTreer_Expecter{mock: &_m.Mock} -} - -// GetFirstInfo provides a mock function with no fields -func (_m *L1InfoTreer) GetFirstInfo() (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for GetFirstInfo") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func() (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetFirstInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstInfo' -type L1InfoTreer_GetFirstInfo_Call struct { - *mock.Call -} - -// GetFirstInfo is a helper method to define mock.On call -func (_e *L1InfoTreer_Expecter) GetFirstInfo() *L1InfoTreer_GetFirstInfo_Call { - return &L1InfoTreer_GetFirstInfo_Call{Call: _e.mock.On("GetFirstInfo")} -} - -func (_c *L1InfoTreer_GetFirstInfo_Call) Run(run func()) *L1InfoTreer_GetFirstInfo_Call { - _c.Call.Run(func(args mock.Arguments) { - run() - }) - return _c -} - -func (_c *L1InfoTreer_GetFirstInfo_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *L1InfoTreer_GetFirstInfo_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetFirstInfo_Call) RunAndReturn(run func() (*l1infotreesync.L1InfoTreeLeaf, error)) *L1InfoTreer_GetFirstInfo_Call { - _c.Call.Return(run) - return _c -} - -// GetFirstInfoAfterBlock provides a mock function with given fields: blockNum -func (_m *L1InfoTreer) GetFirstInfoAfterBlock(blockNum uint64) (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called(blockNum) - - if len(ret) == 0 { - panic("no return value specified for GetFirstInfoAfterBlock") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func(uint64) (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf(blockNum) - } - if rf, ok := ret.Get(0).(func(uint64) *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf(blockNum) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func(uint64) error); ok { - r1 = rf(blockNum) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetFirstInfoAfterBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstInfoAfterBlock' -type L1InfoTreer_GetFirstInfoAfterBlock_Call struct { - *mock.Call -} - -// GetFirstInfoAfterBlock is a helper method to define mock.On call -// - blockNum uint64 -func (_e *L1InfoTreer_Expecter) GetFirstInfoAfterBlock(blockNum interface{}) *L1InfoTreer_GetFirstInfoAfterBlock_Call { - return &L1InfoTreer_GetFirstInfoAfterBlock_Call{Call: _e.mock.On("GetFirstInfoAfterBlock", blockNum)} -} - -func (_c *L1InfoTreer_GetFirstInfoAfterBlock_Call) Run(run func(blockNum uint64)) *L1InfoTreer_GetFirstInfoAfterBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint64)) - }) - return _c -} - -func (_c *L1InfoTreer_GetFirstInfoAfterBlock_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *L1InfoTreer_GetFirstInfoAfterBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetFirstInfoAfterBlock_Call) RunAndReturn(run func(uint64) (*l1infotreesync.L1InfoTreeLeaf, error)) *L1InfoTreer_GetFirstInfoAfterBlock_Call { - _c.Call.Return(run) - return _c -} - -// GetFirstL1InfoWithRollupExitRoot provides a mock function with given fields: rollupExitRoot -func (_m *L1InfoTreer) GetFirstL1InfoWithRollupExitRoot(rollupExitRoot common.Hash) (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called(rollupExitRoot) - - if len(ret) == 0 { - panic("no return value specified for GetFirstL1InfoWithRollupExitRoot") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func(common.Hash) (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf(rollupExitRoot) - } - if rf, ok := ret.Get(0).(func(common.Hash) *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf(rollupExitRoot) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func(common.Hash) error); ok { - r1 = rf(rollupExitRoot) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstL1InfoWithRollupExitRoot' -type L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call struct { - *mock.Call -} - -// GetFirstL1InfoWithRollupExitRoot is a helper method to define mock.On call -// - rollupExitRoot common.Hash -func (_e *L1InfoTreer_Expecter) GetFirstL1InfoWithRollupExitRoot(rollupExitRoot interface{}) *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call { - return &L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call{Call: _e.mock.On("GetFirstL1InfoWithRollupExitRoot", rollupExitRoot)} -} - -func (_c *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call) Run(run func(rollupExitRoot common.Hash)) *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(common.Hash)) - }) - return _c -} - -func (_c *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call) RunAndReturn(run func(common.Hash) (*l1infotreesync.L1InfoTreeLeaf, error)) *L1InfoTreer_GetFirstL1InfoWithRollupExitRoot_Call { - _c.Call.Return(run) - return _c -} - -// GetFirstVerifiedBatches provides a mock function with given fields: rollupID -func (_m *L1InfoTreer) GetFirstVerifiedBatches(rollupID uint32) (*l1infotreesync.VerifyBatches, error) { - ret := _m.Called(rollupID) - - if len(ret) == 0 { - panic("no return value specified for GetFirstVerifiedBatches") - } - - var r0 *l1infotreesync.VerifyBatches - var r1 error - if rf, ok := ret.Get(0).(func(uint32) (*l1infotreesync.VerifyBatches, error)); ok { - return rf(rollupID) - } - if rf, ok := ret.Get(0).(func(uint32) *l1infotreesync.VerifyBatches); ok { - r0 = rf(rollupID) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.VerifyBatches) - } - } - - if rf, ok := ret.Get(1).(func(uint32) error); ok { - r1 = rf(rollupID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetFirstVerifiedBatches_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstVerifiedBatches' -type L1InfoTreer_GetFirstVerifiedBatches_Call struct { - *mock.Call -} - -// GetFirstVerifiedBatches is a helper method to define mock.On call -// - rollupID uint32 -func (_e *L1InfoTreer_Expecter) GetFirstVerifiedBatches(rollupID interface{}) *L1InfoTreer_GetFirstVerifiedBatches_Call { - return &L1InfoTreer_GetFirstVerifiedBatches_Call{Call: _e.mock.On("GetFirstVerifiedBatches", rollupID)} -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatches_Call) Run(run func(rollupID uint32)) *L1InfoTreer_GetFirstVerifiedBatches_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32)) - }) - return _c -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatches_Call) Return(_a0 *l1infotreesync.VerifyBatches, _a1 error) *L1InfoTreer_GetFirstVerifiedBatches_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatches_Call) RunAndReturn(run func(uint32) (*l1infotreesync.VerifyBatches, error)) *L1InfoTreer_GetFirstVerifiedBatches_Call { - _c.Call.Return(run) - return _c -} - -// GetFirstVerifiedBatchesAfterBlock provides a mock function with given fields: rollupID, blockNum -func (_m *L1InfoTreer) GetFirstVerifiedBatchesAfterBlock(rollupID uint32, blockNum uint64) (*l1infotreesync.VerifyBatches, error) { - ret := _m.Called(rollupID, blockNum) - - if len(ret) == 0 { - panic("no return value specified for GetFirstVerifiedBatchesAfterBlock") - } - - var r0 *l1infotreesync.VerifyBatches - var r1 error - if rf, ok := ret.Get(0).(func(uint32, uint64) (*l1infotreesync.VerifyBatches, error)); ok { - return rf(rollupID, blockNum) - } - if rf, ok := ret.Get(0).(func(uint32, uint64) *l1infotreesync.VerifyBatches); ok { - r0 = rf(rollupID, blockNum) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.VerifyBatches) - } - } - - if rf, ok := ret.Get(1).(func(uint32, uint64) error); ok { - r1 = rf(rollupID, blockNum) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstVerifiedBatchesAfterBlock' -type L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call struct { - *mock.Call -} - -// GetFirstVerifiedBatchesAfterBlock is a helper method to define mock.On call -// - rollupID uint32 -// - blockNum uint64 -func (_e *L1InfoTreer_Expecter) GetFirstVerifiedBatchesAfterBlock(rollupID interface{}, blockNum interface{}) *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call { - return &L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call{Call: _e.mock.On("GetFirstVerifiedBatchesAfterBlock", rollupID, blockNum)} -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call) Run(run func(rollupID uint32, blockNum uint64)) *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32), args[1].(uint64)) - }) - return _c -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call) Return(_a0 *l1infotreesync.VerifyBatches, _a1 error) *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call) RunAndReturn(run func(uint32, uint64) (*l1infotreesync.VerifyBatches, error)) *L1InfoTreer_GetFirstVerifiedBatchesAfterBlock_Call { - _c.Call.Return(run) - return _c -} - -// GetInfoByIndex provides a mock function with given fields: ctx, index -func (_m *L1InfoTreer) GetInfoByIndex(ctx context.Context, index uint32) (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called(ctx, index) - - if len(ret) == 0 { - panic("no return value specified for GetInfoByIndex") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf(ctx, index) - } - if rf, ok := ret.Get(0).(func(context.Context, uint32) *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf(ctx, index) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint32) error); ok { - r1 = rf(ctx, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetInfoByIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetInfoByIndex' -type L1InfoTreer_GetInfoByIndex_Call struct { - *mock.Call -} - -// GetInfoByIndex is a helper method to define mock.On call -// - ctx context.Context -// - index uint32 -func (_e *L1InfoTreer_Expecter) GetInfoByIndex(ctx interface{}, index interface{}) *L1InfoTreer_GetInfoByIndex_Call { - return &L1InfoTreer_GetInfoByIndex_Call{Call: _e.mock.On("GetInfoByIndex", ctx, index)} -} - -func (_c *L1InfoTreer_GetInfoByIndex_Call) Run(run func(ctx context.Context, index uint32)) *L1InfoTreer_GetInfoByIndex_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint32)) - }) - return _c -} - -func (_c *L1InfoTreer_GetInfoByIndex_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *L1InfoTreer_GetInfoByIndex_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetInfoByIndex_Call) RunAndReturn(run func(context.Context, uint32) (*l1infotreesync.L1InfoTreeLeaf, error)) *L1InfoTreer_GetInfoByIndex_Call { - _c.Call.Return(run) - return _c -} - -// GetLastInfo provides a mock function with no fields -func (_m *L1InfoTreer) GetLastInfo() (*l1infotreesync.L1InfoTreeLeaf, error) { - ret := _m.Called() - - if len(ret) == 0 { - panic("no return value specified for GetLastInfo") - } - - var r0 *l1infotreesync.L1InfoTreeLeaf - var r1 error - if rf, ok := ret.Get(0).(func() (*l1infotreesync.L1InfoTreeLeaf, error)); ok { - return rf() - } - if rf, ok := ret.Get(0).(func() *l1infotreesync.L1InfoTreeLeaf); ok { - r0 = rf() - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.L1InfoTreeLeaf) - } - } - - if rf, ok := ret.Get(1).(func() error); ok { - r1 = rf() - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetLastInfo_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLastInfo' -type L1InfoTreer_GetLastInfo_Call struct { - *mock.Call -} - -// GetLastInfo is a helper method to define mock.On call -func (_e *L1InfoTreer_Expecter) GetLastInfo() *L1InfoTreer_GetLastInfo_Call { - return &L1InfoTreer_GetLastInfo_Call{Call: _e.mock.On("GetLastInfo")} -} - -func (_c *L1InfoTreer_GetLastInfo_Call) Run(run func()) *L1InfoTreer_GetLastInfo_Call { - _c.Call.Run(func(args mock.Arguments) { - run() - }) - return _c -} - -func (_c *L1InfoTreer_GetLastInfo_Call) Return(_a0 *l1infotreesync.L1InfoTreeLeaf, _a1 error) *L1InfoTreer_GetLastInfo_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetLastInfo_Call) RunAndReturn(run func() (*l1infotreesync.L1InfoTreeLeaf, error)) *L1InfoTreer_GetLastInfo_Call { - _c.Call.Return(run) - return _c -} - -// GetLastVerifiedBatches provides a mock function with given fields: rollupID -func (_m *L1InfoTreer) GetLastVerifiedBatches(rollupID uint32) (*l1infotreesync.VerifyBatches, error) { - ret := _m.Called(rollupID) - - if len(ret) == 0 { - panic("no return value specified for GetLastVerifiedBatches") - } - - var r0 *l1infotreesync.VerifyBatches - var r1 error - if rf, ok := ret.Get(0).(func(uint32) (*l1infotreesync.VerifyBatches, error)); ok { - return rf(rollupID) - } - if rf, ok := ret.Get(0).(func(uint32) *l1infotreesync.VerifyBatches); ok { - r0 = rf(rollupID) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*l1infotreesync.VerifyBatches) - } - } - - if rf, ok := ret.Get(1).(func(uint32) error); ok { - r1 = rf(rollupID) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetLastVerifiedBatches_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLastVerifiedBatches' -type L1InfoTreer_GetLastVerifiedBatches_Call struct { - *mock.Call -} - -// GetLastVerifiedBatches is a helper method to define mock.On call -// - rollupID uint32 -func (_e *L1InfoTreer_Expecter) GetLastVerifiedBatches(rollupID interface{}) *L1InfoTreer_GetLastVerifiedBatches_Call { - return &L1InfoTreer_GetLastVerifiedBatches_Call{Call: _e.mock.On("GetLastVerifiedBatches", rollupID)} -} - -func (_c *L1InfoTreer_GetLastVerifiedBatches_Call) Run(run func(rollupID uint32)) *L1InfoTreer_GetLastVerifiedBatches_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(uint32)) - }) - return _c -} - -func (_c *L1InfoTreer_GetLastVerifiedBatches_Call) Return(_a0 *l1infotreesync.VerifyBatches, _a1 error) *L1InfoTreer_GetLastVerifiedBatches_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetLastVerifiedBatches_Call) RunAndReturn(run func(uint32) (*l1infotreesync.VerifyBatches, error)) *L1InfoTreer_GetLastVerifiedBatches_Call { - _c.Call.Return(run) - return _c -} - -// GetLocalExitRoot provides a mock function with given fields: ctx, networkID, rollupExitRoot -func (_m *L1InfoTreer) GetLocalExitRoot(ctx context.Context, networkID uint32, rollupExitRoot common.Hash) (common.Hash, error) { - ret := _m.Called(ctx, networkID, rollupExitRoot) - - if len(ret) == 0 { - panic("no return value specified for GetLocalExitRoot") - } - - var r0 common.Hash - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) (common.Hash, error)); ok { - return rf(ctx, networkID, rollupExitRoot) - } - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) common.Hash); ok { - r0 = rf(ctx, networkID, rollupExitRoot) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(common.Hash) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint32, common.Hash) error); ok { - r1 = rf(ctx, networkID, rollupExitRoot) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetLocalExitRoot_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLocalExitRoot' -type L1InfoTreer_GetLocalExitRoot_Call struct { - *mock.Call -} - -// GetLocalExitRoot is a helper method to define mock.On call -// - ctx context.Context -// - networkID uint32 -// - rollupExitRoot common.Hash -func (_e *L1InfoTreer_Expecter) GetLocalExitRoot(ctx interface{}, networkID interface{}, rollupExitRoot interface{}) *L1InfoTreer_GetLocalExitRoot_Call { - return &L1InfoTreer_GetLocalExitRoot_Call{Call: _e.mock.On("GetLocalExitRoot", ctx, networkID, rollupExitRoot)} -} - -func (_c *L1InfoTreer_GetLocalExitRoot_Call) Run(run func(ctx context.Context, networkID uint32, rollupExitRoot common.Hash)) *L1InfoTreer_GetLocalExitRoot_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint32), args[2].(common.Hash)) - }) - return _c -} - -func (_c *L1InfoTreer_GetLocalExitRoot_Call) Return(_a0 common.Hash, _a1 error) *L1InfoTreer_GetLocalExitRoot_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetLocalExitRoot_Call) RunAndReturn(run func(context.Context, uint32, common.Hash) (common.Hash, error)) *L1InfoTreer_GetLocalExitRoot_Call { - _c.Call.Return(run) - return _c -} - -// GetRollupExitTreeMerkleProof provides a mock function with given fields: ctx, networkID, root -func (_m *L1InfoTreer) GetRollupExitTreeMerkleProof(ctx context.Context, networkID uint32, root common.Hash) (types.Proof, error) { - ret := _m.Called(ctx, networkID, root) - - if len(ret) == 0 { - panic("no return value specified for GetRollupExitTreeMerkleProof") - } - - var r0 types.Proof - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) (types.Proof, error)); ok { - return rf(ctx, networkID, root) - } - if rf, ok := ret.Get(0).(func(context.Context, uint32, common.Hash) types.Proof); ok { - r0 = rf(ctx, networkID, root) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(types.Proof) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, uint32, common.Hash) error); ok { - r1 = rf(ctx, networkID, root) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L1InfoTreer_GetRollupExitTreeMerkleProof_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetRollupExitTreeMerkleProof' -type L1InfoTreer_GetRollupExitTreeMerkleProof_Call struct { - *mock.Call -} - -// GetRollupExitTreeMerkleProof is a helper method to define mock.On call -// - ctx context.Context -// - networkID uint32 -// - root common.Hash -func (_e *L1InfoTreer_Expecter) GetRollupExitTreeMerkleProof(ctx interface{}, networkID interface{}, root interface{}) *L1InfoTreer_GetRollupExitTreeMerkleProof_Call { - return &L1InfoTreer_GetRollupExitTreeMerkleProof_Call{Call: _e.mock.On("GetRollupExitTreeMerkleProof", ctx, networkID, root)} -} - -func (_c *L1InfoTreer_GetRollupExitTreeMerkleProof_Call) Run(run func(ctx context.Context, networkID uint32, root common.Hash)) *L1InfoTreer_GetRollupExitTreeMerkleProof_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint32), args[2].(common.Hash)) - }) - return _c -} - -func (_c *L1InfoTreer_GetRollupExitTreeMerkleProof_Call) Return(_a0 types.Proof, _a1 error) *L1InfoTreer_GetRollupExitTreeMerkleProof_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L1InfoTreer_GetRollupExitTreeMerkleProof_Call) RunAndReturn(run func(context.Context, uint32, common.Hash) (types.Proof, error)) *L1InfoTreer_GetRollupExitTreeMerkleProof_Call { - _c.Call.Return(run) - return _c -} - -// NewL1InfoTreer creates a new instance of L1InfoTreer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewL1InfoTreer(t interface { - mock.TestingT - Cleanup(func()) -}) *L1InfoTreer { - mock := &L1InfoTreer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/mocks/mock_last_ge_rer.go b/rpc/mocks/mock_last_ge_rer.go deleted file mode 100644 index 7b338e2e7..000000000 --- a/rpc/mocks/mock_last_ge_rer.go +++ /dev/null @@ -1,94 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package mocks - -import ( - context "context" - - lastgersync "github.com/0xPolygon/cdk/lastgersync" - mock "github.com/stretchr/testify/mock" -) - -// LastGERer is an autogenerated mock type for the LastGERer type -type LastGERer struct { - mock.Mock -} - -type LastGERer_Expecter struct { - mock *mock.Mock -} - -func (_m *LastGERer) EXPECT() *LastGERer_Expecter { - return &LastGERer_Expecter{mock: &_m.Mock} -} - -// GetFirstGERAfterL1InfoTreeIndex provides a mock function with given fields: ctx, atOrAfterL1InfoTreeIndex -func (_m *LastGERer) GetFirstGERAfterL1InfoTreeIndex(ctx context.Context, atOrAfterL1InfoTreeIndex uint32) (lastgersync.Event, error) { - ret := _m.Called(ctx, atOrAfterL1InfoTreeIndex) - - if len(ret) == 0 { - panic("no return value specified for GetFirstGERAfterL1InfoTreeIndex") - } - - var r0 lastgersync.Event - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, uint32) (lastgersync.Event, error)); ok { - return rf(ctx, atOrAfterL1InfoTreeIndex) - } - if rf, ok := ret.Get(0).(func(context.Context, uint32) lastgersync.Event); ok { - r0 = rf(ctx, atOrAfterL1InfoTreeIndex) - } else { - r0 = ret.Get(0).(lastgersync.Event) - } - - if rf, ok := ret.Get(1).(func(context.Context, uint32) error); ok { - r1 = rf(ctx, atOrAfterL1InfoTreeIndex) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetFirstGERAfterL1InfoTreeIndex' -type LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call struct { - *mock.Call -} - -// GetFirstGERAfterL1InfoTreeIndex is a helper method to define mock.On call -// - ctx context.Context -// - atOrAfterL1InfoTreeIndex uint32 -func (_e *LastGERer_Expecter) GetFirstGERAfterL1InfoTreeIndex(ctx interface{}, atOrAfterL1InfoTreeIndex interface{}) *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call { - return &LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call{Call: _e.mock.On("GetFirstGERAfterL1InfoTreeIndex", ctx, atOrAfterL1InfoTreeIndex)} -} - -func (_c *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call) Run(run func(ctx context.Context, atOrAfterL1InfoTreeIndex uint32)) *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint32)) - }) - return _c -} - -func (_c *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call) Return(_a0 lastgersync.Event, _a1 error) *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call) RunAndReturn(run func(context.Context, uint32) (lastgersync.Event, error)) *LastGERer_GetFirstGERAfterL1InfoTreeIndex_Call { - _c.Call.Return(run) - return _c -} - -// NewLastGERer creates a new instance of LastGERer. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewLastGERer(t interface { - mock.TestingT - Cleanup(func()) -}) *LastGERer { - mock := &LastGERer{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/rpc/openrpc.json b/rpc/openrpc.json deleted file mode 100644 index 4e3a2518e..000000000 --- a/rpc/openrpc.json +++ /dev/null @@ -1,386 +0,0 @@ -{ - "openrpc": "1.0.0", - "info": { - "title": "CDK Endpoints", - "version": "0.0.1" - }, - "methods": [ - { - "name": "bridge_l1InfoTreeIndexForBridge", - "summary": "Returns the first L1 Info Tree index in which the bridge was included. NetworkID represents the origin network. This call needs to be done to a client of the same network were the bridge tx was sent", - "params": [ - { - "$ref": "#/components/contentDescriptors/NetworkID" - }, - { - "$ref": "#/components/contentDescriptors/DepositCount" - } - ], - "result": { - "$ref": "#/components/contentDescriptors/L1InfoTreeIndex" - }, - "examples": [ - { - "name": "example", - "params": [], - "result": { - "name": "exampleResult", - "value": "0x1" - } - } - ] - }, - { - "name": "bridge_injectedInfoAfterIndex", - "summary": "Return the first GER injected onto the network that is linked to the given index or greater. This call is useful to understand when a bridge is ready to be claimed on its destination network", - "params": [ - { - "$ref": "#/components/contentDescriptors/NetworkID" - }, - { - "$ref": "#/components/contentDescriptors/L1InfoTreeIndex" - } - ], - "result": { - "$ref": "#/components/contentDescriptors/L1InfoTreeLeaf" - }, - "examples": [ ] - }, - { - "name": "bridge_getProof", - "summary": "Gets the proof needed to perform a claim for a given bridge", - "params": [ - { - "$ref": "#/components/contentDescriptors/NetworkID" - }, - { - "$ref": "#/components/contentDescriptors/DepositCount" - }, - { - "$ref": "#/components/contentDescriptors/L1InfoTreeIndex" - } - ], - "result": { - "$ref": "#/components/contentDescriptors/Proof" - }, - "examples": [] - }, - { - "name": "bridge_sponsorClaim", - "summary": "Request to sponsor the claim tx for a given bridge", - "params": [ - { - "$ref": "#/components/contentDescriptors/SponsorClaim" - } - ], - "result": { - "name": "empty", - "schema": {"type": "null"} - }, - "examples": [] - }, - { - "name": "bridge_getSponsoredClaimStatus", - "summary": "Gets the proof needed to perform a claim for a given bridge", - "params": [ - { - "$ref": "#/components/contentDescriptors/GlobalIndex" - } - ], - "result": { - "$ref": "#/components/contentDescriptors/ClaimStatus" - }, - "examples": [] - } - ], - "components": { - "contentDescriptors": { - "NetworkID": { - "name": "networkID", - "required": true, - "schema": { - "$ref": "#/components/schemas/NetworkID" - } - }, - "DepositCount": { - "name": "depositCount", - "required": true, - "schema": { - "$ref": "#/components/schemas/DepositCount" - } - }, - "L1InfoTreeIndex": { - "name": "l1InfoTreeIndex", - "required": true, - "schema": { - "$ref": "#/components/schemas/L1InfoTreeIndex" - } - }, - "L1InfoTreeLeaf": { - "name": "l1InfoTreeLeaf", - "required": true, - "schema": { - "$ref": "#/components/schemas/L1InfoTreeLeaf" - } - }, - "Proof": { - "name": "proof", - "required": true, - "schema": { - "$ref": "#/components/schemas/Proof" - } - }, - "SponsorClaim": { - "name": "sponsorClaim", - "required": true, - "schema": { - "$ref": "#/components/schemas/SponsorClaim" - } - }, - "GlobalIndex": { - "name": "globalIndex", - "required": true, - "schema": { - "$ref": "#/components/schemas/GlobalIndex" - } - }, - "ClaimStatus": { - "name": "claimStatus", - "required": true, - "schema": { - "$ref": "#/components/schemas/ClaimStatus" - } - } - }, - "schemas": { - "Bytes": { - "title": "bytes", - "type": "string", - "description": "Hex representation of a variable length byte array", - "pattern": "^0x([a-fA-F0-9]?)+$" - }, - "Integer": { - "title": "integer", - "type": "string", - "pattern": "^0x[a-fA-F0-9]+$", - "description": "Hex representation of the integer" - }, - "Keccak": { - "title": "keccak", - "type": "string", - "description": "Hex representation of a Keccak 256 hash", - "pattern": "^0x[a-fA-F\\d]{64}$" - }, - "Address": { - "title": "address", - "type": "string", - "pattern": "^0x[a-fA-F\\d]{40}$" - }, - "BlockHash": { - "title": "blockHash", - "type": "string", - "pattern": "^0x[a-fA-F\\d]{64}$", - "description": "The hex representation of the Keccak 256 of the RLP encoded block" - }, - "BlockNumber": { - "title": "blockNumber", - "type": "string", - "description": "The hex representation of the block's height", - "$ref": "#/components/schemas/Integer" - }, - "BlockPosition": { - "title": "blockPosition", - "type": "string", - "description": "The hex representation of the position inside the block", - "$ref": "#/components/schemas/Integer" - }, - "NetworkID": { - "title": "networkID", - "type": "string", - "description": "The hex representation of the network ID", - "$ref": "#/components/schemas/Integer" - }, - "DepositCount": { - "title": "depositCount", - "type": "string", - "description": "The hex representation of the deposit count", - "$ref": "#/components/schemas/Integer" - }, - "L1InfoTreeIndex": { - "title": "l1InfoTreeIndex", - "type": "string", - "description": "The hex representation of the L1 info tree index", - "$ref": "#/components/schemas/Integer" - }, - "L1InfoTreeLeaf": { - "title": "l1InfoTreeLeaf", - "type": "object", - "readOnly": true, - "properties": { - "blockNumber": { - "$ref": "#/components/schemas/BlockNumber" - }, - "blockPosition": { - "$ref": "#/components/schemas/BlockPosition" - }, - "previousBlockHash": { - "$ref": "#/components/schemas/Keccak" - }, - "timestamp": { - "title": "blockTimeStamp", - "type": "string", - "description": "The unix timestamp for when the block was collated" - }, - "l1InfoTreeIndex": { - "$ref": "#/components/schemas/L1InfoTreeIndex" - }, - "mainnetExitRoot": { - "$ref": "#/components/schemas/Keccak" - }, - "rollupExitRoot": { - "$ref": "#/components/schemas/Keccak" - }, - "globalExitRoot": { - "$ref": "#/components/schemas/Keccak" - }, - "hash": { - "$ref": "#/components/schemas/Keccak" - } - } - }, - "MerkleProof": { - "title": "merkleProof", - "type": "array", - "description": "Array of hashes that constitute a merkle proof", - "items": { - "$ref": "#/components/schemas/Keccak" - } - }, - "ProofLocalExitRoot": { - "title": "proofLocalExitRoot", - "description": "Merkle Proof that proofs the existance of a deposit in the local exit tree of a network", - "$ref": "#/components/schemas/MerkleProof" - }, - "ProofRollupExitRoot": { - "title": "proofLocalExitRoot", - "description": "Merkle Proof that proofs the existance of a deposit in the local exit tree of a network", - "$ref": "#/components/schemas/MerkleProof" - }, - "Proof": { - "title": "proof", - "type": "object", - "readOnly": true, - "properties": { - "l1InfoTreeLeaf": { - "$ref": "#/components/schemas/L1InfoTreeLeaf" - }, - "proofLocalExitRoot": { - "$ref": "#/components/schemas/ProofLocalExitRoot" - }, - "proofRollupExitRoot": { - "$ref": "#/components/schemas/ProofRollupExitRoot" - } - } - }, - "LeafType": { - "title": "leafType", - "type": "string", - "description": "The hex representation of the leaf type", - "$ref": "#/components/schemas/Integer" - }, - "GlobalIndex": { - "title": "globalIndex", - "type": "string", - "description": "The hex representation of the global index", - "$ref": "#/components/schemas/Integer" - }, - "OriginNetwork": { - "title": "originNetwork", - "type": "string", - "description": "The hex representation of the origin network ID of the token", - "$ref": "#/components/schemas/Integer" - }, - "OriginTokenAddress": { - "title": "originTokenAddress", - "type": "string", - "description": "address of the token on it's origin network", - "$ref": "#/components/schemas/Address" - }, - "DestinationNetwork": { - "title": "destinationNetwork", - "type": "string", - "description": "The hex representation of the destination network ID", - "$ref": "#/components/schemas/Integer" - }, - "DestinationAddress": { - "title": "destinationAddress", - "type": "string", - "description": "address of the receiver of the bridge", - "$ref": "#/components/schemas/Address" - }, - "Amount": { - "title": "amount", - "description": "Amount of tokens being bridged", - "$ref": "#/components/schemas/Keccak" - }, - "Metadata": { - "title": "metadata", - "description": "Extra data included in the bridge", - "$ref": "#/components/schemas/Bytes" - }, - "SponsorClaim": { - "title": "sponsorClaim", - "type": "object", - "readOnly": true, - "properties": { - "leafType": { - "$ref": "#/components/schemas/LeafType" - }, - "proofLocalExitRoot": { - "$ref": "#/components/schemas/ProofLocalExitRoot" - }, - "proofRollupExitRoot": { - "$ref": "#/components/schemas/ProofRollupExitRoot" - }, - "globalIndex": { - "$ref": "#/components/schemas/GlobalIndex" - }, - "mainnetExitRoot": { - "$ref": "#/components/schemas/Keccak" - }, - "rollupExitRoot": { - "$ref": "#/components/schemas/Keccak" - }, - "originNetwork": { - "$ref": "#/components/schemas/OriginNetwork" - }, - "originTokenAddress": { - "$ref": "#/components/schemas/OriginTokenAddress" - }, - "destinationNetwork": { - "$ref": "#/components/schemas/DestinationNetwork" - }, - "destinationAddress": { - "$ref": "#/components/schemas/DestinationAddress" - }, - "amount": { - "$ref": "#/components/schemas/Amount" - }, - "metadata": { - "$ref": "#/components/schemas/Metadata" - } - } - }, - "ClaimStatus": { - "title": "claimStatus", - "description": "The status of a claim", - "type": "string", - "enum": [ - "pending", - "failed", - "success" - ] - } - } - } -} diff --git a/rpc/types/bridge.go b/rpc/types/bridge.go deleted file mode 100644 index eb8c64645..000000000 --- a/rpc/types/bridge.go +++ /dev/null @@ -1,12 +0,0 @@ -package types - -import ( - "github.com/0xPolygon/cdk/l1infotreesync" - tree "github.com/0xPolygon/cdk/tree/types" -) - -type ClaimProof struct { - ProofLocalExitRoot tree.Proof - ProofRollupExitRoot tree.Proof - L1InfoTreeLeaf l1infotreesync.L1InfoTreeLeaf -} diff --git a/sequencesender/config.go b/sequencesender/config.go index 4f77500b2..80f473621 100644 --- a/sequencesender/config.go +++ b/sequencesender/config.go @@ -2,8 +2,8 @@ package sequencesender import ( "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ) diff --git a/sequencesender/ethtx.go b/sequencesender/ethtx.go index 3234992e4..b71324fc0 100644 --- a/sequencesender/ethtx.go +++ b/sequencesender/ethtx.go @@ -11,9 +11,9 @@ import ( "sync/atomic" "time" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ) diff --git a/sequencesender/ethtx_test.go b/sequencesender/ethtx_test.go index 1bc21535a..5cf915c64 100644 --- a/sequencesender/ethtx_test.go +++ b/sequencesender/ethtx_test.go @@ -9,10 +9,10 @@ import ( "testing" "time" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/mocks" "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" diff --git a/sequencesender/mocks/mock_eth_tx_manager.go b/sequencesender/mocks/mock_eth_tx_manager.go index 3d0ebebcd..62c6352ea 100644 --- a/sequencesender/mocks/mock_eth_tx_manager.go +++ b/sequencesender/mocks/mock_eth_tx_manager.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/sequencesender/mocks/mock_etherman.go b/sequencesender/mocks/mock_etherman.go index 298d96c3b..72bc1a023 100644 --- a/sequencesender/mocks/mock_etherman.go +++ b/sequencesender/mocks/mock_etherman.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/sequencesender/mocks/mock_rpc_interface.go b/sequencesender/mocks/mock_rpc_interface.go index eef0188df..7a2b9950a 100644 --- a/sequencesender/mocks/mock_rpc_interface.go +++ b/sequencesender/mocks/mock_rpc_interface.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/sequencesender/mocks/mock_tx_builder.go b/sequencesender/mocks/mock_tx_builder.go index ecc0e44e0..70738e5e8 100644 --- a/sequencesender/mocks/mock_tx_builder.go +++ b/sequencesender/mocks/mock_tx_builder.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/sequencesender/sequencesender.go b/sequencesender/sequencesender.go index 634e08cf8..41a56709b 100644 --- a/sequencesender/sequencesender.go +++ b/sequencesender/sequencesender.go @@ -11,7 +11,6 @@ import ( "time" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/rpc" "github.com/0xPolygon/cdk/rpc/types" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" @@ -20,6 +19,7 @@ import ( "github.com/0xPolygon/zkevm-ethtx-manager/ethtxmanager" ethtxlog "github.com/0xPolygon/zkevm-ethtx-manager/log" ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ethtypes "github.com/ethereum/go-ethereum/core/types" ) diff --git a/sequencesender/sequencesender_test.go b/sequencesender/sequencesender_test.go index e1d694e5b..052719d34 100644 --- a/sequencesender/sequencesender_test.go +++ b/sequencesender/sequencesender_test.go @@ -9,13 +9,13 @@ import ( types2 "github.com/0xPolygon/cdk/config/types" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" rpctypes "github.com/0xPolygon/cdk/rpc/types" "github.com/0xPolygon/cdk/sequencesender/mocks" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/state" ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" "github.com/stretchr/testify/mock" diff --git a/sequencesender/txbuilder/banana_base.go b/sequencesender/txbuilder/banana_base.go index ee21228d0..009149340 100644 --- a/sequencesender/txbuilder/banana_base.go +++ b/sequencesender/txbuilder/banana_base.go @@ -8,10 +8,10 @@ import ( cdkcommon "github.com/0xPolygon/cdk/common" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/banana_base_test.go b/sequencesender/txbuilder/banana_base_test.go index e59115005..dd2854b4d 100644 --- a/sequencesender/txbuilder/banana_base_test.go +++ b/sequencesender/txbuilder/banana_base_test.go @@ -6,12 +6,12 @@ import ( "math/big" "testing" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/sequencesender/txbuilder/mocks_txbuilder" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/banana_validium.go b/sequencesender/txbuilder/banana_validium.go index 68fa67622..586a44754 100644 --- a/sequencesender/txbuilder/banana_validium.go +++ b/sequencesender/txbuilder/banana_validium.go @@ -8,8 +8,8 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/banana/polygonvalidiumetrog" "github.com/0xPolygon/cdk/dataavailability" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/banana_validium_test.go b/sequencesender/txbuilder/banana_validium_test.go index 71f059b98..19f6f1874 100644 --- a/sequencesender/txbuilder/banana_validium_test.go +++ b/sequencesender/txbuilder/banana_validium_test.go @@ -8,12 +8,12 @@ import ( "testing" "github.com/0xPolygon/cdk/dataavailability/mocks_da" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/sequencesender/txbuilder/mocks_txbuilder" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/banana_zkevm.go b/sequencesender/txbuilder/banana_zkevm.go index 42668323c..199da0438 100644 --- a/sequencesender/txbuilder/banana_zkevm.go +++ b/sequencesender/txbuilder/banana_zkevm.go @@ -6,8 +6,8 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/banana/polygonvalidiumetrog" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/banana_zkevm_test.go b/sequencesender/txbuilder/banana_zkevm_test.go index 4570729e7..4230783b8 100644 --- a/sequencesender/txbuilder/banana_zkevm_test.go +++ b/sequencesender/txbuilder/banana_zkevm_test.go @@ -7,12 +7,12 @@ import ( "strings" "testing" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/sequencesender/txbuilder/mocks_txbuilder" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/elderberry_base.go b/sequencesender/txbuilder/elderberry_base.go index 8e61e174b..7f2bffa52 100644 --- a/sequencesender/txbuilder/elderberry_base.go +++ b/sequencesender/txbuilder/elderberry_base.go @@ -4,9 +4,9 @@ import ( "context" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" ) diff --git a/sequencesender/txbuilder/elderberry_base_test.go b/sequencesender/txbuilder/elderberry_base_test.go index 806a47f87..1d518c605 100644 --- a/sequencesender/txbuilder/elderberry_base_test.go +++ b/sequencesender/txbuilder/elderberry_base_test.go @@ -4,9 +4,9 @@ import ( "context" "testing" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/stretchr/testify/require" diff --git a/sequencesender/txbuilder/elderberry_validium.go b/sequencesender/txbuilder/elderberry_validium.go index 62973b025..9f769e7e2 100644 --- a/sequencesender/txbuilder/elderberry_validium.go +++ b/sequencesender/txbuilder/elderberry_validium.go @@ -10,8 +10,8 @@ import ( "github.com/0xPolygon/cdk/dataavailability" "github.com/0xPolygon/cdk/etherman" "github.com/0xPolygon/cdk/etherman/contracts" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/elderberry_validium_test.go b/sequencesender/txbuilder/elderberry_validium_test.go index 6ca80a58b..92e22c367 100644 --- a/sequencesender/txbuilder/elderberry_validium_test.go +++ b/sequencesender/txbuilder/elderberry_validium_test.go @@ -10,10 +10,10 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/elderberry/polygonvalidiumetrog" "github.com/0xPolygon/cdk/dataavailability/mocks_da" "github.com/0xPolygon/cdk/etherman/contracts" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" diff --git a/sequencesender/txbuilder/elderberry_zkevm.go b/sequencesender/txbuilder/elderberry_zkevm.go index a4d3bb567..c784d595e 100644 --- a/sequencesender/txbuilder/elderberry_zkevm.go +++ b/sequencesender/txbuilder/elderberry_zkevm.go @@ -7,8 +7,8 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/elderberry/polygonvalidiumetrog" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/sequencesender/txbuilder/elderberry_zkevm_test.go b/sequencesender/txbuilder/elderberry_zkevm_test.go index 3544a7009..3afeba2de 100644 --- a/sequencesender/txbuilder/elderberry_zkevm_test.go +++ b/sequencesender/txbuilder/elderberry_zkevm_test.go @@ -8,10 +8,10 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/elderberry/polygonvalidiumetrog" "github.com/0xPolygon/cdk/etherman/contracts" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" "github.com/0xPolygon/cdk/sequencesender/txbuilder" "github.com/0xPolygon/cdk/state/datastream" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/crypto" diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_cond_new_sequence.go b/sequencesender/txbuilder/mocks_txbuilder/mock_cond_new_sequence.go index ae818ce98..d38905526 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_cond_new_sequence.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_cond_new_sequence.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_contractor.go index 86fd4366b..1c952c660 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_zkevm_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_zkevm_contractor.go index 57c6c1576..7006660f3 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_zkevm_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_global_exit_root_banana_zkevm_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_l1_client.go b/sequencesender/txbuilder/mocks_txbuilder/mock_l1_client.go index 853494f98..c7ff99fc0 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_l1_client.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_l1_client.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_l1_info_syncer.go b/sequencesender/txbuilder/mocks_txbuilder/mock_l1_info_syncer.go index 12d641a83..c88b38318 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_l1_info_syncer.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_l1_info_syncer.go @@ -1,11 +1,11 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder import ( context "context" - l1infotreesync "github.com/0xPolygon/cdk/l1infotreesync" + l1infotreesync "github.com/agglayer/aggkit/l1infotreesync" mock "github.com/stretchr/testify/mock" ) diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_base_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_base_contractor.go index acd82a4ee..4d06e8c8d 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_base_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_base_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_validium_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_validium_contractor.go index a59b88dd5..ef98103f9 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_validium_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_validium_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_zkevm_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_zkevm_contractor.go index e29e32529..77b70a13a 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_zkevm_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_banana_zkevm_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_validium_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_validium_contractor.go index 0d94c0810..9b3d35d5a 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_validium_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_validium_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_zkevm_contractor.go b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_zkevm_contractor.go index 1ed208ab2..db5beac34 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_zkevm_contractor.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_rollup_elderberry_zkevm_contractor.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/mocks_txbuilder/mock_tx_builder.go b/sequencesender/txbuilder/mocks_txbuilder/mock_tx_builder.go index 32ab8ab49..3eda5fdd3 100644 --- a/sequencesender/txbuilder/mocks_txbuilder/mock_tx_builder.go +++ b/sequencesender/txbuilder/mocks_txbuilder/mock_tx_builder.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks_txbuilder diff --git a/sequencesender/txbuilder/validium_cond_num_batches.go b/sequencesender/txbuilder/validium_cond_num_batches.go index 35173d8e6..13434cc68 100644 --- a/sequencesender/txbuilder/validium_cond_num_batches.go +++ b/sequencesender/txbuilder/validium_cond_num_batches.go @@ -3,8 +3,8 @@ package txbuilder import ( "context" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ) diff --git a/sequencesender/txbuilder/zkevm_cond_max_size.go b/sequencesender/txbuilder/zkevm_cond_max_size.go index 66eb94461..100d1403a 100644 --- a/sequencesender/txbuilder/zkevm_cond_max_size.go +++ b/sequencesender/txbuilder/zkevm_cond_max_size.go @@ -6,8 +6,8 @@ import ( "fmt" "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/sequencesender/seqsendertypes" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/common" ) diff --git a/state/encoding_batch_v2.go b/state/encoding_batch_v2.go index f058f072f..947825edd 100644 --- a/state/encoding_batch_v2.go +++ b/state/encoding_batch_v2.go @@ -56,8 +56,8 @@ import ( "fmt" "strconv" - "github.com/0xPolygon/cdk/hex" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/hex" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" ) diff --git a/state/encoding_batch_v2_test.go b/state/encoding_batch_v2_test.go index d263b5c79..e8eb94545 100644 --- a/state/encoding_batch_v2_test.go +++ b/state/encoding_batch_v2_test.go @@ -3,8 +3,8 @@ package state import ( "testing" - "github.com/0xPolygon/cdk/hex" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/hex" + "github.com/agglayer/aggkit/log" "github.com/stretchr/testify/require" ) diff --git a/state/helper.go b/state/helper.go index 7f2b64be5..4ddd0dfcd 100644 --- a/state/helper.go +++ b/state/helper.go @@ -6,8 +6,8 @@ import ( "math/big" "strconv" - "github.com/0xPolygon/cdk/hex" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/hex" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/core/types" "github.com/ethereum/go-ethereum/rlp" ) diff --git a/sync/common.go b/sync/common.go deleted file mode 100644 index 9e1129690..000000000 --- a/sync/common.go +++ /dev/null @@ -1,31 +0,0 @@ -package sync - -import ( - "log" - "sync" - "time" -) - -type RetryHandler struct { - RetryAfterErrorPeriod time.Duration - MaxRetryAttemptsAfterError int -} - -func (h *RetryHandler) Handle(funcName string, attempts int) { - if h.MaxRetryAttemptsAfterError > -1 && attempts >= h.MaxRetryAttemptsAfterError { - log.Fatalf( - "%s failed too many times (%d)", - funcName, h.MaxRetryAttemptsAfterError, - ) - } - time.Sleep(h.RetryAfterErrorPeriod) -} - -func UnhaltIfAffectedRows(halted *bool, haltedReason *string, mu *sync.RWMutex, rowsAffected int64) { - if rowsAffected > 0 { - mu.Lock() - defer mu.Unlock() - *halted = false - *haltedReason = "" - } -} diff --git a/sync/driver.go b/sync/driver.go deleted file mode 100644 index 7d3068fbb..000000000 --- a/sync/driver.go +++ /dev/null @@ -1,22 +0,0 @@ -package sync - -import ( - "context" - "errors" - - "github.com/ethereum/go-ethereum/common" -) - -var ErrInconsistentState = errors.New("state is inconsistent, try again later once the state is consolidated") - -type Block struct { - Num uint64 - Events []interface{} - Hash common.Hash -} - -type ProcessorInterface interface { - GetLastProcessedBlock(ctx context.Context) (uint64, error) - ProcessBlock(block Block) error - Reorg(firstReorgedBlock uint64) error -} diff --git a/sync/evmdownloader.go b/sync/evmdownloader.go deleted file mode 100644 index 1de2be732..000000000 --- a/sync/evmdownloader.go +++ /dev/null @@ -1,386 +0,0 @@ -package sync - -import ( - "context" - "errors" - "fmt" - "math/big" - "time" - - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/accounts/abi/bind" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" -) - -const ( - DefaultWaitPeriodBlockNotFound = time.Millisecond * 100 -) - -type EthClienter interface { - ethereum.LogFilterer - ethereum.BlockNumberReader - ethereum.ChainReader - bind.ContractBackend -} - -type EVMDownloaderInterface interface { - WaitForNewBlocks(ctx context.Context, lastBlockSeen uint64) (newLastBlock uint64) - GetEventsByBlockRange(ctx context.Context, fromBlock, toBlock uint64) EVMBlocks - GetLogs(ctx context.Context, fromBlock, toBlock uint64) []types.Log - GetBlockHeader(ctx context.Context, blockNum uint64) (EVMBlockHeader, bool) - GetLastFinalizedBlock(ctx context.Context) (*types.Header, error) -} - -type LogAppenderMap map[common.Hash]func(b *EVMBlock, l types.Log) error - -type EVMDownloader struct { - syncBlockChunkSize uint64 - EVMDownloaderInterface - log *log.Logger - finalizedBlockType etherman.BlockNumberFinality -} - -func NewEVMDownloader( - syncerID string, - ethClient EthClienter, - syncBlockChunkSize uint64, - blockFinalityType etherman.BlockNumberFinality, - waitForNewBlocksPeriod time.Duration, - appender LogAppenderMap, - adressessToQuery []common.Address, - rh *RetryHandler, - finalizedBlockType etherman.BlockNumberFinality, -) (*EVMDownloader, error) { - logger := log.WithFields("syncer", syncerID) - finality, err := blockFinalityType.ToBlockNum() - if err != nil { - return nil, err - } - - topicsToQuery := make([]common.Hash, 0, len(appender)) - for topic := range appender { - topicsToQuery = append(topicsToQuery, topic) - } - - fbtEthermanType := finalizedBlockType - fbt, err := finalizedBlockType.ToBlockNum() - if err != nil { - return nil, err - } - - if fbt.Cmp(finality) > 0 { - // if someone configured the syncer to query blocks by Safe or Finalized block - // finalized block type should be at least the same as the block finality - fbt = finality - fbtEthermanType = blockFinalityType - logger.Warnf("finalized block type %s is greater than block finality %s, setting finalized block type to %s", - finalizedBlockType, blockFinalityType, fbtEthermanType) - } - - logger.Infof("downloader initialized with block finality: %s, finalized block type: %s. SyncChunkSize: %d", - blockFinalityType, fbtEthermanType, syncBlockChunkSize) - - return &EVMDownloader{ - syncBlockChunkSize: syncBlockChunkSize, - log: logger, - finalizedBlockType: fbtEthermanType, - EVMDownloaderInterface: &EVMDownloaderImplementation{ - ethClient: ethClient, - blockFinality: finality, - waitForNewBlocksPeriod: waitForNewBlocksPeriod, - appender: appender, - topicsToQuery: topicsToQuery, - adressessToQuery: adressessToQuery, - rh: rh, - log: logger, - finalizedBlockType: fbt, - }, - }, nil -} - -func (d *EVMDownloader) Download(ctx context.Context, fromBlock uint64, downloadedCh chan EVMBlock) { - lastBlock := d.WaitForNewBlocks(ctx, 0) - - for { - select { - case <-ctx.Done(): - d.log.Info("closing evm downloader channel") - close(downloadedCh) - return - default: - } - - toBlock := fromBlock + d.syncBlockChunkSize - if toBlock > lastBlock { - toBlock = lastBlock - } - - if fromBlock > toBlock { - d.log.Infof( - "waiting for new blocks, last block processed: %d, last block seen on L1: %d", - fromBlock-1, lastBlock, - ) - lastBlock = d.WaitForNewBlocks(ctx, fromBlock-1) - continue - } - - lastFinalizedBlock, err := d.GetLastFinalizedBlock(ctx) - if err != nil { - d.log.Error("error getting last finalized block: ", err) - continue - } - - lastFinalizedBlockNumber := lastFinalizedBlock.Number.Uint64() - - d.log.Infof("getting events from blocks %d to %d. lastFinalizedBlock: %d", - fromBlock, toBlock, lastFinalizedBlockNumber) - blocks := d.GetEventsByBlockRange(ctx, fromBlock, toBlock) - - if toBlock <= lastFinalizedBlockNumber { - d.reportBlocks(downloadedCh, blocks, lastFinalizedBlockNumber) - fromBlock = toBlock + 1 - - if blocks.Len() == 0 || blocks[blocks.Len()-1].Num < toBlock { - d.reportEmptyBlock(ctx, downloadedCh, toBlock, lastFinalizedBlockNumber) - } - } else { - d.reportBlocks(downloadedCh, blocks, lastFinalizedBlockNumber) - - if blocks.Len() == 0 { - if lastFinalizedBlockNumber > fromBlock && - lastFinalizedBlockNumber-fromBlock > d.syncBlockChunkSize { - d.reportEmptyBlock(ctx, downloadedCh, fromBlock+d.syncBlockChunkSize, lastFinalizedBlockNumber) - fromBlock += d.syncBlockChunkSize + 1 - } - } else { - fromBlock = blocks[blocks.Len()-1].Num + 1 - } - } - } -} - -func (d *EVMDownloader) reportBlocks(downloadedCh chan EVMBlock, blocks EVMBlocks, lastFinalizedBlock uint64) { - for _, block := range blocks { - d.log.Infof("sending block %d to the driver (with events)", block.Num) - block.IsFinalizedBlock = d.finalizedBlockType.IsFinalized() && block.Num <= lastFinalizedBlock - downloadedCh <- *block - } -} - -func (d *EVMDownloader) reportEmptyBlock(ctx context.Context, downloadedCh chan EVMBlock, - blockNum, lastFinalizedBlock uint64) { - // Indicate the last downloaded block if there are not events on it - d.log.Debugf("sending block %d to the driver (without events)", blockNum) - header, isCanceled := d.GetBlockHeader(ctx, blockNum) - if isCanceled { - return - } - - downloadedCh <- EVMBlock{ - IsFinalizedBlock: d.finalizedBlockType.IsFinalized() && header.Num <= lastFinalizedBlock, - EVMBlockHeader: header, - } -} - -type EVMDownloaderImplementation struct { - ethClient EthClienter - blockFinality *big.Int - waitForNewBlocksPeriod time.Duration - appender LogAppenderMap - topicsToQuery []common.Hash - adressessToQuery []common.Address - rh *RetryHandler - log *log.Logger - finalizedBlockType *big.Int -} - -func NewEVMDownloaderImplementation( - syncerID string, - ethClient EthClienter, - blockFinality *big.Int, - waitForNewBlocksPeriod time.Duration, - appender LogAppenderMap, - topicsToQuery []common.Hash, - adressessToQuery []common.Address, - rh *RetryHandler, -) *EVMDownloaderImplementation { - logger := log.WithFields("syncer", syncerID) - return &EVMDownloaderImplementation{ - ethClient: ethClient, - blockFinality: blockFinality, - waitForNewBlocksPeriod: waitForNewBlocksPeriod, - appender: appender, - topicsToQuery: topicsToQuery, - adressessToQuery: adressessToQuery, - rh: rh, - log: logger, - } -} - -func (d *EVMDownloaderImplementation) GetLastFinalizedBlock(ctx context.Context) (*types.Header, error) { - return d.ethClient.HeaderByNumber(ctx, d.finalizedBlockType) -} - -func (d *EVMDownloaderImplementation) WaitForNewBlocks( - ctx context.Context, lastBlockSeen uint64, -) (newLastBlock uint64) { - attempts := 0 - ticker := time.NewTicker(d.waitForNewBlocksPeriod) - defer ticker.Stop() - for { - select { - case <-ctx.Done(): - d.log.Info("context cancelled") - return lastBlockSeen - case <-ticker.C: - header, err := d.ethClient.HeaderByNumber(ctx, d.blockFinality) - if err != nil { - if ctx.Err() == nil { - attempts++ - d.log.Error("error getting last block num from eth client: ", err) - d.rh.Handle("waitForNewBlocks", attempts) - } else { - d.log.Warn("context has been canceled while trying to get header by number") - } - continue - } - if header.Number.Uint64() > lastBlockSeen { - return header.Number.Uint64() - } - } - } -} - -func (d *EVMDownloaderImplementation) GetEventsByBlockRange(ctx context.Context, fromBlock, toBlock uint64) EVMBlocks { - select { - case <-ctx.Done(): - return nil - default: - blocks := EVMBlocks{} - logs := d.GetLogs(ctx, fromBlock, toBlock) - for _, l := range logs { - if len(blocks) == 0 || blocks[len(blocks)-1].Num < l.BlockNumber { - b, canceled := d.GetBlockHeader(ctx, l.BlockNumber) - if canceled { - return nil - } - - if b.Hash != l.BlockHash { - d.log.Infof( - "there has been a block hash change between the event query and the block query "+ - "for block %d: %s vs %s. Retrying.", - l.BlockNumber, b.Hash, l.BlockHash, - ) - return d.GetEventsByBlockRange(ctx, fromBlock, toBlock) - } - blocks = append(blocks, &EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: l.BlockNumber, - Hash: l.BlockHash, - Timestamp: b.Timestamp, - ParentHash: b.ParentHash, - }, - Events: []interface{}{}, - }) - } - - for { - attempts := 0 - err := d.appender[l.Topics[0]](blocks[len(blocks)-1], l) - if err != nil { - attempts++ - d.log.Error("error trying to append log: ", err) - d.rh.Handle("getLogs", attempts) - continue - } - break - } - } - - return blocks - } -} - -func filterQueryToString(query ethereum.FilterQuery) string { - return fmt.Sprintf("FromBlock: %s, ToBlock: %s, Addresses: %s, Topics: %s", - query.FromBlock.String(), query.ToBlock.String(), query.Addresses, query.Topics) -} - -func (d *EVMDownloaderImplementation) GetLogs(ctx context.Context, fromBlock, toBlock uint64) []types.Log { - query := ethereum.FilterQuery{ - FromBlock: new(big.Int).SetUint64(fromBlock), - Addresses: d.adressessToQuery, - ToBlock: new(big.Int).SetUint64(toBlock), - } - var ( - attempts = 0 - unfilteredLogs []types.Log - err error - ) - for { - unfilteredLogs, err = d.ethClient.FilterLogs(ctx, query) - if err != nil { - if errors.Is(err, context.Canceled) { - // context is canceled, we don't want to fatal on max attempts in this case - return nil - } - - attempts++ - d.log.Errorf("error calling FilterLogs to eth client: filter: %s err:%w ", - filterQueryToString(query), - err, - ) - d.rh.Handle("getLogs", attempts) - continue - } - break - } - logs := make([]types.Log, 0, len(unfilteredLogs)) - for _, l := range unfilteredLogs { - for _, topic := range d.topicsToQuery { - if l.Topics[0] == topic { - logs = append(logs, l) - break - } - } - } - return logs -} - -func (d *EVMDownloaderImplementation) GetBlockHeader(ctx context.Context, blockNum uint64) (EVMBlockHeader, bool) { - attempts := 0 - for { - header, err := d.ethClient.HeaderByNumber(ctx, new(big.Int).SetUint64(blockNum)) - if err != nil { - if errors.Is(err, context.Canceled) { - // context is canceled, we don't want to fatal on max attempts in this case - return EVMBlockHeader{}, true - } - if errors.Is(err, ethereum.NotFound) { - // block num can temporary disappear from the execution client due to a reorg, - // in this case, we want to wait and not panic - log.Warnf("block %d not found on the ethereum client: %v", blockNum, err) - if d.rh.RetryAfterErrorPeriod != 0 { - time.Sleep(d.rh.RetryAfterErrorPeriod) - } else { - time.Sleep(DefaultWaitPeriodBlockNotFound) - } - continue - } - - attempts++ - d.log.Errorf("error getting block header for block %d, err: %v", blockNum, err) - d.rh.Handle("getBlockHeader", attempts) - continue - } - return EVMBlockHeader{ - Num: header.Number.Uint64(), - Hash: header.Hash(), - ParentHash: header.ParentHash, - Timestamp: header.Time, - }, false - } -} diff --git a/sync/evmdownloader_test.go b/sync/evmdownloader_test.go deleted file mode 100644 index b4c600f16..000000000 --- a/sync/evmdownloader_test.go +++ /dev/null @@ -1,514 +0,0 @@ -package sync - -import ( - "context" - "errors" - "math/big" - "strconv" - "testing" - "time" - - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/log" - "github.com/ethereum/go-ethereum" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/core/types" - "github.com/ethereum/go-ethereum/crypto" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -var ( - contractAddr = common.HexToAddress("f00") - eventSignature = crypto.Keccak256Hash([]byte("foo")) -) - -const ( - syncBlockChunck = uint64(10) -) - -type testEvent common.Hash - -func TestGetEventsByBlockRange(t *testing.T) { - type testCase struct { - description string - inputLogs []types.Log - fromBlock, toBlock uint64 - expectedBlocks EVMBlocks - } - testCases := []testCase{} - ctx := context.Background() - d, clientMock := NewTestDownloader(t, time.Millisecond*100) - - // case 0: single block, no events - case0 := testCase{ - description: "case 0: single block, no events", - inputLogs: []types.Log{}, - fromBlock: 1, - toBlock: 3, - expectedBlocks: EVMBlocks{}, - } - testCases = append(testCases, case0) - - // case 1: single block, single event - logC1, updateC1 := generateEvent(3) - logsC1 := []types.Log{ - *logC1, - } - blocksC1 := EVMBlocks{ - { - EVMBlockHeader: EVMBlockHeader{ - Num: logC1.BlockNumber, - Hash: logC1.BlockHash, - ParentHash: common.HexToHash("foo"), - }, - Events: []interface{}{updateC1}, - }, - } - case1 := testCase{ - description: "case 1: single block, single event", - inputLogs: logsC1, - fromBlock: 3, - toBlock: 3, - expectedBlocks: blocksC1, - } - testCases = append(testCases, case1) - - // case 2: single block, multiple events - logC2_1, updateC2_1 := generateEvent(5) - logC2_2, updateC2_2 := generateEvent(5) - logC2_3, updateC2_3 := generateEvent(5) - logC2_4, updateC2_4 := generateEvent(5) - logsC2 := []types.Log{ - *logC2_1, - *logC2_2, - *logC2_3, - *logC2_4, - } - blocksC2 := []*EVMBlock{ - { - EVMBlockHeader: EVMBlockHeader{ - Num: logC2_1.BlockNumber, - Hash: logC2_1.BlockHash, - ParentHash: common.HexToHash("foo"), - }, - Events: []interface{}{ - updateC2_1, - updateC2_2, - updateC2_3, - updateC2_4, - }, - }, - } - case2 := testCase{ - description: "case 2: single block, multiple events", - inputLogs: logsC2, - fromBlock: 5, - toBlock: 5, - expectedBlocks: blocksC2, - } - testCases = append(testCases, case2) - - // case 3: multiple blocks, some events - logC3_1, updateC3_1 := generateEvent(7) - logC3_2, updateC3_2 := generateEvent(7) - logC3_3, updateC3_3 := generateEvent(8) - logC3_4, updateC3_4 := generateEvent(8) - logsC3 := []types.Log{ - *logC3_1, - *logC3_2, - *logC3_3, - *logC3_4, - } - blocksC3 := EVMBlocks{ - { - EVMBlockHeader: EVMBlockHeader{ - Num: logC3_1.BlockNumber, - Hash: logC3_1.BlockHash, - ParentHash: common.HexToHash("foo"), - }, - Events: []interface{}{ - updateC3_1, - updateC3_2, - }, - }, - { - EVMBlockHeader: EVMBlockHeader{ - Num: logC3_3.BlockNumber, - Hash: logC3_3.BlockHash, - ParentHash: common.HexToHash("foo"), - }, - Events: []interface{}{ - updateC3_3, - updateC3_4, - }, - }, - } - case3 := testCase{ - description: "case 3: multiple blocks, some events", - inputLogs: logsC3, - fromBlock: 7, - toBlock: 8, - expectedBlocks: blocksC3, - } - testCases = append(testCases, case3) - - for _, tc := range testCases { - query := ethereum.FilterQuery{ - FromBlock: new(big.Int).SetUint64(tc.fromBlock), - Addresses: []common.Address{contractAddr}, - ToBlock: new(big.Int).SetUint64(tc.toBlock), - } - clientMock. - On("FilterLogs", mock.Anything, query). - Return(tc.inputLogs, nil) - for _, b := range tc.expectedBlocks { - clientMock. - On("HeaderByNumber", mock.Anything, big.NewInt(int64(b.Num))). - Return(&types.Header{ - Number: big.NewInt(int64(b.Num)), - ParentHash: common.HexToHash("foo"), - }, nil) - } - - actualBlocks := d.GetEventsByBlockRange(ctx, tc.fromBlock, tc.toBlock) - require.Equal(t, tc.expectedBlocks, actualBlocks, tc.description) - } -} - -func generateEvent(blockNum uint32) (*types.Log, testEvent) { - h := common.HexToHash(strconv.Itoa(int(blockNum))) - header := types.Header{ - Number: big.NewInt(int64(blockNum)), - ParentHash: common.HexToHash("foo"), - } - blockHash := header.Hash() - log := &types.Log{ - Address: contractAddr, - BlockNumber: uint64(blockNum), - Topics: []common.Hash{ - eventSignature, - h, - }, - BlockHash: blockHash, - Data: nil, - } - return log, testEvent(h) -} - -func TestDownload(t *testing.T) { - /* - NOTE: due to the concurrent nature of this test (the function being tested runs through a goroutine) - if the mock doesn't match, the goroutine will get stuck and the test will timeout - */ - d := NewEVMDownloaderMock(t) - downloadCh := make(chan EVMBlock, 1) - ctx := context.Background() - ctx1, cancel := context.WithCancel(ctx) - expectedBlocks := EVMBlocks{} - dwnldr, _ := NewTestDownloader(t, time.Millisecond*100) - dwnldr.EVMDownloaderInterface = d - - d.On("WaitForNewBlocks", mock.Anything, uint64(0)). - Return(uint64(1)) - - lastFinalizedBlock := &types.Header{Number: big.NewInt(1)} - createEVMBlockFn := func(header *types.Header, isSafeBlock bool) *EVMBlock { - return &EVMBlock{ - IsFinalizedBlock: isSafeBlock, - EVMBlockHeader: EVMBlockHeader{ - Num: header.Number.Uint64(), - Hash: header.Hash(), - ParentHash: header.ParentHash, - Timestamp: header.Time, - }, - } - } - - // iteration 0: - // last block is 1, download that block (no events and wait) - b0 := createEVMBlockFn(lastFinalizedBlock, true) - expectedBlocks = append(expectedBlocks, b0) - d.On("GetLastFinalizedBlock", mock.Anything).Return(lastFinalizedBlock, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(0), uint64(1)). - Return(EVMBlocks{}, false).Once() - d.On("GetBlockHeader", mock.Anything, uint64(1)).Return(b0.EVMBlockHeader, false).Once() - - // iteration 1: we have a new block, so increase to block (no events) - lastFinalizedBlock = &types.Header{Number: big.NewInt(2)} - b2 := createEVMBlockFn(lastFinalizedBlock, true) - expectedBlocks = append(expectedBlocks, b2) - d.On("WaitForNewBlocks", mock.Anything, uint64(1)). - Return(uint64(2)) - d.On("GetLastFinalizedBlock", mock.Anything).Return(lastFinalizedBlock, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(2), uint64(2)). - Return(EVMBlocks{}, false).Once() - d.On("GetBlockHeader", mock.Anything, uint64(2)).Return(b2.EVMBlockHeader, false).Once() - - // iteration 2: wait for next block to be created (jump to block 8) - d.On("WaitForNewBlocks", mock.Anything, uint64(2)). - After(time.Millisecond * 100). - Return(uint64(8)).Once() - - // iteration 3: blocks 6 and 7 have events, last finalized block is 5 - lastFinalizedBlock = &types.Header{Number: big.NewInt(5)} - b6 := &EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 6, - Hash: common.HexToHash("06"), - }, - Events: []interface{}{"06"}, - } - b7 := &EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 7, - Hash: common.HexToHash("07"), - }, - Events: []interface{}{"07"}, - } - expectedBlocks = append(expectedBlocks, b6, b7) - d.On("GetLastFinalizedBlock", mock.Anything).Return(lastFinalizedBlock, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(3), uint64(8)). - Return(EVMBlocks{b6, b7}, false) - - // iteration 4: finalized block is now block 8, report the finalized block - lastFinalizedBlock = &types.Header{Number: big.NewInt(8)} - b8 := createEVMBlockFn(lastFinalizedBlock, true) - expectedBlocks = append(expectedBlocks, b8) - d.On("GetLastFinalizedBlock", mock.Anything).Return(lastFinalizedBlock, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(8), uint64(8)). - Return(EVMBlocks{}, false) - d.On("GetBlockHeader", mock.Anything, uint64(8)).Return(b8.EVMBlockHeader, false).Once() - - // iteration 5: from block 9 to 19, no events - lastFinalizedBlock = &types.Header{Number: big.NewInt(15)} - d.On("WaitForNewBlocks", mock.Anything, uint64(8)). - After(time.Millisecond * 100). - Return(uint64(19)).Once() - d.On("GetLastFinalizedBlock", mock.Anything).Return(lastFinalizedBlock, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(9), uint64(19)). - Return(EVMBlocks{}, false) - - // iteration 6: last finalized block is now 20, no events, report empty block - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(20)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(9), uint64(19)). - Return(EVMBlocks{}, false) - - d.On("WaitForNewBlocks", mock.Anything, uint64(19)). - After(time.Millisecond * 100). - Return(uint64(20)).Once() - b19 := createEVMBlockFn(&types.Header{Number: big.NewInt(19)}, true) - expectedBlocks = append(expectedBlocks, b19) - d.On("GetBlockHeader", mock.Anything, uint64(19)).Return(b19.EVMBlockHeader, false) // reporting empty finalized to block - - // iteration 8: last finalized block is 21, no events - b20 := createEVMBlockFn(&types.Header{Number: big.NewInt(20)}, true) - expectedBlocks = append(expectedBlocks, b20) - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(21)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(20), uint64(20)). - Return(EVMBlocks{}, false) - d.On("GetBlockHeader", mock.Anything, uint64(20)).Return(b20.EVMBlockHeader, false) // reporting empty finalized to block - - // iteration 9: last finalized block is 22, no events - d.On("WaitForNewBlocks", mock.Anything, uint64(20)). - After(time.Millisecond * 100). - Return(uint64(21)).Once() - b21 := createEVMBlockFn(&types.Header{Number: big.NewInt(21)}, true) - expectedBlocks = append(expectedBlocks, b21) - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(22)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(21), uint64(21)). - Return(EVMBlocks{}, false) - d.On("GetBlockHeader", mock.Anything, uint64(21)).Return(b21.EVMBlockHeader, false) // reporting empty finalized to block - - // iteration 10: last finalized block is 23, no events - d.On("WaitForNewBlocks", mock.Anything, uint64(21)). - After(time.Millisecond * 100). - Return(uint64(22)).Once() - b22 := createEVMBlockFn(&types.Header{Number: big.NewInt(22)}, true) - expectedBlocks = append(expectedBlocks, b22) - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(23)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(22), uint64(22)). - Return(EVMBlocks{}, false) - d.On("GetBlockHeader", mock.Anything, uint64(22)).Return(b22.EVMBlockHeader, false) // reporting empty finalized to block - - // iteration 11: last finalized block is still 23, no events - d.On("WaitForNewBlocks", mock.Anything, uint64(22)). - After(time.Millisecond * 100). - Return(uint64(23)).Once() - b23 := createEVMBlockFn(&types.Header{Number: big.NewInt(23)}, true) - expectedBlocks = append(expectedBlocks, b23) - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(23)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(23), uint64(23)). - Return(EVMBlocks{}, false) - d.On("GetBlockHeader", mock.Anything, uint64(23)).Return(b23.EVMBlockHeader, false) // reporting empty finalized to block - - // iteration 12: finalized block is 24, has events - d.On("WaitForNewBlocks", mock.Anything, uint64(23)). - After(time.Millisecond * 100). - Return(uint64(24)).Once() - b24 := &EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 24, - Hash: common.HexToHash("24"), - }, - Events: []interface{}{testEvent(common.HexToHash("24"))}, - } - expectedBlocks = append(expectedBlocks, b24) - d.On("GetLastFinalizedBlock", mock.Anything).Return(&types.Header{Number: big.NewInt(24)}, nil).Once() - d.On("GetEventsByBlockRange", mock.Anything, uint64(24), uint64(24)). - Return(EVMBlocks{b24}, false) - - // iteration 13: closing the downloader - d.On("WaitForNewBlocks", mock.Anything, uint64(24)).Return(uint64(25)).After(time.Millisecond * 100).Once() - - go dwnldr.Download(ctx1, 0, downloadCh) - for _, expectedBlock := range expectedBlocks { - actualBlock := <-downloadCh - log.Debugf("block %d received!", actualBlock.Num) - require.Equal(t, *expectedBlock, actualBlock) - } - log.Debug("canceling") - cancel() - _, ok := <-downloadCh - require.False(t, ok) -} - -func TestWaitForNewBlocks(t *testing.T) { - ctx := context.Background() - d, clientMock := NewTestDownloader(t, time.Millisecond*100) - - // at first attempt - currentBlock := uint64(5) - expectedBlock := uint64(6) - clientMock.On("HeaderByNumber", ctx, mock.Anything).Return(&types.Header{ - Number: big.NewInt(6), - }, nil).Once() - actualBlock := d.WaitForNewBlocks(ctx, currentBlock) - assert.Equal(t, expectedBlock, actualBlock) - - // 2 iterations - clientMock.On("HeaderByNumber", ctx, mock.Anything).Return(&types.Header{ - Number: big.NewInt(5), - }, nil).Once() - clientMock.On("HeaderByNumber", ctx, mock.Anything).Return(&types.Header{ - Number: big.NewInt(6), - }, nil).Once() - actualBlock = d.WaitForNewBlocks(ctx, currentBlock) - assert.Equal(t, expectedBlock, actualBlock) - - // after error from client - clientMock.On("HeaderByNumber", ctx, mock.Anything).Return(nil, errors.New("foo")).Once() - clientMock.On("HeaderByNumber", ctx, mock.Anything).Return(&types.Header{ - Number: big.NewInt(6), - }, nil).Once() - actualBlock = d.WaitForNewBlocks(ctx, currentBlock) - assert.Equal(t, expectedBlock, actualBlock) -} - -func TestGetBlockHeader(t *testing.T) { - ctx := context.Background() - d, clientMock := NewTestDownloader(t, time.Millisecond) - - blockNum := uint64(5) - blockNumBig := big.NewInt(5) - returnedBlock := &types.Header{ - Number: blockNumBig, - } - expectedBlock := EVMBlockHeader{ - Num: 5, - Hash: returnedBlock.Hash(), - } - - // at first attempt - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(returnedBlock, nil).Once() - actualBlock, isCanceled := d.GetBlockHeader(ctx, blockNum) - assert.Equal(t, expectedBlock, actualBlock) - assert.False(t, isCanceled) - - // after error from client - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(nil, errors.New("foo")).Once() - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(returnedBlock, nil).Once() - actualBlock, isCanceled = d.GetBlockHeader(ctx, blockNum) - assert.Equal(t, expectedBlock, actualBlock) - assert.False(t, isCanceled) - - // header not found default - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(nil, ethereum.NotFound).Once() - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(returnedBlock, nil).Once() - actualBlock, isCanceled = d.GetBlockHeader(ctx, 5) - assert.Equal(t, expectedBlock, actualBlock) - assert.False(t, isCanceled) - - // header not found default TO - d, clientMock = NewTestDownloader(t, 0) - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(nil, ethereum.NotFound).Once() - clientMock.On("HeaderByNumber", ctx, blockNumBig).Return(returnedBlock, nil).Once() - actualBlock, isCanceled = d.GetBlockHeader(ctx, 5) - assert.Equal(t, expectedBlock, actualBlock) - assert.False(t, isCanceled) -} - -func TestFilterQueryToString(t *testing.T) { - addr1 := common.HexToAddress("0xf000") - addr2 := common.HexToAddress("0xabcd") - query := ethereum.FilterQuery{ - FromBlock: new(big.Int).SetUint64(1000), - Addresses: []common.Address{addr1, addr2}, - ToBlock: new(big.Int).SetUint64(1100), - } - - assert.Equal(t, "FromBlock: 1000, ToBlock: 1100, Addresses: [0x000000000000000000000000000000000000f000 0x000000000000000000000000000000000000ABcD], Topics: []", filterQueryToString(query)) - - query = ethereum.FilterQuery{ - FromBlock: new(big.Int).SetUint64(1000), - Addresses: []common.Address{addr1, addr2}, - ToBlock: new(big.Int).SetUint64(1100), - Topics: [][]common.Hash{{common.HexToHash("0x1234"), common.HexToHash("0x5678")}}, - } - assert.Equal(t, "FromBlock: 1000, ToBlock: 1100, Addresses: [0x000000000000000000000000000000000000f000 0x000000000000000000000000000000000000ABcD], Topics: [[0x0000000000000000000000000000000000000000000000000000000000001234 0x0000000000000000000000000000000000000000000000000000000000005678]]", filterQueryToString(query)) -} - -func TestGetLogs(t *testing.T) { - mockEthClient := NewL2Mock(t) - sut := EVMDownloaderImplementation{ - ethClient: mockEthClient, - adressessToQuery: []common.Address{contractAddr}, - log: log.WithFields("test", "EVMDownloaderImplementation"), - rh: &RetryHandler{ - RetryAfterErrorPeriod: time.Millisecond, - MaxRetryAttemptsAfterError: 5, - }, - } - ctx := context.TODO() - mockEthClient.EXPECT().FilterLogs(ctx, mock.Anything).Return(nil, errors.New("foo")).Once() - mockEthClient.EXPECT().FilterLogs(ctx, mock.Anything).Return(nil, nil).Once() - logs := sut.GetLogs(ctx, 0, 1) - require.Equal(t, []types.Log{}, logs) -} - -func buildAppender() LogAppenderMap { - appender := make(LogAppenderMap) - appender[eventSignature] = func(b *EVMBlock, l types.Log) error { - b.Events = append(b.Events, testEvent(l.Topics[1])) - return nil - } - return appender -} - -func NewTestDownloader(t *testing.T, retryPeriod time.Duration) (*EVMDownloader, *L2Mock) { - t.Helper() - - rh := &RetryHandler{ - MaxRetryAttemptsAfterError: 5, - RetryAfterErrorPeriod: retryPeriod, - } - clientMock := NewL2Mock(t) - d, err := NewEVMDownloader("test", - clientMock, syncBlockChunck, etherman.LatestBlock, time.Millisecond, - buildAppender(), []common.Address{contractAddr}, rh, - etherman.FinalizedBlock, - ) - require.NoError(t, err) - return d, clientMock -} diff --git a/sync/evmdriver.go b/sync/evmdriver.go deleted file mode 100644 index 4ac4c9cbf..000000000 --- a/sync/evmdriver.go +++ /dev/null @@ -1,191 +0,0 @@ -package sync - -import ( - "context" - "errors" - - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/reorgdetector" - "github.com/ethereum/go-ethereum/common" -) - -type downloader interface { - Download(ctx context.Context, fromBlock uint64, downloadedCh chan EVMBlock) -} - -type EVMDriver struct { - reorgDetector ReorgDetector - reorgSub *reorgdetector.Subscription - processor processorInterface - downloader downloader - reorgDetectorID string - downloadBufferSize int - rh *RetryHandler - log *log.Logger -} - -type processorInterface interface { - GetLastProcessedBlock(ctx context.Context) (uint64, error) - ProcessBlock(ctx context.Context, block Block) error - Reorg(ctx context.Context, firstReorgedBlock uint64) error -} - -type ReorgDetector interface { - Subscribe(id string) (*reorgdetector.Subscription, error) - AddBlockToTrack(ctx context.Context, id string, blockNum uint64, blockHash common.Hash) error -} - -func NewEVMDriver( - reorgDetector ReorgDetector, - processor processorInterface, - downloader downloader, - reorgDetectorID string, - downloadBufferSize int, - rh *RetryHandler, -) (*EVMDriver, error) { - logger := log.WithFields("syncer", reorgDetectorID) - reorgSub, err := reorgDetector.Subscribe(reorgDetectorID) - if err != nil { - return nil, err - } - return &EVMDriver{ - reorgDetector: reorgDetector, - reorgSub: reorgSub, - processor: processor, - downloader: downloader, - reorgDetectorID: reorgDetectorID, - downloadBufferSize: downloadBufferSize, - rh: rh, - log: logger, - }, nil -} - -func (d *EVMDriver) Sync(ctx context.Context) { -reset: - var ( - lastProcessedBlock uint64 - attempts int - err error - ) - - for { - lastProcessedBlock, err = d.processor.GetLastProcessedBlock(ctx) - if err != nil { - attempts++ - d.log.Error("error getting last processed block: ", err) - d.rh.Handle("Sync", attempts) - continue - } - break - } - cancellableCtx, cancel := context.WithCancel(ctx) - defer cancel() - - d.log.Infof("Starting sync... lastProcessedBlock %d", lastProcessedBlock) - // start downloading - downloadCh := make(chan EVMBlock, d.downloadBufferSize) - go d.downloader.Download(cancellableCtx, lastProcessedBlock+1, downloadCh) - - for { - select { - case <-ctx.Done(): - d.log.Info("sync stopped due to context done") - cancel() - return - case b, ok := <-downloadCh: - if ok { - // when channel is closing, it is sending an empty block with num = 0, and empty hash - // because it is not passing object by reference, but by value, so do not handle that since it is closing - d.log.Infof("handleNewBlock, blockNum: %d, blockHash: %s", b.Num, b.Hash) - d.handleNewBlock(ctx, cancel, b) - } - case firstReorgedBlock := <-d.reorgSub.ReorgedBlock: - d.log.Debug("handleReorg from block: ", firstReorgedBlock) - d.handleReorg(ctx, cancel, firstReorgedBlock) - goto reset - } - } -} - -func (d *EVMDriver) handleNewBlock(ctx context.Context, cancel context.CancelFunc, b EVMBlock) { - attempts := 0 - succeed := false - for { - select { - case <-ctx.Done(): - // If the context is canceled, exit the function - d.log.Warnf("context canceled while adding block %d to tracker", b.Num) - return - default: - if !b.IsFinalizedBlock { - err := d.reorgDetector.AddBlockToTrack(ctx, d.reorgDetectorID, b.Num, b.Hash) - if err != nil { - attempts++ - d.log.Errorf("error adding block %d to tracker: %v", b.Num, err) - d.rh.Handle("handleNewBlock", attempts) - } else { - succeed = true - } - } else { - succeed = true - } - } - if succeed { - break - } - } - attempts = 0 - succeed = false - for { - select { - case <-ctx.Done(): - // If the context is canceled, exit the function - d.log.Warnf("context canceled while processing block %d", b.Num) - return - default: - blockToProcess := Block{ - Num: b.Num, - Events: b.Events, - Hash: b.Hash, - } - err := d.processor.ProcessBlock(ctx, blockToProcess) - if err != nil { - if errors.Is(err, ErrInconsistentState) { - d.log.Warn("state got inconsistent after processing this block. Stopping downloader until there is a reorg") - cancel() - return - } - attempts++ - d.log.Errorf("error processing events for block %d, err: %v", b.Num, err) - d.rh.Handle("handleNewBlock", attempts) - } else { - succeed = true - } - } - if succeed { - break - } - } -} - -func (d *EVMDriver) handleReorg(ctx context.Context, cancel context.CancelFunc, firstReorgedBlock uint64) { - // stop downloader - cancel() - - // handle reorg - attempts := 0 - for { - err := d.processor.Reorg(ctx, firstReorgedBlock) - if err != nil { - attempts++ - d.log.Errorf( - "error processing reorg, last valid Block %d, err: %v", - firstReorgedBlock, err, - ) - d.rh.Handle("handleReorg", attempts) - continue - } - break - } - d.reorgSub.ReorgProcessed <- true -} diff --git a/sync/evmdriver_test.go b/sync/evmdriver_test.go deleted file mode 100644 index 9edbf0b2b..000000000 --- a/sync/evmdriver_test.go +++ /dev/null @@ -1,235 +0,0 @@ -package sync - -import ( - "context" - "errors" - "sync" - "testing" - "time" - - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/reorgdetector" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/mock" - "github.com/stretchr/testify/require" -) - -var ( - reorgDetectorID = "foo" -) - -func TestSync(t *testing.T) { - rh := &RetryHandler{ - MaxRetryAttemptsAfterError: 5, - RetryAfterErrorPeriod: time.Millisecond * 100, - } - rdm := NewReorgDetectorMock(t) - pm := NewProcessorMock(t) - dm := NewEVMDownloaderMock(t) - firstReorgedBlock := make(chan uint64) - reorgProcessed := make(chan bool) - rdm.On("Subscribe", reorgDetectorID).Return(&reorgdetector.Subscription{ - ReorgedBlock: firstReorgedBlock, - ReorgProcessed: reorgProcessed, - }, nil) - driver, err := NewEVMDriver(rdm, pm, dm, reorgDetectorID, 10, rh) - require.NoError(t, err) - ctx := context.Background() - expectedBlock1 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 3, - Hash: common.HexToHash("03"), - }, - } - expectedBlock2 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 9, - Hash: common.HexToHash("09"), - }, - } - type reorgSemaphore struct { - mu sync.Mutex - green bool - } - reorg1Completed := reorgSemaphore{} - dm.On("Download", mock.Anything, mock.Anything, mock.Anything).Run(func(args mock.Arguments) { - ctx, ok := args.Get(0).(context.Context) - if !ok { - log.Error("failed to assert type for context") - return - } - - downloadedCh, ok := args.Get(2).(chan EVMBlock) - if !ok { - log.Error("failed to assert type for downloadedCh") - return - } - - log.Info("entering mock loop") - for { - select { - case <-ctx.Done(): - log.Info("closing channel") - close(downloadedCh) - return - default: - } - reorg1Completed.mu.Lock() - green := reorg1Completed.green - reorg1Completed.mu.Unlock() - if green { - downloadedCh <- expectedBlock2 - } else { - downloadedCh <- expectedBlock1 - } - time.Sleep(100 * time.Millisecond) - } - }) - - // Mocking this actions, the driver should "store" all the blocks from the downloader - pm.On("GetLastProcessedBlock", ctx). - Return(uint64(3), nil) - rdm.On("AddBlockToTrack", ctx, reorgDetectorID, expectedBlock1.Num, expectedBlock1.Hash). - Return(nil) - pm.On("ProcessBlock", ctx, Block{Num: expectedBlock1.Num, Events: expectedBlock1.Events, Hash: expectedBlock1.Hash}). - Return(nil) - rdm.On("AddBlockToTrack", ctx, reorgDetectorID, expectedBlock2.Num, expectedBlock2.Hash). - Return(nil) - pm.On("ProcessBlock", ctx, Block{Num: expectedBlock2.Num, Events: expectedBlock2.Events, Hash: expectedBlock2.Hash}). - Return(nil) - go driver.Sync(ctx) - time.Sleep(time.Millisecond * 200) // time to download expectedBlock1 - - // Trigger reorg 1 - reorgedBlock1 := uint64(5) - pm.On("Reorg", ctx, reorgedBlock1).Return(nil) - firstReorgedBlock <- reorgedBlock1 - ok := <-reorgProcessed - require.True(t, ok) - reorg1Completed.mu.Lock() - reorg1Completed.green = true - reorg1Completed.mu.Unlock() - time.Sleep(time.Millisecond * 200) // time to download expectedBlock2 - - // Trigger reorg 2: syncer restarts the porcess - reorgedBlock2 := uint64(7) - pm.On("Reorg", ctx, reorgedBlock2).Return(nil) - firstReorgedBlock <- reorgedBlock2 - ok = <-reorgProcessed - require.True(t, ok) -} - -func TestHandleNewBlock(t *testing.T) { - rh := &RetryHandler{ - MaxRetryAttemptsAfterError: 5, - RetryAfterErrorPeriod: time.Millisecond * 100, - } - rdm := NewReorgDetectorMock(t) - pm := NewProcessorMock(t) - dm := NewEVMDownloaderMock(t) - rdm.On("Subscribe", reorgDetectorID).Return(&reorgdetector.Subscription{}, nil) - driver, err := NewEVMDriver(rdm, pm, dm, reorgDetectorID, 10, rh) - require.NoError(t, err) - ctx := context.Background() - - // happy path - b1 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 1, - Hash: common.HexToHash("f00"), - }, - } - rdm. - On("AddBlockToTrack", ctx, reorgDetectorID, b1.Num, b1.Hash). - Return(nil) - pm.On("ProcessBlock", ctx, Block{Num: b1.Num, Events: b1.Events, Hash: b1.Hash}). - Return(nil) - driver.handleNewBlock(ctx, nil, b1) - - // reorg deteector fails once - b2 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 2, - Hash: common.HexToHash("f00"), - }, - } - rdm. - On("AddBlockToTrack", ctx, reorgDetectorID, b2.Num, b2.Hash). - Return(errors.New("foo")).Once() - rdm. - On("AddBlockToTrack", ctx, reorgDetectorID, b2.Num, b2.Hash). - Return(nil).Once() - pm.On("ProcessBlock", ctx, Block{Num: b2.Num, Events: b2.Events, Hash: b2.Hash}). - Return(nil) - driver.handleNewBlock(ctx, nil, b2) - - // processor fails once - b3 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 3, - Hash: common.HexToHash("f00"), - }, - } - rdm. - On("AddBlockToTrack", ctx, reorgDetectorID, b3.Num, b3.Hash). - Return(nil) - pm.On("ProcessBlock", ctx, Block{Num: b3.Num, Events: b3.Events, Hash: b3.Hash}). - Return(errors.New("foo")).Once() - pm.On("ProcessBlock", ctx, Block{Num: b3.Num, Events: b3.Events, Hash: b3.Hash}). - Return(nil).Once() - driver.handleNewBlock(ctx, nil, b3) - - // inconsistent state error - b4 := EVMBlock{ - EVMBlockHeader: EVMBlockHeader{ - Num: 4, - Hash: common.HexToHash("f00"), - }, - } - rdm. - On("AddBlockToTrack", ctx, reorgDetectorID, b4.Num, b4.Hash). - Return(nil) - pm.On("ProcessBlock", ctx, Block{Num: b4.Num, Events: b4.Events, Hash: b4.Hash}). - Return(ErrInconsistentState) - cancelIsCalled := false - cancel := func() { - cancelIsCalled = true - } - driver.handleNewBlock(ctx, cancel, b4) - require.True(t, cancelIsCalled) -} - -func TestHandleReorg(t *testing.T) { - rh := &RetryHandler{ - MaxRetryAttemptsAfterError: 5, - RetryAfterErrorPeriod: time.Millisecond * 100, - } - rdm := NewReorgDetectorMock(t) - pm := NewProcessorMock(t) - dm := NewEVMDownloaderMock(t) - reorgProcessed := make(chan bool) - rdm.On("Subscribe", reorgDetectorID).Return(&reorgdetector.Subscription{ - ReorgProcessed: reorgProcessed, - }, nil) - driver, err := NewEVMDriver(rdm, pm, dm, reorgDetectorID, 10, rh) - require.NoError(t, err) - ctx := context.Background() - - // happy path - _, cancel := context.WithCancel(ctx) - firstReorgedBlock := uint64(5) - pm.On("Reorg", ctx, firstReorgedBlock).Return(nil) - go driver.handleReorg(ctx, cancel, firstReorgedBlock) - done := <-reorgProcessed - require.True(t, done) - - // processor fails 2 times - _, cancel = context.WithCancel(ctx) - firstReorgedBlock = uint64(7) - pm.On("Reorg", ctx, firstReorgedBlock).Return(errors.New("foo")).Once() - pm.On("Reorg", ctx, firstReorgedBlock).Return(errors.New("foo")).Once() - pm.On("Reorg", ctx, firstReorgedBlock).Return(nil).Once() - go driver.handleReorg(ctx, cancel, firstReorgedBlock) - done = <-reorgProcessed - require.True(t, done) -} diff --git a/sync/evmtypes.go b/sync/evmtypes.go deleted file mode 100644 index 739154f90..000000000 --- a/sync/evmtypes.go +++ /dev/null @@ -1,22 +0,0 @@ -package sync - -import "github.com/ethereum/go-ethereum/common" - -type EVMBlocks []*EVMBlock - -func (e EVMBlocks) Len() int { - return len(e) -} - -type EVMBlock struct { - EVMBlockHeader - IsFinalizedBlock bool - Events []interface{} -} - -type EVMBlockHeader struct { - Num uint64 - Hash common.Hash - ParentHash common.Hash - Timestamp uint64 -} diff --git a/sync/mock_eth_clienter.go b/sync/mock_eth_clienter.go deleted file mode 100644 index 955af0dbb..000000000 --- a/sync/mock_eth_clienter.go +++ /dev/null @@ -1,1086 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package sync - -import ( - context "context" - big "math/big" - - common "github.com/ethereum/go-ethereum/common" - - ethereum "github.com/ethereum/go-ethereum" - - mock "github.com/stretchr/testify/mock" - - types "github.com/ethereum/go-ethereum/core/types" -) - -// L2Mock is an autogenerated mock type for the EthClienter type -type L2Mock struct { - mock.Mock -} - -type L2Mock_Expecter struct { - mock *mock.Mock -} - -func (_m *L2Mock) EXPECT() *L2Mock_Expecter { - return &L2Mock_Expecter{mock: &_m.Mock} -} - -// BlockByHash provides a mock function with given fields: ctx, hash -func (_m *L2Mock) BlockByHash(ctx context.Context, hash common.Hash) (*types.Block, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for BlockByHash") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Block, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Block); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_BlockByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByHash' -type L2Mock_BlockByHash_Call struct { - *mock.Call -} - -// BlockByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *L2Mock_Expecter) BlockByHash(ctx interface{}, hash interface{}) *L2Mock_BlockByHash_Call { - return &L2Mock_BlockByHash_Call{Call: _e.mock.On("BlockByHash", ctx, hash)} -} - -func (_c *L2Mock_BlockByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *L2Mock_BlockByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *L2Mock_BlockByHash_Call) Return(_a0 *types.Block, _a1 error) *L2Mock_BlockByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_BlockByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Block, error)) *L2Mock_BlockByHash_Call { - _c.Call.Return(run) - return _c -} - -// BlockByNumber provides a mock function with given fields: ctx, number -func (_m *L2Mock) BlockByNumber(ctx context.Context, number *big.Int) (*types.Block, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for BlockByNumber") - } - - var r0 *types.Block - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Block, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Block); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Block) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_BlockByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockByNumber' -type L2Mock_BlockByNumber_Call struct { - *mock.Call -} - -// BlockByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *L2Mock_Expecter) BlockByNumber(ctx interface{}, number interface{}) *L2Mock_BlockByNumber_Call { - return &L2Mock_BlockByNumber_Call{Call: _e.mock.On("BlockByNumber", ctx, number)} -} - -func (_c *L2Mock_BlockByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *L2Mock_BlockByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *L2Mock_BlockByNumber_Call) Return(_a0 *types.Block, _a1 error) *L2Mock_BlockByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_BlockByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Block, error)) *L2Mock_BlockByNumber_Call { - _c.Call.Return(run) - return _c -} - -// BlockNumber provides a mock function with given fields: ctx -func (_m *L2Mock) BlockNumber(ctx context.Context) (uint64, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for BlockNumber") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_BlockNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'BlockNumber' -type L2Mock_BlockNumber_Call struct { - *mock.Call -} - -// BlockNumber is a helper method to define mock.On call -// - ctx context.Context -func (_e *L2Mock_Expecter) BlockNumber(ctx interface{}) *L2Mock_BlockNumber_Call { - return &L2Mock_BlockNumber_Call{Call: _e.mock.On("BlockNumber", ctx)} -} - -func (_c *L2Mock_BlockNumber_Call) Run(run func(ctx context.Context)) *L2Mock_BlockNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *L2Mock_BlockNumber_Call) Return(_a0 uint64, _a1 error) *L2Mock_BlockNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_BlockNumber_Call) RunAndReturn(run func(context.Context) (uint64, error)) *L2Mock_BlockNumber_Call { - _c.Call.Return(run) - return _c -} - -// CallContract provides a mock function with given fields: ctx, call, blockNumber -func (_m *L2Mock) CallContract(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, call, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CallContract") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)); ok { - return rf(ctx, call, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg, *big.Int) []byte); ok { - r0 = rf(ctx, call, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg, *big.Int) error); ok { - r1 = rf(ctx, call, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_CallContract_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CallContract' -type L2Mock_CallContract_Call struct { - *mock.Call -} - -// CallContract is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -// - blockNumber *big.Int -func (_e *L2Mock_Expecter) CallContract(ctx interface{}, call interface{}, blockNumber interface{}) *L2Mock_CallContract_Call { - return &L2Mock_CallContract_Call{Call: _e.mock.On("CallContract", ctx, call, blockNumber)} -} - -func (_c *L2Mock_CallContract_Call) Run(run func(ctx context.Context, call ethereum.CallMsg, blockNumber *big.Int)) *L2Mock_CallContract_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg), args[2].(*big.Int)) - }) - return _c -} - -func (_c *L2Mock_CallContract_Call) Return(_a0 []byte, _a1 error) *L2Mock_CallContract_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_CallContract_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg, *big.Int) ([]byte, error)) *L2Mock_CallContract_Call { - _c.Call.Return(run) - return _c -} - -// CodeAt provides a mock function with given fields: ctx, contract, blockNumber -func (_m *L2Mock) CodeAt(ctx context.Context, contract common.Address, blockNumber *big.Int) ([]byte, error) { - ret := _m.Called(ctx, contract, blockNumber) - - if len(ret) == 0 { - panic("no return value specified for CodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) ([]byte, error)); ok { - return rf(ctx, contract, blockNumber) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address, *big.Int) []byte); ok { - r0 = rf(ctx, contract, blockNumber) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address, *big.Int) error); ok { - r1 = rf(ctx, contract, blockNumber) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_CodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CodeAt' -type L2Mock_CodeAt_Call struct { - *mock.Call -} - -// CodeAt is a helper method to define mock.On call -// - ctx context.Context -// - contract common.Address -// - blockNumber *big.Int -func (_e *L2Mock_Expecter) CodeAt(ctx interface{}, contract interface{}, blockNumber interface{}) *L2Mock_CodeAt_Call { - return &L2Mock_CodeAt_Call{Call: _e.mock.On("CodeAt", ctx, contract, blockNumber)} -} - -func (_c *L2Mock_CodeAt_Call) Run(run func(ctx context.Context, contract common.Address, blockNumber *big.Int)) *L2Mock_CodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address), args[2].(*big.Int)) - }) - return _c -} - -func (_c *L2Mock_CodeAt_Call) Return(_a0 []byte, _a1 error) *L2Mock_CodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_CodeAt_Call) RunAndReturn(run func(context.Context, common.Address, *big.Int) ([]byte, error)) *L2Mock_CodeAt_Call { - _c.Call.Return(run) - return _c -} - -// EstimateGas provides a mock function with given fields: ctx, call -func (_m *L2Mock) EstimateGas(ctx context.Context, call ethereum.CallMsg) (uint64, error) { - ret := _m.Called(ctx, call) - - if len(ret) == 0 { - panic("no return value specified for EstimateGas") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) (uint64, error)); ok { - return rf(ctx, call) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.CallMsg) uint64); ok { - r0 = rf(ctx, call) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.CallMsg) error); ok { - r1 = rf(ctx, call) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_EstimateGas_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'EstimateGas' -type L2Mock_EstimateGas_Call struct { - *mock.Call -} - -// EstimateGas is a helper method to define mock.On call -// - ctx context.Context -// - call ethereum.CallMsg -func (_e *L2Mock_Expecter) EstimateGas(ctx interface{}, call interface{}) *L2Mock_EstimateGas_Call { - return &L2Mock_EstimateGas_Call{Call: _e.mock.On("EstimateGas", ctx, call)} -} - -func (_c *L2Mock_EstimateGas_Call) Run(run func(ctx context.Context, call ethereum.CallMsg)) *L2Mock_EstimateGas_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.CallMsg)) - }) - return _c -} - -func (_c *L2Mock_EstimateGas_Call) Return(_a0 uint64, _a1 error) *L2Mock_EstimateGas_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_EstimateGas_Call) RunAndReturn(run func(context.Context, ethereum.CallMsg) (uint64, error)) *L2Mock_EstimateGas_Call { - _c.Call.Return(run) - return _c -} - -// FilterLogs provides a mock function with given fields: ctx, q -func (_m *L2Mock) FilterLogs(ctx context.Context, q ethereum.FilterQuery) ([]types.Log, error) { - ret := _m.Called(ctx, q) - - if len(ret) == 0 { - panic("no return value specified for FilterLogs") - } - - var r0 []types.Log - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) ([]types.Log, error)); ok { - return rf(ctx, q) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery) []types.Log); ok { - r0 = rf(ctx, q) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Log) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery) error); ok { - r1 = rf(ctx, q) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_FilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'FilterLogs' -type L2Mock_FilterLogs_Call struct { - *mock.Call -} - -// FilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -func (_e *L2Mock_Expecter) FilterLogs(ctx interface{}, q interface{}) *L2Mock_FilterLogs_Call { - return &L2Mock_FilterLogs_Call{Call: _e.mock.On("FilterLogs", ctx, q)} -} - -func (_c *L2Mock_FilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery)) *L2Mock_FilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery)) - }) - return _c -} - -func (_c *L2Mock_FilterLogs_Call) Return(_a0 []types.Log, _a1 error) *L2Mock_FilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_FilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery) ([]types.Log, error)) *L2Mock_FilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByHash provides a mock function with given fields: ctx, hash -func (_m *L2Mock) HeaderByHash(ctx context.Context, hash common.Hash) (*types.Header, error) { - ret := _m.Called(ctx, hash) - - if len(ret) == 0 { - panic("no return value specified for HeaderByHash") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (*types.Header, error)); ok { - return rf(ctx, hash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) *types.Header); ok { - r0 = rf(ctx, hash) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, hash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_HeaderByHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByHash' -type L2Mock_HeaderByHash_Call struct { - *mock.Call -} - -// HeaderByHash is a helper method to define mock.On call -// - ctx context.Context -// - hash common.Hash -func (_e *L2Mock_Expecter) HeaderByHash(ctx interface{}, hash interface{}) *L2Mock_HeaderByHash_Call { - return &L2Mock_HeaderByHash_Call{Call: _e.mock.On("HeaderByHash", ctx, hash)} -} - -func (_c *L2Mock_HeaderByHash_Call) Run(run func(ctx context.Context, hash common.Hash)) *L2Mock_HeaderByHash_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *L2Mock_HeaderByHash_Call) Return(_a0 *types.Header, _a1 error) *L2Mock_HeaderByHash_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_HeaderByHash_Call) RunAndReturn(run func(context.Context, common.Hash) (*types.Header, error)) *L2Mock_HeaderByHash_Call { - _c.Call.Return(run) - return _c -} - -// HeaderByNumber provides a mock function with given fields: ctx, number -func (_m *L2Mock) HeaderByNumber(ctx context.Context, number *big.Int) (*types.Header, error) { - ret := _m.Called(ctx, number) - - if len(ret) == 0 { - panic("no return value specified for HeaderByNumber") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) (*types.Header, error)); ok { - return rf(ctx, number) - } - if rf, ok := ret.Get(0).(func(context.Context, *big.Int) *types.Header); ok { - r0 = rf(ctx, number) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, *big.Int) error); ok { - r1 = rf(ctx, number) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_HeaderByNumber_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'HeaderByNumber' -type L2Mock_HeaderByNumber_Call struct { - *mock.Call -} - -// HeaderByNumber is a helper method to define mock.On call -// - ctx context.Context -// - number *big.Int -func (_e *L2Mock_Expecter) HeaderByNumber(ctx interface{}, number interface{}) *L2Mock_HeaderByNumber_Call { - return &L2Mock_HeaderByNumber_Call{Call: _e.mock.On("HeaderByNumber", ctx, number)} -} - -func (_c *L2Mock_HeaderByNumber_Call) Run(run func(ctx context.Context, number *big.Int)) *L2Mock_HeaderByNumber_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*big.Int)) - }) - return _c -} - -func (_c *L2Mock_HeaderByNumber_Call) Return(_a0 *types.Header, _a1 error) *L2Mock_HeaderByNumber_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_HeaderByNumber_Call) RunAndReturn(run func(context.Context, *big.Int) (*types.Header, error)) *L2Mock_HeaderByNumber_Call { - _c.Call.Return(run) - return _c -} - -// PendingCodeAt provides a mock function with given fields: ctx, account -func (_m *L2Mock) PendingCodeAt(ctx context.Context, account common.Address) ([]byte, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingCodeAt") - } - - var r0 []byte - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) ([]byte, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) []byte); ok { - r0 = rf(ctx, account) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]byte) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_PendingCodeAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingCodeAt' -type L2Mock_PendingCodeAt_Call struct { - *mock.Call -} - -// PendingCodeAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *L2Mock_Expecter) PendingCodeAt(ctx interface{}, account interface{}) *L2Mock_PendingCodeAt_Call { - return &L2Mock_PendingCodeAt_Call{Call: _e.mock.On("PendingCodeAt", ctx, account)} -} - -func (_c *L2Mock_PendingCodeAt_Call) Run(run func(ctx context.Context, account common.Address)) *L2Mock_PendingCodeAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *L2Mock_PendingCodeAt_Call) Return(_a0 []byte, _a1 error) *L2Mock_PendingCodeAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_PendingCodeAt_Call) RunAndReturn(run func(context.Context, common.Address) ([]byte, error)) *L2Mock_PendingCodeAt_Call { - _c.Call.Return(run) - return _c -} - -// PendingNonceAt provides a mock function with given fields: ctx, account -func (_m *L2Mock) PendingNonceAt(ctx context.Context, account common.Address) (uint64, error) { - ret := _m.Called(ctx, account) - - if len(ret) == 0 { - panic("no return value specified for PendingNonceAt") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Address) (uint64, error)); ok { - return rf(ctx, account) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Address) uint64); ok { - r0 = rf(ctx, account) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Address) error); ok { - r1 = rf(ctx, account) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_PendingNonceAt_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'PendingNonceAt' -type L2Mock_PendingNonceAt_Call struct { - *mock.Call -} - -// PendingNonceAt is a helper method to define mock.On call -// - ctx context.Context -// - account common.Address -func (_e *L2Mock_Expecter) PendingNonceAt(ctx interface{}, account interface{}) *L2Mock_PendingNonceAt_Call { - return &L2Mock_PendingNonceAt_Call{Call: _e.mock.On("PendingNonceAt", ctx, account)} -} - -func (_c *L2Mock_PendingNonceAt_Call) Run(run func(ctx context.Context, account common.Address)) *L2Mock_PendingNonceAt_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Address)) - }) - return _c -} - -func (_c *L2Mock_PendingNonceAt_Call) Return(_a0 uint64, _a1 error) *L2Mock_PendingNonceAt_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_PendingNonceAt_Call) RunAndReturn(run func(context.Context, common.Address) (uint64, error)) *L2Mock_PendingNonceAt_Call { - _c.Call.Return(run) - return _c -} - -// SendTransaction provides a mock function with given fields: ctx, tx -func (_m *L2Mock) SendTransaction(ctx context.Context, tx *types.Transaction) error { - ret := _m.Called(ctx, tx) - - if len(ret) == 0 { - panic("no return value specified for SendTransaction") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, *types.Transaction) error); ok { - r0 = rf(ctx, tx) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// L2Mock_SendTransaction_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SendTransaction' -type L2Mock_SendTransaction_Call struct { - *mock.Call -} - -// SendTransaction is a helper method to define mock.On call -// - ctx context.Context -// - tx *types.Transaction -func (_e *L2Mock_Expecter) SendTransaction(ctx interface{}, tx interface{}) *L2Mock_SendTransaction_Call { - return &L2Mock_SendTransaction_Call{Call: _e.mock.On("SendTransaction", ctx, tx)} -} - -func (_c *L2Mock_SendTransaction_Call) Run(run func(ctx context.Context, tx *types.Transaction)) *L2Mock_SendTransaction_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(*types.Transaction)) - }) - return _c -} - -func (_c *L2Mock_SendTransaction_Call) Return(_a0 error) *L2Mock_SendTransaction_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *L2Mock_SendTransaction_Call) RunAndReturn(run func(context.Context, *types.Transaction) error) *L2Mock_SendTransaction_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeFilterLogs provides a mock function with given fields: ctx, q, ch -func (_m *L2Mock) SubscribeFilterLogs(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log) (ethereum.Subscription, error) { - ret := _m.Called(ctx, q, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeFilterLogs") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)); ok { - return rf(ctx, q, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) ethereum.Subscription); ok { - r0 = rf(ctx, q, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, ethereum.FilterQuery, chan<- types.Log) error); ok { - r1 = rf(ctx, q, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_SubscribeFilterLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeFilterLogs' -type L2Mock_SubscribeFilterLogs_Call struct { - *mock.Call -} - -// SubscribeFilterLogs is a helper method to define mock.On call -// - ctx context.Context -// - q ethereum.FilterQuery -// - ch chan<- types.Log -func (_e *L2Mock_Expecter) SubscribeFilterLogs(ctx interface{}, q interface{}, ch interface{}) *L2Mock_SubscribeFilterLogs_Call { - return &L2Mock_SubscribeFilterLogs_Call{Call: _e.mock.On("SubscribeFilterLogs", ctx, q, ch)} -} - -func (_c *L2Mock_SubscribeFilterLogs_Call) Run(run func(ctx context.Context, q ethereum.FilterQuery, ch chan<- types.Log)) *L2Mock_SubscribeFilterLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(ethereum.FilterQuery), args[2].(chan<- types.Log)) - }) - return _c -} - -func (_c *L2Mock_SubscribeFilterLogs_Call) Return(_a0 ethereum.Subscription, _a1 error) *L2Mock_SubscribeFilterLogs_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_SubscribeFilterLogs_Call) RunAndReturn(run func(context.Context, ethereum.FilterQuery, chan<- types.Log) (ethereum.Subscription, error)) *L2Mock_SubscribeFilterLogs_Call { - _c.Call.Return(run) - return _c -} - -// SubscribeNewHead provides a mock function with given fields: ctx, ch -func (_m *L2Mock) SubscribeNewHead(ctx context.Context, ch chan<- *types.Header) (ethereum.Subscription, error) { - ret := _m.Called(ctx, ch) - - if len(ret) == 0 { - panic("no return value specified for SubscribeNewHead") - } - - var r0 ethereum.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)); ok { - return rf(ctx, ch) - } - if rf, ok := ret.Get(0).(func(context.Context, chan<- *types.Header) ethereum.Subscription); ok { - r0 = rf(ctx, ch) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(ethereum.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, chan<- *types.Header) error); ok { - r1 = rf(ctx, ch) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_SubscribeNewHead_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SubscribeNewHead' -type L2Mock_SubscribeNewHead_Call struct { - *mock.Call -} - -// SubscribeNewHead is a helper method to define mock.On call -// - ctx context.Context -// - ch chan<- *types.Header -func (_e *L2Mock_Expecter) SubscribeNewHead(ctx interface{}, ch interface{}) *L2Mock_SubscribeNewHead_Call { - return &L2Mock_SubscribeNewHead_Call{Call: _e.mock.On("SubscribeNewHead", ctx, ch)} -} - -func (_c *L2Mock_SubscribeNewHead_Call) Run(run func(ctx context.Context, ch chan<- *types.Header)) *L2Mock_SubscribeNewHead_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(chan<- *types.Header)) - }) - return _c -} - -func (_c *L2Mock_SubscribeNewHead_Call) Return(_a0 ethereum.Subscription, _a1 error) *L2Mock_SubscribeNewHead_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_SubscribeNewHead_Call) RunAndReturn(run func(context.Context, chan<- *types.Header) (ethereum.Subscription, error)) *L2Mock_SubscribeNewHead_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasPrice provides a mock function with given fields: ctx -func (_m *L2Mock) SuggestGasPrice(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasPrice") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_SuggestGasPrice_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasPrice' -type L2Mock_SuggestGasPrice_Call struct { - *mock.Call -} - -// SuggestGasPrice is a helper method to define mock.On call -// - ctx context.Context -func (_e *L2Mock_Expecter) SuggestGasPrice(ctx interface{}) *L2Mock_SuggestGasPrice_Call { - return &L2Mock_SuggestGasPrice_Call{Call: _e.mock.On("SuggestGasPrice", ctx)} -} - -func (_c *L2Mock_SuggestGasPrice_Call) Run(run func(ctx context.Context)) *L2Mock_SuggestGasPrice_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *L2Mock_SuggestGasPrice_Call) Return(_a0 *big.Int, _a1 error) *L2Mock_SuggestGasPrice_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_SuggestGasPrice_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *L2Mock_SuggestGasPrice_Call { - _c.Call.Return(run) - return _c -} - -// SuggestGasTipCap provides a mock function with given fields: ctx -func (_m *L2Mock) SuggestGasTipCap(ctx context.Context) (*big.Int, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for SuggestGasTipCap") - } - - var r0 *big.Int - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*big.Int, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *big.Int); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*big.Int) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_SuggestGasTipCap_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'SuggestGasTipCap' -type L2Mock_SuggestGasTipCap_Call struct { - *mock.Call -} - -// SuggestGasTipCap is a helper method to define mock.On call -// - ctx context.Context -func (_e *L2Mock_Expecter) SuggestGasTipCap(ctx interface{}) *L2Mock_SuggestGasTipCap_Call { - return &L2Mock_SuggestGasTipCap_Call{Call: _e.mock.On("SuggestGasTipCap", ctx)} -} - -func (_c *L2Mock_SuggestGasTipCap_Call) Run(run func(ctx context.Context)) *L2Mock_SuggestGasTipCap_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *L2Mock_SuggestGasTipCap_Call) Return(_a0 *big.Int, _a1 error) *L2Mock_SuggestGasTipCap_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_SuggestGasTipCap_Call) RunAndReturn(run func(context.Context) (*big.Int, error)) *L2Mock_SuggestGasTipCap_Call { - _c.Call.Return(run) - return _c -} - -// TransactionCount provides a mock function with given fields: ctx, blockHash -func (_m *L2Mock) TransactionCount(ctx context.Context, blockHash common.Hash) (uint, error) { - ret := _m.Called(ctx, blockHash) - - if len(ret) == 0 { - panic("no return value specified for TransactionCount") - } - - var r0 uint - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) (uint, error)); ok { - return rf(ctx, blockHash) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash) uint); ok { - r0 = rf(ctx, blockHash) - } else { - r0 = ret.Get(0).(uint) - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash) error); ok { - r1 = rf(ctx, blockHash) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_TransactionCount_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionCount' -type L2Mock_TransactionCount_Call struct { - *mock.Call -} - -// TransactionCount is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -func (_e *L2Mock_Expecter) TransactionCount(ctx interface{}, blockHash interface{}) *L2Mock_TransactionCount_Call { - return &L2Mock_TransactionCount_Call{Call: _e.mock.On("TransactionCount", ctx, blockHash)} -} - -func (_c *L2Mock_TransactionCount_Call) Run(run func(ctx context.Context, blockHash common.Hash)) *L2Mock_TransactionCount_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash)) - }) - return _c -} - -func (_c *L2Mock_TransactionCount_Call) Return(_a0 uint, _a1 error) *L2Mock_TransactionCount_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_TransactionCount_Call) RunAndReturn(run func(context.Context, common.Hash) (uint, error)) *L2Mock_TransactionCount_Call { - _c.Call.Return(run) - return _c -} - -// TransactionInBlock provides a mock function with given fields: ctx, blockHash, index -func (_m *L2Mock) TransactionInBlock(ctx context.Context, blockHash common.Hash, index uint) (*types.Transaction, error) { - ret := _m.Called(ctx, blockHash, index) - - if len(ret) == 0 { - panic("no return value specified for TransactionInBlock") - } - - var r0 *types.Transaction - var r1 error - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) (*types.Transaction, error)); ok { - return rf(ctx, blockHash, index) - } - if rf, ok := ret.Get(0).(func(context.Context, common.Hash, uint) *types.Transaction); ok { - r0 = rf(ctx, blockHash, index) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Transaction) - } - } - - if rf, ok := ret.Get(1).(func(context.Context, common.Hash, uint) error); ok { - r1 = rf(ctx, blockHash, index) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// L2Mock_TransactionInBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TransactionInBlock' -type L2Mock_TransactionInBlock_Call struct { - *mock.Call -} - -// TransactionInBlock is a helper method to define mock.On call -// - ctx context.Context -// - blockHash common.Hash -// - index uint -func (_e *L2Mock_Expecter) TransactionInBlock(ctx interface{}, blockHash interface{}, index interface{}) *L2Mock_TransactionInBlock_Call { - return &L2Mock_TransactionInBlock_Call{Call: _e.mock.On("TransactionInBlock", ctx, blockHash, index)} -} - -func (_c *L2Mock_TransactionInBlock_Call) Run(run func(ctx context.Context, blockHash common.Hash, index uint)) *L2Mock_TransactionInBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(common.Hash), args[2].(uint)) - }) - return _c -} - -func (_c *L2Mock_TransactionInBlock_Call) Return(_a0 *types.Transaction, _a1 error) *L2Mock_TransactionInBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *L2Mock_TransactionInBlock_Call) RunAndReturn(run func(context.Context, common.Hash, uint) (*types.Transaction, error)) *L2Mock_TransactionInBlock_Call { - _c.Call.Return(run) - return _c -} - -// NewL2Mock creates a new instance of L2Mock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewL2Mock(t interface { - mock.TestingT - Cleanup(func()) -}) *L2Mock { - mock := &L2Mock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/sync/mock_evm_downloader_full.go b/sync/mock_evm_downloader_full.go deleted file mode 100644 index 43fed1ede..000000000 --- a/sync/mock_evm_downloader_full.go +++ /dev/null @@ -1,276 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package sync - -import ( - context "context" - - types "github.com/ethereum/go-ethereum/core/types" - mock "github.com/stretchr/testify/mock" -) - -// EVMDownloaderMock is an autogenerated mock type for the evmDownloaderFull type -type EVMDownloaderMock struct { - mock.Mock -} - -type EVMDownloaderMock_Expecter struct { - mock *mock.Mock -} - -func (_m *EVMDownloaderMock) EXPECT() *EVMDownloaderMock_Expecter { - return &EVMDownloaderMock_Expecter{mock: &_m.Mock} -} - -// Download provides a mock function with given fields: ctx, fromBlock, downloadedCh -func (_m *EVMDownloaderMock) Download(ctx context.Context, fromBlock uint64, downloadedCh chan EVMBlock) { - _m.Called(ctx, fromBlock, downloadedCh) -} - -// EVMDownloaderMock_Download_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Download' -type EVMDownloaderMock_Download_Call struct { - *mock.Call -} - -// Download is a helper method to define mock.On call -// - ctx context.Context -// - fromBlock uint64 -// - downloadedCh chan EVMBlock -func (_e *EVMDownloaderMock_Expecter) Download(ctx interface{}, fromBlock interface{}, downloadedCh interface{}) *EVMDownloaderMock_Download_Call { - return &EVMDownloaderMock_Download_Call{Call: _e.mock.On("Download", ctx, fromBlock, downloadedCh)} -} - -func (_c *EVMDownloaderMock_Download_Call) Run(run func(ctx context.Context, fromBlock uint64, downloadedCh chan EVMBlock)) *EVMDownloaderMock_Download_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint64), args[2].(chan EVMBlock)) - }) - return _c -} - -func (_c *EVMDownloaderMock_Download_Call) Return() *EVMDownloaderMock_Download_Call { - _c.Call.Return() - return _c -} - -func (_c *EVMDownloaderMock_Download_Call) RunAndReturn(run func(context.Context, uint64, chan EVMBlock)) *EVMDownloaderMock_Download_Call { - _c.Run(run) - return _c -} - -// GetBlockHeader provides a mock function with given fields: ctx, blockNum -func (_m *EVMDownloaderMock) GetBlockHeader(ctx context.Context, blockNum uint64) (EVMBlockHeader, bool) { - ret := _m.Called(ctx, blockNum) - - if len(ret) == 0 { - panic("no return value specified for GetBlockHeader") - } - - var r0 EVMBlockHeader - var r1 bool - if rf, ok := ret.Get(0).(func(context.Context, uint64) (EVMBlockHeader, bool)); ok { - return rf(ctx, blockNum) - } - if rf, ok := ret.Get(0).(func(context.Context, uint64) EVMBlockHeader); ok { - r0 = rf(ctx, blockNum) - } else { - r0 = ret.Get(0).(EVMBlockHeader) - } - - if rf, ok := ret.Get(1).(func(context.Context, uint64) bool); ok { - r1 = rf(ctx, blockNum) - } else { - r1 = ret.Get(1).(bool) - } - - return r0, r1 -} - -// EVMDownloaderMock_GetBlockHeader_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetBlockHeader' -type EVMDownloaderMock_GetBlockHeader_Call struct { - *mock.Call -} - -// GetBlockHeader is a helper method to define mock.On call -// - ctx context.Context -// - blockNum uint64 -func (_e *EVMDownloaderMock_Expecter) GetBlockHeader(ctx interface{}, blockNum interface{}) *EVMDownloaderMock_GetBlockHeader_Call { - return &EVMDownloaderMock_GetBlockHeader_Call{Call: _e.mock.On("GetBlockHeader", ctx, blockNum)} -} - -func (_c *EVMDownloaderMock_GetBlockHeader_Call) Run(run func(ctx context.Context, blockNum uint64)) *EVMDownloaderMock_GetBlockHeader_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint64)) - }) - return _c -} - -func (_c *EVMDownloaderMock_GetBlockHeader_Call) Return(_a0 EVMBlockHeader, _a1 bool) *EVMDownloaderMock_GetBlockHeader_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *EVMDownloaderMock_GetBlockHeader_Call) RunAndReturn(run func(context.Context, uint64) (EVMBlockHeader, bool)) *EVMDownloaderMock_GetBlockHeader_Call { - _c.Call.Return(run) - return _c -} - -// GetEventsByBlockRange provides a mock function with given fields: ctx, fromBlock, toBlock -func (_m *EVMDownloaderMock) GetEventsByBlockRange(ctx context.Context, fromBlock uint64, toBlock uint64) EVMBlocks { - ret := _m.Called(ctx, fromBlock, toBlock) - - if len(ret) == 0 { - panic("no return value specified for GetEventsByBlockRange") - } - - var r0 EVMBlocks - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64) EVMBlocks); ok { - r0 = rf(ctx, fromBlock, toBlock) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(EVMBlocks) - } - } - - return r0 -} - -// GetLastFinalizedBlock provides a mock function with given fields: ctx -func (_m *EVMDownloaderMock) GetLastFinalizedBlock(ctx context.Context) (*types.Header, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetLastFinalizedBlock") - } - - var r0 *types.Header - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (*types.Header, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) *types.Header); ok { - r0 = rf(ctx) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*types.Header) - } - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// GetLogs provides a mock function with given fields: ctx, fromBlock, toBlock -func (_m *EVMDownloaderMock) GetLogs(ctx context.Context, fromBlock uint64, toBlock uint64) []types.Log { - ret := _m.Called(ctx, fromBlock, toBlock) - - if len(ret) == 0 { - panic("no return value specified for GetLogs") - } - - var r0 []types.Log - if rf, ok := ret.Get(0).(func(context.Context, uint64, uint64) []types.Log); ok { - r0 = rf(ctx, fromBlock, toBlock) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).([]types.Log) - } - } - - return r0 -} - -// EVMDownloaderMock_GetLogs_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLogs' -type EVMDownloaderMock_GetLogs_Call struct { - *mock.Call -} - -// GetLogs is a helper method to define mock.On call -// - ctx context.Context -// - fromBlock uint64 -// - toBlock uint64 -func (_e *EVMDownloaderMock_Expecter) GetLogs(ctx interface{}, fromBlock interface{}, toBlock interface{}) *EVMDownloaderMock_GetLogs_Call { - return &EVMDownloaderMock_GetLogs_Call{Call: _e.mock.On("GetLogs", ctx, fromBlock, toBlock)} -} - -func (_c *EVMDownloaderMock_GetLogs_Call) Run(run func(ctx context.Context, fromBlock uint64, toBlock uint64)) *EVMDownloaderMock_GetLogs_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint64), args[2].(uint64)) - }) - return _c -} - -func (_c *EVMDownloaderMock_GetLogs_Call) Return(_a0 []types.Log) *EVMDownloaderMock_GetLogs_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *EVMDownloaderMock_GetLogs_Call) RunAndReturn(run func(context.Context, uint64, uint64) []types.Log) *EVMDownloaderMock_GetLogs_Call { - _c.Call.Return(run) - return _c -} - -// WaitForNewBlocks provides a mock function with given fields: ctx, lastBlockSeen -func (_m *EVMDownloaderMock) WaitForNewBlocks(ctx context.Context, lastBlockSeen uint64) uint64 { - ret := _m.Called(ctx, lastBlockSeen) - - if len(ret) == 0 { - panic("no return value specified for WaitForNewBlocks") - } - - var r0 uint64 - if rf, ok := ret.Get(0).(func(context.Context, uint64) uint64); ok { - r0 = rf(ctx, lastBlockSeen) - } else { - r0 = ret.Get(0).(uint64) - } - - return r0 -} - -// EVMDownloaderMock_WaitForNewBlocks_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'WaitForNewBlocks' -type EVMDownloaderMock_WaitForNewBlocks_Call struct { - *mock.Call -} - -// WaitForNewBlocks is a helper method to define mock.On call -// - ctx context.Context -// - lastBlockSeen uint64 -func (_e *EVMDownloaderMock_Expecter) WaitForNewBlocks(ctx interface{}, lastBlockSeen interface{}) *EVMDownloaderMock_WaitForNewBlocks_Call { - return &EVMDownloaderMock_WaitForNewBlocks_Call{Call: _e.mock.On("WaitForNewBlocks", ctx, lastBlockSeen)} -} - -func (_c *EVMDownloaderMock_WaitForNewBlocks_Call) Run(run func(ctx context.Context, lastBlockSeen uint64)) *EVMDownloaderMock_WaitForNewBlocks_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint64)) - }) - return _c -} - -func (_c *EVMDownloaderMock_WaitForNewBlocks_Call) Return(newLastBlock uint64) *EVMDownloaderMock_WaitForNewBlocks_Call { - _c.Call.Return(newLastBlock) - return _c -} - -func (_c *EVMDownloaderMock_WaitForNewBlocks_Call) RunAndReturn(run func(context.Context, uint64) uint64) *EVMDownloaderMock_WaitForNewBlocks_Call { - _c.Call.Return(run) - return _c -} - -// NewEVMDownloaderMock creates a new instance of EVMDownloaderMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewEVMDownloaderMock(t interface { - mock.TestingT - Cleanup(func()) -}) *EVMDownloaderMock { - mock := &EVMDownloaderMock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/sync/mock_processor_interface.go b/sync/mock_processor_interface.go deleted file mode 100644 index 96ece8d42..000000000 --- a/sync/mock_processor_interface.go +++ /dev/null @@ -1,186 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package sync - -import ( - context "context" - - mock "github.com/stretchr/testify/mock" -) - -// ProcessorMock is an autogenerated mock type for the processorInterface type -type ProcessorMock struct { - mock.Mock -} - -type ProcessorMock_Expecter struct { - mock *mock.Mock -} - -func (_m *ProcessorMock) EXPECT() *ProcessorMock_Expecter { - return &ProcessorMock_Expecter{mock: &_m.Mock} -} - -// GetLastProcessedBlock provides a mock function with given fields: ctx -func (_m *ProcessorMock) GetLastProcessedBlock(ctx context.Context) (uint64, error) { - ret := _m.Called(ctx) - - if len(ret) == 0 { - panic("no return value specified for GetLastProcessedBlock") - } - - var r0 uint64 - var r1 error - if rf, ok := ret.Get(0).(func(context.Context) (uint64, error)); ok { - return rf(ctx) - } - if rf, ok := ret.Get(0).(func(context.Context) uint64); ok { - r0 = rf(ctx) - } else { - r0 = ret.Get(0).(uint64) - } - - if rf, ok := ret.Get(1).(func(context.Context) error); ok { - r1 = rf(ctx) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ProcessorMock_GetLastProcessedBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetLastProcessedBlock' -type ProcessorMock_GetLastProcessedBlock_Call struct { - *mock.Call -} - -// GetLastProcessedBlock is a helper method to define mock.On call -// - ctx context.Context -func (_e *ProcessorMock_Expecter) GetLastProcessedBlock(ctx interface{}) *ProcessorMock_GetLastProcessedBlock_Call { - return &ProcessorMock_GetLastProcessedBlock_Call{Call: _e.mock.On("GetLastProcessedBlock", ctx)} -} - -func (_c *ProcessorMock_GetLastProcessedBlock_Call) Run(run func(ctx context.Context)) *ProcessorMock_GetLastProcessedBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context)) - }) - return _c -} - -func (_c *ProcessorMock_GetLastProcessedBlock_Call) Return(_a0 uint64, _a1 error) *ProcessorMock_GetLastProcessedBlock_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ProcessorMock_GetLastProcessedBlock_Call) RunAndReturn(run func(context.Context) (uint64, error)) *ProcessorMock_GetLastProcessedBlock_Call { - _c.Call.Return(run) - return _c -} - -// ProcessBlock provides a mock function with given fields: ctx, block -func (_m *ProcessorMock) ProcessBlock(ctx context.Context, block Block) error { - ret := _m.Called(ctx, block) - - if len(ret) == 0 { - panic("no return value specified for ProcessBlock") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, Block) error); ok { - r0 = rf(ctx, block) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ProcessorMock_ProcessBlock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ProcessBlock' -type ProcessorMock_ProcessBlock_Call struct { - *mock.Call -} - -// ProcessBlock is a helper method to define mock.On call -// - ctx context.Context -// - block Block -func (_e *ProcessorMock_Expecter) ProcessBlock(ctx interface{}, block interface{}) *ProcessorMock_ProcessBlock_Call { - return &ProcessorMock_ProcessBlock_Call{Call: _e.mock.On("ProcessBlock", ctx, block)} -} - -func (_c *ProcessorMock_ProcessBlock_Call) Run(run func(ctx context.Context, block Block)) *ProcessorMock_ProcessBlock_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(Block)) - }) - return _c -} - -func (_c *ProcessorMock_ProcessBlock_Call) Return(_a0 error) *ProcessorMock_ProcessBlock_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ProcessorMock_ProcessBlock_Call) RunAndReturn(run func(context.Context, Block) error) *ProcessorMock_ProcessBlock_Call { - _c.Call.Return(run) - return _c -} - -// Reorg provides a mock function with given fields: ctx, firstReorgedBlock -func (_m *ProcessorMock) Reorg(ctx context.Context, firstReorgedBlock uint64) error { - ret := _m.Called(ctx, firstReorgedBlock) - - if len(ret) == 0 { - panic("no return value specified for Reorg") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, uint64) error); ok { - r0 = rf(ctx, firstReorgedBlock) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ProcessorMock_Reorg_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Reorg' -type ProcessorMock_Reorg_Call struct { - *mock.Call -} - -// Reorg is a helper method to define mock.On call -// - ctx context.Context -// - firstReorgedBlock uint64 -func (_e *ProcessorMock_Expecter) Reorg(ctx interface{}, firstReorgedBlock interface{}) *ProcessorMock_Reorg_Call { - return &ProcessorMock_Reorg_Call{Call: _e.mock.On("Reorg", ctx, firstReorgedBlock)} -} - -func (_c *ProcessorMock_Reorg_Call) Run(run func(ctx context.Context, firstReorgedBlock uint64)) *ProcessorMock_Reorg_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(uint64)) - }) - return _c -} - -func (_c *ProcessorMock_Reorg_Call) Return(_a0 error) *ProcessorMock_Reorg_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ProcessorMock_Reorg_Call) RunAndReturn(run func(context.Context, uint64) error) *ProcessorMock_Reorg_Call { - _c.Call.Return(run) - return _c -} - -// NewProcessorMock creates a new instance of ProcessorMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewProcessorMock(t interface { - mock.TestingT - Cleanup(func()) -}) *ProcessorMock { - mock := &ProcessorMock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/sync/mock_reorg_detector.go b/sync/mock_reorg_detector.go deleted file mode 100644 index 43551baa2..000000000 --- a/sync/mock_reorg_detector.go +++ /dev/null @@ -1,147 +0,0 @@ -// Code generated by mockery. DO NOT EDIT. - -package sync - -import ( - context "context" - - common "github.com/ethereum/go-ethereum/common" - - mock "github.com/stretchr/testify/mock" - - reorgdetector "github.com/0xPolygon/cdk/reorgdetector" -) - -// ReorgDetectorMock is an autogenerated mock type for the ReorgDetector type -type ReorgDetectorMock struct { - mock.Mock -} - -type ReorgDetectorMock_Expecter struct { - mock *mock.Mock -} - -func (_m *ReorgDetectorMock) EXPECT() *ReorgDetectorMock_Expecter { - return &ReorgDetectorMock_Expecter{mock: &_m.Mock} -} - -// AddBlockToTrack provides a mock function with given fields: ctx, id, blockNum, blockHash -func (_m *ReorgDetectorMock) AddBlockToTrack(ctx context.Context, id string, blockNum uint64, blockHash common.Hash) error { - ret := _m.Called(ctx, id, blockNum, blockHash) - - if len(ret) == 0 { - panic("no return value specified for AddBlockToTrack") - } - - var r0 error - if rf, ok := ret.Get(0).(func(context.Context, string, uint64, common.Hash) error); ok { - r0 = rf(ctx, id, blockNum, blockHash) - } else { - r0 = ret.Error(0) - } - - return r0 -} - -// ReorgDetectorMock_AddBlockToTrack_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AddBlockToTrack' -type ReorgDetectorMock_AddBlockToTrack_Call struct { - *mock.Call -} - -// AddBlockToTrack is a helper method to define mock.On call -// - ctx context.Context -// - id string -// - blockNum uint64 -// - blockHash common.Hash -func (_e *ReorgDetectorMock_Expecter) AddBlockToTrack(ctx interface{}, id interface{}, blockNum interface{}, blockHash interface{}) *ReorgDetectorMock_AddBlockToTrack_Call { - return &ReorgDetectorMock_AddBlockToTrack_Call{Call: _e.mock.On("AddBlockToTrack", ctx, id, blockNum, blockHash)} -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) Run(run func(ctx context.Context, id string, blockNum uint64, blockHash common.Hash)) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(context.Context), args[1].(string), args[2].(uint64), args[3].(common.Hash)) - }) - return _c -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) Return(_a0 error) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Return(_a0) - return _c -} - -func (_c *ReorgDetectorMock_AddBlockToTrack_Call) RunAndReturn(run func(context.Context, string, uint64, common.Hash) error) *ReorgDetectorMock_AddBlockToTrack_Call { - _c.Call.Return(run) - return _c -} - -// Subscribe provides a mock function with given fields: id -func (_m *ReorgDetectorMock) Subscribe(id string) (*reorgdetector.Subscription, error) { - ret := _m.Called(id) - - if len(ret) == 0 { - panic("no return value specified for Subscribe") - } - - var r0 *reorgdetector.Subscription - var r1 error - if rf, ok := ret.Get(0).(func(string) (*reorgdetector.Subscription, error)); ok { - return rf(id) - } - if rf, ok := ret.Get(0).(func(string) *reorgdetector.Subscription); ok { - r0 = rf(id) - } else { - if ret.Get(0) != nil { - r0 = ret.Get(0).(*reorgdetector.Subscription) - } - } - - if rf, ok := ret.Get(1).(func(string) error); ok { - r1 = rf(id) - } else { - r1 = ret.Error(1) - } - - return r0, r1 -} - -// ReorgDetectorMock_Subscribe_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Subscribe' -type ReorgDetectorMock_Subscribe_Call struct { - *mock.Call -} - -// Subscribe is a helper method to define mock.On call -// - id string -func (_e *ReorgDetectorMock_Expecter) Subscribe(id interface{}) *ReorgDetectorMock_Subscribe_Call { - return &ReorgDetectorMock_Subscribe_Call{Call: _e.mock.On("Subscribe", id)} -} - -func (_c *ReorgDetectorMock_Subscribe_Call) Run(run func(id string)) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Run(func(args mock.Arguments) { - run(args[0].(string)) - }) - return _c -} - -func (_c *ReorgDetectorMock_Subscribe_Call) Return(_a0 *reorgdetector.Subscription, _a1 error) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Return(_a0, _a1) - return _c -} - -func (_c *ReorgDetectorMock_Subscribe_Call) RunAndReturn(run func(string) (*reorgdetector.Subscription, error)) *ReorgDetectorMock_Subscribe_Call { - _c.Call.Return(run) - return _c -} - -// NewReorgDetectorMock creates a new instance of ReorgDetectorMock. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. -// The first argument is typically a *testing.T value. -func NewReorgDetectorMock(t interface { - mock.TestingT - Cleanup(func()) -}) *ReorgDetectorMock { - mock := &ReorgDetectorMock{} - mock.Mock.Test(t) - - t.Cleanup(func() { mock.AssertExpectations(t) }) - - return mock -} diff --git a/test/Makefile b/test/Makefile index 08de85f0f..b05b83ce5 100644 --- a/test/Makefile +++ b/test/Makefile @@ -1,4 +1,4 @@ -COMMON_MOCKERY_PARAMS=--disable-version-string --with-expecter --exported +COMMON_MOCKERY_PARAMS=--with-expecter --exported .PHONY: generate-mocks generate-mocks: @@ -7,22 +7,22 @@ generate-mocks: .PHONY: test-e2e-fork9-validium test-e2e-fork9-validium: stop ./run-e2e.sh fork9 cdk-validium - bats bats/fep/ + bats bats/ .PHONY: test-e2e-fork11-rollup test-e2e-fork11-rollup: stop ./run-e2e.sh fork11 rollup - bats bats/fep/ + bats bats/ .PHONY: test-e2e-fork12-validium test-e2e-fork12-validium: stop ./run-e2e.sh fork12 cdk-validium - bats bats/fep/ + bats bats/ .PHONY: test-e2e-fork12-rollup test-e2e-fork12-rollup: stop ./run-e2e.sh fork12 rollup - bats bats/fep/ + bats bats/ .PHONY: stop stop: diff --git a/test/aggregator/mocks/mock_synchronizer.go b/test/aggregator/mocks/mock_synchronizer.go index ae7735b17..371344fc6 100644 --- a/test/aggregator/mocks/mock_synchronizer.go +++ b/test/aggregator/mocks/mock_synchronizer.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package mocks diff --git a/test/bats/fep/access-list-e2e.bats b/test/bats/access-list-e2e.bats similarity index 98% rename from test/bats/fep/access-list-e2e.bats rename to test/bats/access-list-e2e.bats index cc621c109..bf8c7533e 100644 --- a/test/bats/fep/access-list-e2e.bats +++ b/test/bats/access-list-e2e.bats @@ -1,6 +1,6 @@ setup() { - load '../helpers/common-setup' - load '../helpers/common' + load 'helpers/common-setup' + load 'helpers/common' _common_setup diff --git a/test/bats/fep/basic-e2e.bats b/test/bats/basic-e2e.bats similarity index 99% rename from test/bats/fep/basic-e2e.bats rename to test/bats/basic-e2e.bats index d977f4bcb..0fbb7f40b 100644 --- a/test/bats/fep/basic-e2e.bats +++ b/test/bats/basic-e2e.bats @@ -1,6 +1,6 @@ setup() { - load '../helpers/common-setup' - load '../helpers/common' + load 'helpers/common-setup' + load 'helpers/common' _common_setup diff --git a/test/bats/fep/bridge-e2e.bats b/test/bats/bridge-e2e.bats similarity index 98% rename from test/bats/fep/bridge-e2e.bats rename to test/bats/bridge-e2e.bats index d92032979..b632832e1 100644 --- a/test/bats/fep/bridge-e2e.bats +++ b/test/bats/bridge-e2e.bats @@ -1,7 +1,7 @@ setup() { - load '../helpers/common-setup' - load '../helpers/common' - load '../helpers/lxly-bridge' + load 'helpers/common-setup' + load 'helpers/common' + load 'helpers/lxly-bridge' _common_setup diff --git a/test/bats/fep/e2e.bats b/test/bats/e2e.bats similarity index 57% rename from test/bats/fep/e2e.bats rename to test/bats/e2e.bats index a468e7aa3..e53bba1fb 100644 --- a/test/bats/fep/e2e.bats +++ b/test/bats/e2e.bats @@ -1,11 +1,11 @@ setup() { - load '../helpers/common-setup' + load 'helpers/common-setup' _common_setup } @test "Verify batches" { echo "Waiting 10 minutes to get some verified batch...." - run $PROJECT_ROOT/../scripts/batch_verification_monitor.sh 0 600 + run $PROJECT_ROOT/scripts/batch_verification_monitor.sh 0 600 assert_success } diff --git a/test/helpers/e2e.go b/test/helpers/e2e.go index 3bfff882b..dfc0ce5cb 100644 --- a/test/helpers/e2e.go +++ b/test/helpers/e2e.go @@ -10,12 +10,12 @@ import ( "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/globalexitrootmanagerl2sovereignchain" "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmbridgev2" "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmglobalexitrootv2" - "github.com/0xPolygon/cdk/bridgesync" - cfgTypes "github.com/0xPolygon/cdk/config/types" - "github.com/0xPolygon/cdk/etherman" - "github.com/0xPolygon/cdk/l1infotreesync" - "github.com/0xPolygon/cdk/reorgdetector" "github.com/0xPolygon/cdk/test/contracts/transparentupgradableproxy" + "github.com/agglayer/aggkit/bridgesync" + aggkitTypes "github.com/agglayer/aggkit/config/types" + aggkitetherman "github.com/agglayer/aggkit/etherman" + "github.com/agglayer/aggkit/l1infotreesync" + "github.com/agglayer/aggkit/reorgdetector" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" @@ -83,7 +83,7 @@ func L1Setup(t *testing.T) *L1Environment { dbPathReorgDetectorL1 := path.Join(t.TempDir(), "ReorgDetectorL1.sqlite") rdL1, err := reorgdetector.New(l1Client.Client(), reorgdetector.Config{ DBPath: dbPathReorgDetectorL1, - CheckReorgsInterval: cfgTypes.Duration{Duration: time.Millisecond * 100}, //nolint:mnd + CheckReorgsInterval: aggkitTypes.Duration{Duration: time.Millisecond * 100}, //nolint:mnd }, reorgdetector.L1) require.NoError(t, err) go rdL1.Start(ctx) //nolint:errcheck @@ -93,11 +93,11 @@ func L1Setup(t *testing.T) *L1Environment { l1InfoTreeSync, err := l1infotreesync.New( ctx, dbPathL1InfoTreeSync, gerL1Addr, common.Address{}, - syncBlockChunkSize, etherman.LatestBlock, + syncBlockChunkSize, aggkitetherman.LatestBlock, rdL1, l1Client.Client(), time.Millisecond, 0, periodRetry, retries, l1infotreesync.FlagAllowWrongContractsAddrs, - etherman.SafeBlock, + aggkitetherman.SafeBlock, ) require.NoError(t, err) @@ -117,9 +117,9 @@ func L1Setup(t *testing.T) *L1Environment { dbPathBridgeSyncL1 := path.Join(t.TempDir(), "BridgeSyncL1.sqlite") bridgeL1Sync, err := bridgesync.NewL1( ctx, dbPathBridgeSyncL1, bridgeL1Addr, - syncBlockChunks, etherman.LatestBlock, rdL1, testClient, + syncBlockChunks, aggkitetherman.LatestBlock, rdL1, testClient, initialBlock, waitForNewBlocksPeriod, retryPeriod, - retriesCount, originNetwork, false, etherman.SafeBlock) + retriesCount, originNetwork, false) require.NoError(t, err) go bridgeL1Sync.Start(ctx) @@ -154,7 +154,7 @@ func L2Setup(t *testing.T, networkID uint32) *L2Environment { dbPathReorgL2 := path.Join(t.TempDir(), "ReorgDetectorL2.sqlite") rdL2, err := reorgdetector.New(l2Client.Client(), reorgdetector.Config{ DBPath: dbPathReorgL2, - CheckReorgsInterval: cfgTypes.Duration{Duration: time.Millisecond * 100}}, //nolint:mnd + CheckReorgsInterval: aggkitTypes.Duration{Duration: time.Millisecond * 100}}, //nolint:mnd reorgdetector.L2, ) require.NoError(t, err) @@ -175,9 +175,9 @@ func L2Setup(t *testing.T, networkID uint32) *L2Environment { bridgeL2Sync, err := bridgesync.NewL2( ctx, dbPathL2BridgeSync, bridgeL2Addr, syncBlockChunks, - etherman.LatestBlock, rdL2, testClient, + aggkitetherman.LatestBlock, rdL2, testClient, initialBlock, waitForNewBlocksPeriod, retryPeriod, - retriesCount, originNetwork, false, etherman.LatestBlock) + retriesCount, originNetwork, false) require.NoError(t, err) go bridgeL2Sync.Start(ctx) diff --git a/test/helpers/ethtxmanmock_e2e.go b/test/helpers/ethtxmanmock_e2e.go index 30f28effd..f57476de5 100644 --- a/test/helpers/ethtxmanmock_e2e.go +++ b/test/helpers/ethtxmanmock_e2e.go @@ -7,8 +7,8 @@ import ( big "math/big" "testing" - "github.com/0xPolygon/cdk/log" ethtxtypes "github.com/0xPolygon/zkevm-ethtx-manager/types" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" diff --git a/test/helpers/mock_eth_tx_manager.go b/test/helpers/mock_eth_tx_manager.go index 7937bf1d1..2320a1436 100644 --- a/test/helpers/mock_eth_tx_manager.go +++ b/test/helpers/mock_eth_tx_manager.go @@ -1,4 +1,4 @@ -// Code generated by mockery. DO NOT EDIT. +// Code generated by mockery v2.52.2. DO NOT EDIT. package helpers diff --git a/test/helpers/reorg.go b/test/helpers/reorg.go index 601cbe712..136de16a4 100644 --- a/test/helpers/reorg.go +++ b/test/helpers/reorg.go @@ -6,7 +6,7 @@ import ( "testing" "time" - "github.com/0xPolygon/cdk/log" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/ethclient/simulated" "github.com/stretchr/testify/require" ) diff --git a/test/helpers/simulated.go b/test/helpers/simulated.go index 2b0b0dac1..5cc7b8752 100644 --- a/test/helpers/simulated.go +++ b/test/helpers/simulated.go @@ -8,8 +8,8 @@ import ( "testing" "github.com/0xPolygon/cdk-contracts-tooling/contracts/l2-sovereign-chain/polygonzkevmbridgev2" - "github.com/0xPolygon/cdk/log" "github.com/0xPolygon/cdk/test/contracts/transparentupgradableproxy" + "github.com/agglayer/aggkit/log" "github.com/ethereum/go-ethereum/accounts/abi/bind" "github.com/ethereum/go-ethereum/common" "github.com/ethereum/go-ethereum/core/types" diff --git a/translator/translator_impl.go b/translator/translator_impl.go index cd7fbc426..68a3f8459 100644 --- a/translator/translator_impl.go +++ b/translator/translator_impl.go @@ -1,6 +1,6 @@ package translator -import "github.com/0xPolygon/cdk/log" +import "github.com/agglayer/aggkit/log" type TranslatorFullMatchRule struct { // If null match any context diff --git a/tree/appendonlytree.go b/tree/appendonlytree.go deleted file mode 100644 index 7dbead014..000000000 --- a/tree/appendonlytree.go +++ /dev/null @@ -1,131 +0,0 @@ -package tree - -import ( - "database/sql" - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" -) - -var ( - ErrInvalidIndex = errors.New("invalid index") -) - -// AppendOnlyTree is a tree where leaves are added sequentially (by index) -type AppendOnlyTree struct { - *Tree - lastLeftCache [types.DefaultHeight]common.Hash - lastIndex int64 -} - -// NewAppendOnlyTree creates a AppendOnlyTree -func NewAppendOnlyTree(db *sql.DB, dbPrefix string) *AppendOnlyTree { - t := newTree(db, dbPrefix) - return &AppendOnlyTree{ - Tree: t, - // -1 is used to indicate no leafs, 0 means the first leaf is added (at index 0) and so on. - // In order to differentiate the "cache not initialised" we need any value smaller than -1 - lastIndex: -2, - } -} - -func (t *AppendOnlyTree) AddLeaf(tx db.Txer, blockNum, blockPosition uint64, leaf types.Leaf) error { - if int64(leaf.Index) != t.lastIndex+1 { - // rebuild cache - if err := t.initCache(tx); err != nil { - return err - } - if int64(leaf.Index) != t.lastIndex+1 { - log.Errorf( - "mismatched index. Expected: %d, actual: %d", - t.lastIndex+1, leaf.Index, - ) - return ErrInvalidIndex - } - } - // Calculate new tree nodes - currentChildHash := leaf.Hash - newNodes := []types.TreeNode{} - for h := uint8(0); h < types.DefaultHeight; h++ { - var parent types.TreeNode - if leaf.Index&(1< 0 { - // Add child to the right - parent = newTreeNode(t.lastLeftCache[h], currentChildHash) - } else { - // Add child to the left - parent = newTreeNode(currentChildHash, t.zeroHashes[h]) - // Update cache - t.lastLeftCache[h] = currentChildHash - } - currentChildHash = parent.Hash - newNodes = append(newNodes, parent) - } - - // store root - if err := t.storeRoot(tx, types.Root{ - Hash: currentChildHash, - Index: leaf.Index, - BlockNum: blockNum, - BlockPosition: blockPosition, - }); err != nil { - return err - } - - // store nodes - if err := t.storeNodes(tx, newNodes); err != nil { - return err - } - t.lastIndex++ - tx.AddRollbackCallback(func() { - log.Debugf("decreasing index due to rollback") - t.lastIndex-- - }) - return nil -} - -func (t *AppendOnlyTree) initCache(tx db.Txer) error { - siblings := [types.DefaultHeight]common.Hash{} - lastRoot, err := t.getLastRootWithTx(tx) - if err != nil { - if errors.Is(err, db.ErrNotFound) { - t.lastIndex = -1 - t.lastLeftCache = siblings - return nil - } - return err - } - t.lastIndex = int64(lastRoot.Index) - currentNodeHash := lastRoot.Hash - index := t.lastIndex - // It starts in height-1 because 0 is the level of the leafs - for h := int(types.DefaultHeight - 1); h >= 0; h-- { - currentNode, err := t.getRHTNode(tx, currentNodeHash) - if err != nil { - return fmt.Errorf( - "error getting node %s from the RHT at height %d with root %s: %w", - currentNodeHash.Hex(), h, lastRoot.Hash.Hex(), err, - ) - } - if currentNode == nil { - return db.ErrNotFound - } - siblings[h] = currentNode.Left - if index&(1< 0 { - currentNodeHash = currentNode.Right - } else { - currentNodeHash = currentNode.Left - } - } - - // Reverse the siblings to go from leafs to root - for i, j := 0, len(siblings)-1; i == j; i, j = i+1, j-1 { - siblings[i], siblings[j] = siblings[j], siblings[i] - } - - t.lastLeftCache = siblings - return nil -} diff --git a/tree/migrations/migrations.go b/tree/migrations/migrations.go deleted file mode 100644 index dd5847e7c..000000000 --- a/tree/migrations/migrations.go +++ /dev/null @@ -1,22 +0,0 @@ -package migrations - -import ( - _ "embed" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/db/types" -) - -//go:embed tree0001.sql -var mig001 string - -var Migrations = []types.Migration{ - { - ID: "tree001", - SQL: mig001, - }, -} - -func RunMigrations(dbPath string) error { - return db.RunMigrations(dbPath, Migrations) -} diff --git a/tree/migrations/tree0001.sql b/tree/migrations/tree0001.sql deleted file mode 100644 index f70d048eb..000000000 --- a/tree/migrations/tree0001.sql +++ /dev/null @@ -1,17 +0,0 @@ --- +migrate Down -DROP TABLE IF EXISTS /*dbprefix*/root; -DROP TABLE IF EXISTS /*dbprefix*/rht; - --- +migrate Up -CREATE TABLE /*dbprefix*/root ( - hash VARCHAR PRIMARY KEY, - position INTEGER NOT NULL, - block_num BIGINT NOT NULL, - block_position BIGINT NOT NULL -); - -CREATE TABLE /*dbprefix*/rht ( - hash VARCHAR PRIMARY KEY, - left VARCHAR NOT NULL, - right VARCHAR NOT NULL -); diff --git a/tree/testvectors/claim-vectors.json b/tree/testvectors/claim-vectors.json deleted file mode 100644 index 4778e9e43..000000000 --- a/tree/testvectors/claim-vectors.json +++ /dev/null @@ -1,306 +0,0 @@ -[ - { - "leafs": [ - { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x", - "leafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - }, - { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345670", - "leafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - }, - { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345678", - "leafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - }, - { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266", - "leafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242" - } - ], - "index": 0, - "proof": [ - "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f", - "0xb48c8301099f75206bc93b1512c7b3855b60b4f8cbaedf8679a184d1d450a4f1", - "0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30", - "0x21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85", - "0xe58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344", - "0x0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d", - "0x887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968", - "0xffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83", - "0x9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af", - "0xcefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0", - "0xf9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5", - "0xf8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892", - "0x3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c", - "0xc1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb", - "0x5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc", - "0xda7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2", - "0x2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f", - "0xe1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a", - "0x5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0", - "0xb46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0", - "0xc65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2", - "0xf4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9", - "0x5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377", - "0x4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652", - "0xcdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef", - "0x0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d", - "0xb8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0", - "0x838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e", - "0x662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e", - "0x388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322", - "0x93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735", - "0x8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9" - ], - "root": "0x42d3339fe8eb57770953423f20a029e778a707e8d58aaf110b40d5eb4dd25721" - }, - { - "leafs": [ - { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x", - "leafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - }, - { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345670", - "leafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - }, - { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345678", - "leafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - }, - { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266", - "leafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242" - } - ], - "index": 1, - "proof": [ - "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5", - "0xb48c8301099f75206bc93b1512c7b3855b60b4f8cbaedf8679a184d1d450a4f1", - "0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30", - "0x21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85", - "0xe58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344", - "0x0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d", - "0x887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968", - "0xffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83", - "0x9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af", - "0xcefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0", - "0xf9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5", - "0xf8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892", - "0x3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c", - "0xc1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb", - "0x5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc", - "0xda7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2", - "0x2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f", - "0xe1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a", - "0x5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0", - "0xb46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0", - "0xc65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2", - "0xf4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9", - "0x5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377", - "0x4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652", - "0xcdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef", - "0x0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d", - "0xb8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0", - "0x838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e", - "0x662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e", - "0x388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322", - "0x93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735", - "0x8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9" - ], - "root": "0x42d3339fe8eb57770953423f20a029e778a707e8d58aaf110b40d5eb4dd25721" - }, - { - "leafs": [ - { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x", - "leafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - }, - { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345670", - "leafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - }, - { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345678", - "leafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - }, - { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266", - "leafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242" - } - ], - "index": 2, - "proof": [ - "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242", - "0x653142d4a4d6f7985a3f33cad31e011dbee8909846b34c38c7b235ca08828521", - "0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30", - "0x21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85", - "0xe58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344", - "0x0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d", - "0x887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968", - "0xffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83", - "0x9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af", - "0xcefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0", - "0xf9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5", - "0xf8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892", - "0x3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c", - "0xc1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb", - "0x5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc", - "0xda7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2", - "0x2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f", - "0xe1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a", - "0x5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0", - "0xb46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0", - "0xc65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2", - "0xf4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9", - "0x5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377", - "0x4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652", - "0xcdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef", - "0x0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d", - "0xb8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0", - "0x838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e", - "0x662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e", - "0x388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322", - "0x93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735", - "0x8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9" - ], - "root": "0x42d3339fe8eb57770953423f20a029e778a707e8d58aaf110b40d5eb4dd25721" - }, - { - "leafs": [ - { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x", - "leafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - }, - { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345670", - "leafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - }, - { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345678", - "leafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - }, - { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266", - "leafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242" - } - ], - "index": 3, - "proof": [ - "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d", - "0x653142d4a4d6f7985a3f33cad31e011dbee8909846b34c38c7b235ca08828521", - "0xb4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30", - "0x21ddb9a356815c3fac1026b6dec5df3124afbadb485c9ba5a3e3398a04b7ba85", - "0xe58769b32a1beaf1ea27375a44095a0d1fb664ce2dd358e7fcbfb78c26a19344", - "0x0eb01ebfc9ed27500cd4dfc979272d1f0913cc9f66540d7e8005811109e1cf2d", - "0x887c22bd8750d34016ac3c66b5ff102dacdd73f6b014e710b51e8022af9a1968", - "0xffd70157e48063fc33c97a050f7f640233bf646cc98d9524c6b92bcf3ab56f83", - "0x9867cc5f7f196b93bae1e27e6320742445d290f2263827498b54fec539f756af", - "0xcefad4e508c098b9a7e1d8feb19955fb02ba9675585078710969d3440f5054e0", - "0xf9dc3e7fe016e050eff260334f18a5d4fe391d82092319f5964f2e2eb7c1c3a5", - "0xf8b13a49e282f609c317a833fb8d976d11517c571d1221a265d25af778ecf892", - "0x3490c6ceeb450aecdc82e28293031d10c7d73bf85e57bf041a97360aa2c5d99c", - "0xc1df82d9c4b87413eae2ef048f94b4d3554cea73d92b0f7af96e0271c691e2bb", - "0x5c67add7c6caf302256adedf7ab114da0acfe870d449a3a489f781d659e8becc", - "0xda7bce9f4e8618b6bd2f4132ce798cdc7a60e7e1460a7299e3c6342a579626d2", - "0x2733e50f526ec2fa19a22b31e8ed50f23cd1fdf94c9154ed3a7609a2f1ff981f", - "0xe1d3b5c807b281e4683cc6d6315cf95b9ade8641defcb32372f1c126e398ef7a", - "0x5a2dce0a8a7f68bb74560f8f71837c2c2ebbcbf7fffb42ae1896f13f7c7479a0", - "0xb46a28b6f55540f89444f63de0378e3d121be09e06cc9ded1c20e65876d36aa0", - "0xc65e9645644786b620e2dd2ad648ddfcbf4a7e5b1a3a4ecfe7f64667a3f0b7e2", - "0xf4418588ed35a2458cffeb39b93d26f18d2ab13bdce6aee58e7b99359ec2dfd9", - "0x5a9c16dc00d6ef18b7933a6f8dc65ccb55667138776f7dea101070dc8796e377", - "0x4df84f40ae0c8229d0d6069e5c8f39a7c299677a09d367fc7b05e3bc380ee652", - "0xcdc72595f74c7b1043d0e1ffbab734648c838dfb0527d971b602bc216c9619ef", - "0x0abf5ac974a1ed57f4050aa510dd9c74f508277b39d7973bb2dfccc5eeb0618d", - "0xb8cd74046ff337f0a7bf2c8e03e10f642c1886798d71806ab1e888d9e5ee87d0", - "0x838c5655cb21c6cb83313b5a631175dff4963772cce9108188b34ac87c81c41e", - "0x662ee4dd2dd7b2bc707961b1e646c4047669dcb6584f0d8d770daf5d7e7deb2e", - "0x388ab20e2573d171a88108e79d820e98f26c0b84aa8b2f4aa4968dbb818ea322", - "0x93237c50ba75ee485f4c22adf2f741400bdf8d6a9cc7df7ecae576221665d735", - "0x8448818bb4ae4562849e949e17ac16e0be16688e156b5cf15e098c627c0056a9" - ], - "root": "0x42d3339fe8eb57770953423f20a029e778a707e8d58aaf110b40d5eb4dd25721" - } -] \ No newline at end of file diff --git a/tree/testvectors/leaf-vectors.json b/tree/testvectors/leaf-vectors.json deleted file mode 100644 index a0be08953..000000000 --- a/tree/testvectors/leaf-vectors.json +++ /dev/null @@ -1,38 +0,0 @@ -[ - { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x", - "leafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - }, - { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345670", - "leafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - }, - { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "metadata": "0x12345678", - "leafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - }, - { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266", - "leafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242" - } -] \ No newline at end of file diff --git a/tree/testvectors/root-vectors.json b/tree/testvectors/root-vectors.json deleted file mode 100644 index b1c6929c0..000000000 --- a/tree/testvectors/root-vectors.json +++ /dev/null @@ -1,67 +0,0 @@ -[ - { - "previousLeafsValues": [], - "currentRoot": "0x27ae5ba08d7291c96c8cbddcc148bf48a6d68c7974b94356f53754ef6171d757", - "newLeaf": { - "originNetwork": 0, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "currentLeafValue": "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5", - "metadata": "0x" - }, - "newRoot": "0xbf7ddbb59aa018a4c74e061f5172973ff09e4cb7f58405af117fc521f1ca46aa" - }, - { - "previousLeafsValues": [ - "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5" - ], - "currentRoot": "0xbf7ddbb59aa018a4c74e061f5172973ff09e4cb7f58405af117fc521f1ca46aa", - "newLeaf": { - "originNetwork": 1, - "tokenAddress": "0x6B175474E89094C44Da98b954EedeAC495271d0F", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 0, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "currentLeafValue": "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f", - "metadata": "0x12345670" - }, - "newRoot": "0xa7042a3ce14f384bbff63f1cee6ee5579193c2d7002e0034854963322cda6128" - }, - { - "previousLeafsValues": [ - "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5", - "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f" - ], - "currentRoot": "0xa7042a3ce14f384bbff63f1cee6ee5579193c2d7002e0034854963322cda6128", - "newLeaf": { - "originNetwork": 0, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x8ac7230489e80000", - "destinationNetwork": 1, - "destinationAddress": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266", - "currentLeafValue": "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d", - "metadata": "0x12345678" - }, - "newRoot": "0x88e652896cb1de5962a0173a222059f51e6b943a2ba6dfc9acbff051ceb1abb5" - }, - { - "previousLeafsValues": [ - "0xa4bfa0908dc7b06d98da4309f859023d6947561bc19bc00d77f763dea1a0b9f5", - "0x315fee1aa202bf4a6bd0fde560c89be90b6e6e2aaf92dc5e8d118209abc3410f", - "0xb598ce65aa15c08dda126a2985ba54f0559eaac562bb43ba430c7344261fbc5d" - ], - "currentRoot": "0x88e652896cb1de5962a0173a222059f51e6b943a2ba6dfc9acbff051ceb1abb5", - "newLeaf": { - "originNetwork": 10, - "tokenAddress": "0x0000000000000000000000000000000000000000", - "amount": "0x01", - "destinationNetwork": 4, - "destinationAddress": "0x0000000000000000000000000000000000000000", - "currentLeafValue": "0xe6585bdf74b6a46b9ede8b1b877e1232fb79ee93106c4db8ffd49cf1685bf242", - "metadata": "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb922661234e51aad88F6F4ce6aB8827279cffFb92266" - }, - "newRoot": "0x42d3339fe8eb57770953423f20a029e778a707e8d58aaf110b40d5eb4dd25721" - } -] \ No newline at end of file diff --git a/tree/testvectors/types.go b/tree/testvectors/types.go deleted file mode 100644 index 27bc1abbc..000000000 --- a/tree/testvectors/types.go +++ /dev/null @@ -1,59 +0,0 @@ -package testvectors - -import ( - "encoding/binary" - "math/big" - - "github.com/ethereum/go-ethereum/common" - "github.com/iden3/go-iden3-crypto/keccak256" -) - -// DepositVectorRaw represents the deposit vector -type DepositVectorRaw struct { - OriginNetwork uint32 `json:"originNetwork"` - TokenAddress string `json:"tokenAddress"` - Amount string `json:"amount"` - DestinationNetwork uint32 `json:"destinationNetwork"` - DestinationAddress string `json:"destinationAddress"` - ExpectedHash string `json:"leafValue"` - CurrentHash string `json:"currentLeafValue"` - Metadata string `json:"metadata"` -} - -func (d *DepositVectorRaw) Hash() common.Hash { - origNet := make([]byte, 4) //nolint:mnd - binary.BigEndian.PutUint32(origNet, d.OriginNetwork) - destNet := make([]byte, 4) //nolint:mnd - binary.BigEndian.PutUint32(destNet, d.DestinationNetwork) - - metaHash := keccak256.Hash(common.FromHex(d.Metadata)) - var buf [32]byte - amount, _ := big.NewInt(0).SetString(d.Amount, 0) - origAddrBytes := common.HexToAddress(d.TokenAddress) - destAddrBytes := common.HexToAddress(d.DestinationAddress) - return common.BytesToHash(keccak256.Hash( - []byte{0}, // LeafType - origNet, - origAddrBytes[:], - destNet, - destAddrBytes[:], - amount.FillBytes(buf[:]), - metaHash, - )) -} - -// MTClaimVectorRaw represents the merkle proof -type MTClaimVectorRaw struct { - Deposits []DepositVectorRaw `json:"leafs"` - Index uint32 `json:"index"` - MerkleProof []string `json:"proof"` - ExpectedRoot string `json:"root"` -} - -// MTRootVectorRaw represents the root of Merkle Tree -type MTRootVectorRaw struct { - ExistingLeaves []string `json:"previousLeafsValues"` - CurrentRoot string `json:"currentRoot"` - NewLeaf DepositVectorRaw `json:"newLeaf"` - NewRoot string `json:"newRoot"` -} diff --git a/tree/tree.go b/tree/tree.go deleted file mode 100644 index 51f88a6ee..000000000 --- a/tree/tree.go +++ /dev/null @@ -1,273 +0,0 @@ -package tree - -import ( - "context" - "database/sql" - "errors" - "fmt" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/ethereum/go-ethereum/crypto" - "github.com/russross/meddler" - "golang.org/x/crypto/sha3" -) - -var ( - EmptyProof = types.Proof{} -) - -type Tree struct { - db *sql.DB - zeroHashes []common.Hash - rhtTable string - rootTable string -} - -func newTreeNode(left, right common.Hash) types.TreeNode { - var hash common.Hash - hasher := sha3.NewLegacyKeccak256() - hasher.Write(left[:]) - hasher.Write(right[:]) - copy(hash[:], hasher.Sum(nil)) - return types.TreeNode{ - Hash: hash, - Left: left, - Right: right, - } -} - -func newTree(db *sql.DB, tablePrefix string) *Tree { - t := &Tree{ - db: db, - zeroHashes: generateZeroHashes(types.DefaultHeight), - rhtTable: tablePrefix + "rht", - rootTable: tablePrefix + "root", - } - - return t -} - -func (t *Tree) getSiblings(tx db.Querier, index uint32, root common.Hash) ( - siblings types.Proof, - hasUsedZeroHashes bool, - err error, -) { - currentNodeHash := root - // It starts in height-1 because 0 is the level of the leafs - for h := int(types.DefaultHeight - 1); h >= 0; h-- { - var currentNode *types.TreeNode - currentNode, err = t.getRHTNode(tx, currentNodeHash) - if err != nil { - if errors.Is(err, db.ErrNotFound) { - hasUsedZeroHashes = true - siblings[h] = t.zeroHashes[h] - err = nil - continue - } else { - err = fmt.Errorf( - "height: %d, currentNode: %s, error: %w", - h, currentNodeHash.Hex(), err, - ) - return - } - } - /* - * Root (level h=3 => height=4) - * / \ - * O5 O6 (level h=2) - * / \ / \ - * O1 O2 O3 O4 (level h=1) - * /\ /\ /\ /\ - * 0 1 2 3 4 5 6 7 Leafs (level h=0) - * Example 1: - * Choose index = 3 => 011 binary - * Assuming we are in level 1 => h=1; 1< 011&010=010 which is higher than 0 so we need the left sibling (O1) - * Example 2: - * Choose index = 4 => 100 binary - * Assuming we are in level 1 => h=1; 1< 100&010=000 which is not higher than 0 so we need the right sibling (O4) - * Example 3: - * Choose index = 4 => 100 binary - * Assuming we are in level 2 => h=2; 1< 100&100=100 which is higher than 0 so we need the left sibling (O5) - */ - if index&(1< 0 { - siblings[h] = currentNode.Left - currentNodeHash = currentNode.Right - } else { - siblings[h] = currentNode.Right - currentNodeHash = currentNode.Left - } - } - - return -} - -// GetProof returns the merkle proof for a given index and root. -func (t *Tree) GetProof(ctx context.Context, index uint32, root common.Hash) (types.Proof, error) { - siblings, isErrNotFound, err := t.getSiblings(t.db, index, root) - if err != nil { - return types.Proof{}, err - } - if isErrNotFound { - // TODO: Validate it. It returns a proof of a tree with missing leafs - log.Warnf("getSiblings returned proof with zero hashes for index %d and root %s", index, root.String()) - } - return siblings, nil -} - -func (t *Tree) getRHTNode(tx db.Querier, nodeHash common.Hash) (*types.TreeNode, error) { - node := &types.TreeNode{} - err := meddler.QueryRow( - tx, node, - fmt.Sprintf(`SELECT * FROM %s WHERE hash = $1`, t.rhtTable), - nodeHash.String(), - ) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return node, db.ErrNotFound - } - return node, err - } - return node, err -} - -func generateZeroHashes(height uint8) []common.Hash { - var zeroHashes = []common.Hash{ - {}, - } - // This generates a leaf = HashZero in position 0. In the rest of the positions that are - // equivalent to the ascending levels, we set the hashes of the nodes. - // So all nodes from level i=5 will have the same value and same children nodes. - for i := 1; i <= int(height); i++ { - hasher := sha3.NewLegacyKeccak256() - hasher.Write(zeroHashes[i-1][:]) - hasher.Write(zeroHashes[i-1][:]) - thisHeightHash := common.Hash{} - copy(thisHeightHash[:], hasher.Sum(nil)) - zeroHashes = append(zeroHashes, thisHeightHash) - } - return zeroHashes -} - -func (t *Tree) storeNodes(tx db.Txer, nodes []types.TreeNode) error { - for i := 0; i < len(nodes); i++ { - if err := meddler.Insert(tx, t.rhtTable, &nodes[i]); err != nil { - if sqliteErr, ok := db.SQLiteErr(err); ok { - if sqliteErr.ExtendedCode == db.UniqueConstrain { - // ignore repeated entries. This is likely to happen due to not - // cleaning RHT when reorg - continue - } - } - return err - } - } - return nil -} - -func (t *Tree) storeRoot(tx db.Txer, root types.Root) error { - return meddler.Insert(tx, t.rootTable, &root) -} - -// GetLastRoot returns the last processed root -func (t *Tree) GetLastRoot(tx db.Querier) (types.Root, error) { - if tx == nil { - tx = t.db - } - return t.getLastRootWithTx(tx) -} - -func (t *Tree) getLastRootWithTx(tx db.Querier) (types.Root, error) { - var root types.Root - err := meddler.QueryRow( - tx, &root, - fmt.Sprintf(`SELECT * FROM %s ORDER BY block_num DESC, block_position DESC LIMIT 1;`, t.rootTable), - ) - if err != nil { - if errors.Is(err, sql.ErrNoRows) { - return root, db.ErrNotFound - } - return root, err - } - return root, nil -} - -// GetRootByIndex returns the root associated to the index -func (t *Tree) GetRootByIndex(ctx context.Context, index uint32) (types.Root, error) { - var root types.Root - if err := meddler.QueryRow( - t.db, &root, - fmt.Sprintf(`SELECT * FROM %s WHERE position = $1;`, t.rootTable), - index, - ); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return root, db.ErrNotFound - } - return root, err - } - return root, nil -} - -// GetRootByHash returns the root associated to the hash -func (t *Tree) GetRootByHash(ctx context.Context, hash common.Hash) (*types.Root, error) { - var root types.Root - if err := meddler.QueryRow( - t.db, &root, - fmt.Sprintf(`SELECT * FROM %s WHERE hash = $1;`, t.rootTable), - hash.Hex(), - ); err != nil { - if errors.Is(err, sql.ErrNoRows) { - return nil, db.ErrNotFound - } - return nil, err - } - - return &root, nil -} - -func (t *Tree) GetLeaf(tx db.Querier, index uint32, root common.Hash) (common.Hash, error) { - currentNodeHash := root - for h := int(types.DefaultHeight - 1); h >= 0; h-- { - currentNode, err := t.getRHTNode(tx, currentNodeHash) - if err != nil { - return common.Hash{}, err - } - if index&(1< 0 { - currentNodeHash = currentNode.Right - } else { - currentNodeHash = currentNode.Left - } - } - - return currentNodeHash, nil -} - -// Reorg deletes all the data relevant from firstReorgedBlock (includded) and onwards -func (t *Tree) Reorg(tx db.Txer, firstReorgedBlock uint64) error { - _, err := tx.Exec( - fmt.Sprintf(`DELETE FROM %s WHERE block_num >= $1`, t.rootTable), - firstReorgedBlock, - ) - return err -} - -// CalculateRoot calculates the Merkle Root based on the leaf and proof of inclusion -func CalculateRoot(leafHash common.Hash, proof [types.DefaultHeight]common.Hash, index uint32) common.Hash { - node := leafHash - - // Compute the Merkle root - for height := uint8(0); height < types.DefaultHeight; height++ { - if (index>>height)&1 == 1 { - node = crypto.Keccak256Hash(proof[height].Bytes(), node.Bytes()) - } else { - node = crypto.Keccak256Hash(node.Bytes(), proof[height].Bytes()) - } - } - - return node -} diff --git a/tree/tree_test.go b/tree/tree_test.go deleted file mode 100644 index a08211a6d..000000000 --- a/tree/tree_test.go +++ /dev/null @@ -1,210 +0,0 @@ -package tree_test - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "os" - "path" - "testing" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/log" - "github.com/0xPolygon/cdk/tree" - "github.com/0xPolygon/cdk/tree/migrations" - "github.com/0xPolygon/cdk/tree/testvectors" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestCheckExpectedRoot(t *testing.T) { - createTreeDB := func() *sql.DB { - dbPath := path.Join(t.TempDir(), "treeTestCheckExpectedRoot.sqlite") - log.Debug("DB created at: ", dbPath) - require.NoError(t, migrations.RunMigrations(dbPath)) - treeDB, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - - return treeDB - } - - addLeaves := func(merkletree *tree.AppendOnlyTree, - treeDB *sql.DB, - numOfLeavesToAdd, from int) { - tx, err := db.NewTx(context.Background(), treeDB) - require.NoError(t, err) - - for i := from; i < from+numOfLeavesToAdd; i++ { - require.NoError(t, merkletree.AddLeaf(tx, uint64(i), 0, types.Leaf{ - Index: uint32(i), - Hash: common.HexToHash(fmt.Sprintf("%x", i)), - })) - } - - require.NoError(t, tx.Commit()) - } - - t.Run("Check when no reorg", func(t *testing.T) { - numOfLeavesToAdd := 10 - indexToCheck := uint32(numOfLeavesToAdd - 1) - - treeDB := createTreeDB() - merkleTree := tree.NewAppendOnlyTree(treeDB, "") - - addLeaves(merkleTree, treeDB, numOfLeavesToAdd, 0) - - expectedRoot, err := merkleTree.GetLastRoot(nil) - require.NoError(t, err) - - addLeaves(merkleTree, treeDB, numOfLeavesToAdd, numOfLeavesToAdd) - - root2, err := merkleTree.GetRootByIndex(context.Background(), indexToCheck) - require.NoError(t, err) - require.Equal(t, expectedRoot.Hash, root2.Hash) - require.Equal(t, expectedRoot.Index, root2.Index) - }) - - t.Run("Check after rebuild tree when reorg", func(t *testing.T) { - numOfLeavesToAdd := 10 - indexToCheck := uint32(numOfLeavesToAdd - 1) - treeDB := createTreeDB() - merkleTree := tree.NewAppendOnlyTree(treeDB, "") - - addLeaves(merkleTree, treeDB, numOfLeavesToAdd, 0) - - expectedRoot, err := merkleTree.GetLastRoot(nil) - require.NoError(t, err) - - addLeaves(merkleTree, treeDB, numOfLeavesToAdd, numOfLeavesToAdd) - - // reorg tree - tx, err := db.NewTx(context.Background(), treeDB) - require.NoError(t, err) - require.NoError(t, merkleTree.Reorg(tx, uint64(indexToCheck+1))) - require.NoError(t, tx.Commit()) - - // rebuild cache on adding new leaf - tx, err = db.NewTx(context.Background(), treeDB) - require.NoError(t, err) - require.NoError(t, merkleTree.AddLeaf(tx, uint64(indexToCheck+1), 0, types.Leaf{ - Index: indexToCheck + 1, - Hash: common.HexToHash(fmt.Sprintf("%x", indexToCheck+1)), - })) - require.NoError(t, tx.Commit()) - - root2, err := merkleTree.GetRootByIndex(context.Background(), indexToCheck) - require.NoError(t, err) - require.Equal(t, expectedRoot.Hash, root2.Hash) - require.Equal(t, expectedRoot.Index, root2.Index) - }) -} - -func TestMTAddLeaf(t *testing.T) { - data, err := os.ReadFile("testvectors/root-vectors.json") - require.NoError(t, err) - - var mtTestVectors []testvectors.MTRootVectorRaw - err = json.Unmarshal(data, &mtTestVectors) - require.NoError(t, err) - ctx := context.Background() - - for ti, testVector := range mtTestVectors { - t.Run(fmt.Sprintf("Test vector %d", ti), func(t *testing.T) { - dbPath := path.Join(t.TempDir(), "treeTestMTAddLeaf.sqlite") - log.Debug("DB created at: ", dbPath) - err := migrations.RunMigrations(dbPath) - require.NoError(t, err) - treeDB, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - _, err = treeDB.Exec(`select * from root`) - require.NoError(t, err) - merkletree := tree.NewAppendOnlyTree(treeDB, "") - - // Add exisiting leaves - tx, err := db.NewTx(ctx, treeDB) - require.NoError(t, err) - for i, leaf := range testVector.ExistingLeaves { - err = merkletree.AddLeaf(tx, uint64(i), 0, types.Leaf{ - Index: uint32(i), - Hash: common.HexToHash(leaf), - }) - require.NoError(t, err) - } - require.NoError(t, tx.Commit()) - if len(testVector.ExistingLeaves) > 0 { - root, err := merkletree.GetLastRoot(nil) - require.NoError(t, err) - require.Equal(t, common.HexToHash(testVector.CurrentRoot), root.Hash) - } - - // Add new bridge - tx, err = db.NewTx(ctx, treeDB) - require.NoError(t, err) - err = merkletree.AddLeaf(tx, uint64(len(testVector.ExistingLeaves)), 0, types.Leaf{ - Index: uint32(len(testVector.ExistingLeaves)), - Hash: common.HexToHash(testVector.NewLeaf.CurrentHash), - }) - require.NoError(t, err) - require.NoError(t, tx.Commit()) - - root, err := merkletree.GetLastRoot(nil) - require.NoError(t, err) - require.Equal(t, common.HexToHash(testVector.NewRoot), root.Hash) - }) - } -} - -func TestMTGetProof(t *testing.T) { - data, err := os.ReadFile("testvectors/claim-vectors.json") - require.NoError(t, err) - - var mtTestVectors []testvectors.MTClaimVectorRaw - err = json.Unmarshal(data, &mtTestVectors) - require.NoError(t, err) - ctx := context.Background() - - for ti, testVector := range mtTestVectors { - t.Run(fmt.Sprintf("Test vector %d", ti), func(t *testing.T) { - dbPath := path.Join(t.TempDir(), "treeTestMTGetProof.sqlite") - err := migrations.RunMigrations(dbPath) - require.NoError(t, err) - treeDB, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - tre := tree.NewAppendOnlyTree(treeDB, "") - - tx, err := db.NewTx(ctx, treeDB) - require.NoError(t, err) - for li, leaf := range testVector.Deposits { - err = tre.AddLeaf(tx, uint64(li), 0, types.Leaf{ - Index: uint32(li), - Hash: leaf.Hash(), - }) - require.NoError(t, err) - } - require.NoError(t, tx.Commit()) - - root, err := tre.GetLastRoot(nil) - require.NoError(t, err) - expectedRoot := common.HexToHash(testVector.ExpectedRoot) - require.Equal(t, expectedRoot, root.Hash) - - proof, err := tre.GetProof(ctx, testVector.Index, expectedRoot) - require.NoError(t, err) - for i, sibling := range testVector.MerkleProof { - require.Equal(t, common.HexToHash(sibling), proof[i]) - } - }) - } -} - -func createTreeDBForTest(t *testing.T) *sql.DB { - t.Helper() - dbPath := path.Join(t.TempDir(), "tree_createTreeDBForTest.sqlite") - err := migrations.RunMigrations(dbPath) - require.NoError(t, err) - treeDB, err := db.NewSQLiteDB(dbPath) - require.NoError(t, err) - return treeDB -} diff --git a/tree/types/types.go b/tree/types/types.go deleted file mode 100644 index bb1173422..000000000 --- a/tree/types/types.go +++ /dev/null @@ -1,27 +0,0 @@ -package types - -import "github.com/ethereum/go-ethereum/common" - -const ( - DefaultHeight uint8 = 32 -) - -type Leaf struct { - Index uint32 - Hash common.Hash -} - -type Root struct { - Hash common.Hash `meddler:"hash,hash"` - Index uint32 `meddler:"position"` - BlockNum uint64 `meddler:"block_num"` - BlockPosition uint64 `meddler:"block_position"` -} - -type TreeNode struct { - Hash common.Hash `meddler:"hash,hash"` - Left common.Hash `meddler:"left,hash"` - Right common.Hash `meddler:"right,hash"` -} - -type Proof [DefaultHeight]common.Hash diff --git a/tree/updatabletree.go b/tree/updatabletree.go deleted file mode 100644 index be861b554..000000000 --- a/tree/updatabletree.go +++ /dev/null @@ -1,68 +0,0 @@ -package tree - -import ( - "database/sql" - "errors" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" -) - -// UpdatableTree is a tree that have updatable leaves, and doesn't need to have sequential inserts -type UpdatableTree struct { - *Tree -} - -// NewUpdatableTree returns an UpdatableTree -func NewUpdatableTree(db *sql.DB, dbPrefix string) *UpdatableTree { - t := newTree(db, dbPrefix) - ut := &UpdatableTree{ - Tree: t, - } - return ut -} - -func (t *UpdatableTree) UpsertLeaf(tx db.Txer, blockNum, blockPosition uint64, leaf types.Leaf) (common.Hash, error) { - var rootHash common.Hash - root, err := t.getLastRootWithTx(tx) - if err != nil { - if errors.Is(err, db.ErrNotFound) { - rootHash = t.zeroHashes[types.DefaultHeight] - } else { - return common.Hash{}, err - } - } else { - rootHash = root.Hash - } - siblings, _, err := t.getSiblings(tx, leaf.Index, rootHash) - if err != nil { - return common.Hash{}, err - } - currentChildHash := leaf.Hash - newNodes := []types.TreeNode{} - for h := uint8(0); h < types.DefaultHeight; h++ { - var parent types.TreeNode - if leaf.Index&(1< 0 { - // Add child to the right - parent = newTreeNode(siblings[h], currentChildHash) - } else { - // Add child to the left - parent = newTreeNode(currentChildHash, siblings[h]) - } - currentChildHash = parent.Hash - newNodes = append(newNodes, parent) - } - if err := t.storeRoot(tx, types.Root{ - Hash: currentChildHash, - Index: leaf.Index, - BlockNum: blockNum, - BlockPosition: blockPosition, - }); err != nil { - return common.Hash{}, err - } - if err := t.storeNodes(tx, newNodes); err != nil { - return common.Hash{}, err - } - return currentChildHash, nil -} diff --git a/tree/updatabletree_test.go b/tree/updatabletree_test.go deleted file mode 100644 index a684fd0e1..000000000 --- a/tree/updatabletree_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package tree_test - -import ( - "context" - "testing" - - "github.com/0xPolygon/cdk/db" - "github.com/0xPolygon/cdk/tree" - "github.com/0xPolygon/cdk/tree/types" - "github.com/ethereum/go-ethereum/common" - "github.com/stretchr/testify/require" -) - -func TestUpdatableTreeExploratory(t *testing.T) { - treeDB := createTreeDBForTest(t) - sut := tree.NewUpdatableTree(treeDB, "") - blockNum := uint64(1) - blockPosition := uint64(1) - leaf1 := types.Leaf{ - Index: 10, - Hash: common.HexToHash("0x123456"), - } - leaf2 := types.Leaf{ - Index: 1, - Hash: common.HexToHash("0x123478"), - } - ctx := context.TODO() - - tx, err := db.NewTx(ctx, treeDB) - require.NoError(t, err) - _, err = sut.UpsertLeaf(tx, blockNum, blockPosition, leaf1) - require.NoError(t, err) - - root2, err := sut.UpsertLeaf(tx, blockNum, blockPosition, leaf2) - require.NoError(t, err) - leaf1get, err := sut.GetLeaf(tx, leaf1.Index, root2) - require.NoError(t, err) - require.Equal(t, leaf1.Hash, leaf1get) - // If a leaf dont exist return 'not found' error - _, err = sut.GetLeaf(tx, 99, root2) - require.ErrorIs(t, err, db.ErrNotFound) - leaf99 := types.Leaf{ - Index: 99, - Hash: common.Hash{}, // 0x00000 - } - - _, err = sut.UpsertLeaf(tx, blockNum, blockPosition, leaf99) - require.Error(t, err, "insert 0x000 doesnt change root and return UNIQUE constraint failed: root.hash") -}