diff --git a/besu-plugins/finalized-tag-updater/src/main/kotlin/linea/consensus/LineaL1FinalizationTagUpdaterPlugin.kt b/besu-plugins/finalized-tag-updater/src/main/kotlin/linea/consensus/LineaL1FinalizationTagUpdaterPlugin.kt index 8d4af17b..8ac9f343 100644 --- a/besu-plugins/finalized-tag-updater/src/main/kotlin/linea/consensus/LineaL1FinalizationTagUpdaterPlugin.kt +++ b/besu-plugins/finalized-tag-updater/src/main/kotlin/linea/consensus/LineaL1FinalizationTagUpdaterPlugin.kt @@ -29,7 +29,7 @@ class LineaL1FinalizationTagUpdaterPlugin : BesuPlugin { service = LineaL1FinalizationUpdaterService( vertx, cliOptions.getConfig(), - LineaBesuEngineBlockTagUpdater(blockchainService) + LineaBesuEngineBlockTagUpdater(blockchainService), ) service.start() } diff --git a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/FinalizationUpdatePoller.kt b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/FinalizationUpdatePoller.kt index 867f2d72..6aa4cef5 100644 --- a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/FinalizationUpdatePoller.kt +++ b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/FinalizationUpdatePoller.kt @@ -16,7 +16,7 @@ import kotlin.time.Duration.Companion.seconds data class FinalizationUpdatePollerConfig( val pollingInterval: Duration = 12.seconds, - val blockTag: BlockParameter + val blockTag: BlockParameter, ) { init { require(pollingInterval >= 0.seconds) { @@ -30,18 +30,18 @@ class FinalizationUpdatePoller( private val config: FinalizationUpdatePollerConfig, private val lineaRollup: Web3JLineaRollupSmartContractClientReadOnly, private val finalizationHandler: (ULong) -> CompletableFuture<*>, - private val log: Logger = LogManager.getLogger(FinalizationUpdatePoller::class.java) + private val log: Logger = LogManager.getLogger(FinalizationUpdatePoller::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { private val lastFinalizationRef: AtomicReference = AtomicReference(null) override fun action(): SafeFuture<*> { return AsyncRetryer.retry( vertx, - backoffDelay = config.pollingInterval + backoffDelay = config.pollingInterval, ) { lineaRollup.finalizedL2BlockNumber(config.blockTag) .thenCompose { lineaFinalizedBlockNumber -> @@ -61,7 +61,7 @@ class FinalizationUpdatePoller( if (error.cause is UnsupportedOperationException) { log.error( "\"setFinalizedBlock\" and \"setSafeBlock\" methods are not supported in the hosting Besu client, " + - "the poller will stop now, please check the Besu client's settings" + "the poller will stop now, please check the Besu client's settings", ) super.stop() } else { diff --git a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/LineaL1FinalizationUpdaterService.kt b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/LineaL1FinalizationUpdaterService.kt index 0193d9ce..fa48e387 100644 --- a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/LineaL1FinalizationUpdaterService.kt +++ b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/LineaL1FinalizationUpdaterService.kt @@ -28,7 +28,7 @@ class LineaBesuEngineBlockTagUpdater(private val blockchainService: BlockchainSe log.info( "Linea safe/finalized block update: blockNumber={} blockHash={}", finalizedBlockNumber, - blockHash + blockHash, ) blockchainService.setSafeBlock(blockHash) blockchainService.setFinalizedBlock(blockHash) @@ -40,7 +40,7 @@ class LineaBesuEngineBlockTagUpdater(private val blockchainService: BlockchainSe log.error( "Linea safe/finalized block update failure: Method not supported or not enabled for PoS network: " + "setFinalizedBlock and setSafeBlock", - e + e, ) throw e } catch (e: Exception) { @@ -54,7 +54,7 @@ class LineaBesuEngineBlockTagUpdater(private val blockchainService: BlockchainSe } override fun lineaUpdateFinalizedBlockV1( - finalizedBlockNumber: Long + finalizedBlockNumber: Long, ) { val updateSuccess = setFinalizedAndSafeBlock(finalizedBlockNumber) log.debug("Linea safe/finalized block update: blockNumber={} success={}", finalizedBlockNumber, updateSuccess) @@ -62,10 +62,10 @@ class LineaBesuEngineBlockTagUpdater(private val blockchainService: BlockchainSe } class LineaL1FinalizationUpdater( - private val engineBlockTagUpdater: EngineBlockTagUpdater + private val engineBlockTagUpdater: EngineBlockTagUpdater, ) { fun handleL1Finalization( - finalizedBlockNumber: ULong + finalizedBlockNumber: ULong, ): CompletableFuture { runCatching { engineBlockTagUpdater @@ -80,28 +80,28 @@ class LineaL1FinalizationUpdater( class LineaL1FinalizationUpdaterService( vertx: Vertx, config: PluginConfig, - engineBlockTagUpdater: EngineBlockTagUpdater + engineBlockTagUpdater: EngineBlockTagUpdater, ) : LongRunningService { private val web3j = Web3j.build( HttpService( config.l1RpcEndpoint.toString(), - okHttpClientBuilder(LogManager.getLogger("clients.l1")).build() - ) + okHttpClientBuilder(LogManager.getLogger("clients.l1")).build(), + ), ) private val lineaRollup = Web3JLineaRollupSmartContractClientReadOnly( contractAddress = config.l1SmartContractAddress.toHexString(), - web3j = web3j + web3j = web3j, ) private val updater = LineaL1FinalizationUpdater(engineBlockTagUpdater) private val poller = FinalizationUpdatePoller( vertx, FinalizationUpdatePollerConfig( pollingInterval = config.l1PollingInterval, - blockTag = BlockParameter.Tag.FINALIZED + blockTag = BlockParameter.Tag.FINALIZED, ), lineaRollup, updater::handleL1Finalization, - LogManager.getLogger(FinalizationUpdatePoller::class.java) + LogManager.getLogger(FinalizationUpdatePoller::class.java), ) override fun start(): CompletableFuture { diff --git a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/PluginCliOptions.kt b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/PluginCliOptions.kt index c37383ef..a04f26bc 100644 --- a/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/PluginCliOptions.kt +++ b/besu-plugins/finalized-tag-updater/src/main/kotlin/net/consensys/linea/PluginCliOptions.kt @@ -11,7 +11,7 @@ import kotlin.time.toKotlinDuration data class PluginConfig( val l1SmartContractAddress: Address, val l1RpcEndpoint: URL, - val l1PollingInterval: kotlin.time.Duration + val l1PollingInterval: kotlin.time.Duration, ) { init { require(l1PollingInterval >= 1.seconds) { "Polling interval=$l1PollingInterval must be greater that 1s." } @@ -23,21 +23,21 @@ class PluginCliOptions { names = ["--plugin-linea-l1-smart-contract-address"], description = ["L1 smart contract address"], required = true, - converter = [AddressConverter::class] + converter = [AddressConverter::class], ) lateinit var l1SmartContractAddress: Address @CommandLine.Option( names = ["--plugin-linea-l1-rpc-endpoint"], description = ["L1 RPC endpoint"], - required = true + required = true, ) lateinit var l1RpcEndpoint: String @CommandLine.Option( names = ["--plugin-linea-l1-polling-interval"], description = ["L1 polling interval"], - required = false + required = false, ) var l1PollingInterval: Duration = Duration.ofSeconds(12) @@ -45,14 +45,14 @@ class PluginCliOptions { return PluginConfig( l1SmartContractAddress = l1SmartContractAddress, l1RpcEndpoint = URI(l1RpcEndpoint).toURL(), - l1PollingInterval = l1PollingInterval.toKotlinDuration() + l1PollingInterval = l1PollingInterval.toKotlinDuration(), ) } class AddressConverter : CommandLine.ITypeConverter
{ override fun convert(value: String): Address { return Address.fromHexString(value) ?: throw CommandLine.TypeConversionException( - "Invalid address: $value" + "Invalid address: $value", ) } } diff --git a/besu-plugins/finalized-tag-updater/src/test/kotlin/net/consensys/linea/consensus/ManualIntegrationTest.kt b/besu-plugins/finalized-tag-updater/src/test/kotlin/net/consensys/linea/consensus/ManualIntegrationTest.kt index d9a769b0..ac83119c 100644 --- a/besu-plugins/finalized-tag-updater/src/test/kotlin/net/consensys/linea/consensus/ManualIntegrationTest.kt +++ b/besu-plugins/finalized-tag-updater/src/test/kotlin/net/consensys/linea/consensus/ManualIntegrationTest.kt @@ -11,7 +11,7 @@ import kotlin.time.Duration.Companion.seconds class FakeEngineBlockTagUpdater : EngineBlockTagUpdater { override fun lineaUpdateFinalizedBlockV1( - finalizedBlockNumber: Long + finalizedBlockNumber: Long, ) { println("Linea finalized block update: blockNumber=$finalizedBlockNumber") } @@ -23,7 +23,7 @@ fun main() { val config = PluginConfig( l1RpcEndpoint = URI("https://mainnet.infura.io/v3/$infuraAppKey").toURL(), l1SmartContractAddress = Address.fromHexString("0xd19d4B5d358258f05D7B411E21A1460D11B0876F"), - l1PollingInterval = 1.seconds + l1PollingInterval = 1.seconds, ) val service = LineaL1FinalizationUpdaterService(vertx, config, FakeEngineBlockTagUpdater()) service.start().get() diff --git a/besu-plugins/linea-sequencer/build.gradle b/besu-plugins/linea-sequencer/build.gradle index 1587a114..760184d1 100644 --- a/besu-plugins/linea-sequencer/build.gradle +++ b/besu-plugins/linea-sequencer/build.gradle @@ -33,6 +33,15 @@ licenseReport { ] } +// Make the parent project's spotlessCheck depend on all subproject spotlessCheck tasks +afterEvaluate { + if (tasks.findByName('spotlessCheck')) { + spotlessCheck.dependsOn subprojects.collect { subproject -> + subproject.tasks.matching { task -> task.name == 'spotlessCheck' } + } + } +} + build { dependsOn checkLicense } diff --git a/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/ExecutionLayerClient.kt b/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/ExecutionLayerClient.kt index 1eb1d09f..1b75c1fb 100644 --- a/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/ExecutionLayerClient.kt +++ b/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/ExecutionLayerClient.kt @@ -6,7 +6,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class StateRecoveryStatus( val headBlockNumber: ULong, - val stateRecoverStartBlockNumber: ULong? + val stateRecoverStartBlockNumber: ULong?, ) interface ExecutionLayerClient { fun getBlockNumberAndHash(blockParameter: BlockParameter): SafeFuture diff --git a/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/RecoveryStatusPersistence.kt b/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/RecoveryStatusPersistence.kt index a252a575..043289a7 100644 --- a/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/RecoveryStatusPersistence.kt +++ b/besu-plugins/state-recovery/appcore/clients-interfaces/src/main/kotlin/linea/staterecovery/RecoveryStatusPersistence.kt @@ -24,20 +24,20 @@ class InMemoryRecoveryStatus : RecoveryStatusPersistence { } class FileBasedRecoveryStatusPersistence( - filePath: Path + filePath: Path, ) : RecoveryStatusPersistence { // A little future proofing in case we need to change the file format in the future private enum class FileVersion { - V1 // note: do not rename because it will fail to parse the file if already written + V1, // note: do not rename because it will fail to parse the file if already written } private data class RecoveryStatusEnvelopeDto( val version: FileVersion, - val recoveryStatus: RecoveryStatusV1Dto? + val recoveryStatus: RecoveryStatusV1Dto?, ) private data class RecoveryStatusV1Dto( - val recoveryStartBlockNumber: ULong + val recoveryStartBlockNumber: ULong, ) private val objectMapper = jacksonObjectMapper() private val file = filePath.toFile() @@ -46,8 +46,8 @@ class FileBasedRecoveryStatusPersistence( private fun saveToFile(status: RecoveryStatusV1Dto?) { file.writeText( objectMapper.writeValueAsString( - RecoveryStatusEnvelopeDto(FileVersion.V1, status) - ) + RecoveryStatusEnvelopeDto(FileVersion.V1, status), + ), ) } diff --git a/besu-plugins/state-recovery/appcore/clients-interfaces/src/test/kotlin/linea/staterecovery/FileRecoveryStatusPersistenceTest.kt b/besu-plugins/state-recovery/appcore/clients-interfaces/src/test/kotlin/linea/staterecovery/FileRecoveryStatusPersistenceTest.kt index 77006425..b99e7633 100644 --- a/besu-plugins/state-recovery/appcore/clients-interfaces/src/test/kotlin/linea/staterecovery/FileRecoveryStatusPersistenceTest.kt +++ b/besu-plugins/state-recovery/appcore/clients-interfaces/src/test/kotlin/linea/staterecovery/FileRecoveryStatusPersistenceTest.kt @@ -13,7 +13,7 @@ class FileRecoveryStatusPersistenceTest { @Test fun `should return null when no recovery start block number is saved`( - @TempDir tempDir: Path + @TempDir tempDir: Path, ) { val recoveryStatusPersistence = FileBasedRecoveryStatusPersistence(tempDir.resolve("recovery-status.json")) assertThat(recoveryStatusPersistence.getRecoveryStartBlockNumber()).isNull() @@ -21,7 +21,7 @@ class FileRecoveryStatusPersistenceTest { @Test fun `should return the saved recovery start block number`( - @TempDir tempDir: Path + @TempDir tempDir: Path, ) { FileBasedRecoveryStatusPersistence(tempDir.resolve("recovery-status.json")) .also { persistence -> @@ -46,7 +46,7 @@ class FileRecoveryStatusPersistenceTest { @Test fun `shall throw when it cannot create the file`( - @TempDir tempDir: Path + @TempDir tempDir: Path, ) { val dirWithoutWritePermissions = tempDir.resolve("dir-without-write-permissions") @@ -64,7 +64,7 @@ class FileRecoveryStatusPersistenceTest { @Test fun `should throw error when file version is not supported`( - @TempDir tempDir: Path + @TempDir tempDir: Path, ) { val invalidJsonPayload = """ { diff --git a/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/BlockFromL1RecoveredData.kt b/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/BlockFromL1RecoveredData.kt index b2698e31..54234f46 100644 --- a/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/BlockFromL1RecoveredData.kt +++ b/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/BlockFromL1RecoveredData.kt @@ -9,7 +9,7 @@ data class BlockHeaderFromL1RecoveredData( val coinbase: ByteArray, val blockTimestamp: Instant, val gasLimit: ULong, - val difficulty: ULong + val difficulty: ULong, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -51,7 +51,7 @@ data class BlockHeaderFromL1RecoveredData( data class BlockFromL1RecoveredData( val header: BlockHeaderFromL1RecoveredData, - val transactions: List + val transactions: List, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/TransactionFromL1RecoveredData.kt b/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/TransactionFromL1RecoveredData.kt index d15d22f7..6d29659e 100644 --- a/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/TransactionFromL1RecoveredData.kt +++ b/besu-plugins/state-recovery/appcore/domain-models/src/main/kotlin/linea/staterecovery/TransactionFromL1RecoveredData.kt @@ -14,12 +14,12 @@ data class TransactionFromL1RecoveredData( val to: ByteArray?, val value: BigInteger, val data: ByteArray?, - val accessList: List? + val accessList: List?, ) { data class AccessTuple( val address: ByteArray, - val storageKeys: List + val storageKeys: List, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlobDecompressorAndDeserializer.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlobDecompressorAndDeserializer.kt index 1b07d038..43e5f8cb 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlobDecompressorAndDeserializer.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlobDecompressorAndDeserializer.kt @@ -24,18 +24,18 @@ interface BlobDecompressorAndDeserializer { */ fun decompress( startBlockNumber: ULong, - blobs: List + blobs: List, ): SafeFuture> } data class BlockHeaderStaticFields( val coinbase: ByteArray, val gasLimit: ULong = 2_000_000_000UL, - val difficulty: ULong = 2UL + val difficulty: ULong = 2UL, ) { companion object { val localDev = BlockHeaderStaticFields( - coinbase = "0x6d976c9b8ceee705d4fe8699b44e5eb58242f484".decodeHex() + coinbase = "0x6d976c9b8ceee705d4fe8699b44e5eb58242f484".decodeHex(), ) } @@ -69,11 +69,11 @@ class BlobDecompressorToDomainV1( val staticFields: BlockHeaderStaticFields, val vertx: Vertx, val decoder: BinaryDecoder = BesuRlpBlobDecoder, - val logger: Logger = LogManager.getLogger(BlobDecompressorToDomainV1::class.java) + val logger: Logger = LogManager.getLogger(BlobDecompressorToDomainV1::class.java), ) : BlobDecompressorAndDeserializer { override fun decompress( startBlockNumber: ULong, - blobs: List + blobs: List, ): SafeFuture> { var blockNumber = startBlockNumber val startTime = Clock.System.now() @@ -89,7 +89,7 @@ class BlobDecompressorToDomainV1( coinbase = staticFields.coinbase, blockTimestamp = Instant.fromEpochSeconds(block.header.timestamp), gasLimit = this.staticFields.gasLimit, - difficulty = this.staticFields.difficulty + difficulty = this.staticFields.difficulty, ) val transactions = block.body.transactions.map { transaction -> TransactionFromL1RecoveredData( @@ -106,14 +106,14 @@ class BlobDecompressorToDomainV1( accessList = transaction.accessList.getOrNull()?.map { accessTuple -> TransactionFromL1RecoveredData.AccessTuple( address = accessTuple.address.toArray(), - storageKeys = accessTuple.storageKeys.map { it.toArray() } + storageKeys = accessTuple.storageKeys.map { it.toArray() }, ) - } + }, ) } BlockFromL1RecoveredData( header = header, - transactions = transactions + transactions = transactions, ) } }.thenPeek { @@ -122,7 +122,7 @@ class BlobDecompressorToDomainV1( "blobs decompressed and serialized: duration={} blobsCount={} blocks={}", endTime - startTime, blobs.size, - CommonDomainFunctions.blockIntervalString(startBlockNumber, blockNumber - 1UL) + CommonDomainFunctions.blockIntervalString(startBlockNumber, blockNumber - 1UL), ) } } @@ -130,7 +130,7 @@ class BlobDecompressorToDomainV1( private fun decodeBlocksAsync(blocksRLP: ByteArray): SafeFuture> { return vertx.executeBlocking( Callable { RLP.decodeList(blocksRLP).map(decoder::decode) }, - false + false, ) .onFailure(logger::error) .toSafeFuture() diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlockImporter.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlockImporter.kt index 6bb0a6f7..3c7bc56e 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlockImporter.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/BlockImporter.kt @@ -10,7 +10,7 @@ import kotlin.time.Duration.Companion.seconds data class ImportResult( val blockNumber: ULong, - val zkStateRootHash: ByteArray + val zkStateRootHash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -39,7 +39,7 @@ class BlockImporterAndStateVerifierV1( private val vertx: Vertx, private val elClient: ExecutionLayerClient, private val stateManagerClient: StateManagerClientV1, - private val stateManagerImportTimeoutPerBlock: Duration + private val stateManagerImportTimeoutPerBlock: Duration, ) : BlockImporterAndStateVerifier { override fun importBlocks(blocks: List): SafeFuture { val sortedBlocks = blocks.sortedBy { it.header.blockNumber } @@ -49,20 +49,20 @@ class BlockImporterAndStateVerifierV1( .thenCompose { getBlockStateRootHash( blockNumber = lastBlockNumber, - timeout = stateManagerImportTimeoutPerBlock.times(blocks.size) + timeout = stateManagerImportTimeoutPerBlock.times(blocks.size), ) } .thenApply { stateRootHash -> ImportResult( blockNumber = lastBlockNumber, - zkStateRootHash = stateRootHash + zkStateRootHash = stateRootHash, ) } } private fun getBlockStateRootHash( blockNumber: ULong, - timeout: Duration + timeout: Duration, ): SafeFuture { return AsyncRetryer .retry( @@ -70,7 +70,7 @@ class BlockImporterAndStateVerifierV1( backoffDelay = 1.seconds, timeout = timeout, stopRetriesPredicate = { headBlockNumber -> headBlockNumber >= blockNumber }, - action = { stateManagerClient.rollupGetHeadBlockNumber() } + action = { stateManagerClient.rollupGetHeadBlockNumber() }, ) .thenCompose { stateManagerClient.rollupGetStateMerkleProof(BlockInterval(blockNumber, blockNumber)) diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClient.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClient.kt index 3af606cf..d314ebc7 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClient.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClient.kt @@ -12,7 +12,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class DataSubmittedV3( val parentShnarf: ByteArray, val shnarf: ByteArray, - val finalStateRootHash: ByteArray + val finalStateRootHash: ByteArray, ) { companion object { val topic = "0x55f4c645c36aa5cd3f443d6be44d7a7a5df9d2100d7139dfc69d4289ee072319" @@ -22,9 +22,9 @@ data class DataSubmittedV3( event = DataSubmittedV3( parentShnarf = ethLog.data.sliceOf32(0), shnarf = ethLog.topics[1], - finalStateRootHash = ethLog.data.sliceOf32(1) + finalStateRootHash = ethLog.data.sliceOf32(1), ), - log = ethLog + log = ethLog, ) } } @@ -62,7 +62,7 @@ data class DataFinalizedV3( override val endBlockNumber: ULong, val shnarf: ByteArray, val parentStateRootHash: ByteArray, - val finalStateRootHash: ByteArray + val finalStateRootHash: ByteArray, ) : BlockInterval { companion object { val topic = "0xa0262dc79e4ccb71ceac8574ae906311ae338aa4a2044fd4ec4b99fad5ab60cb" @@ -81,9 +81,9 @@ data class DataFinalizedV3( endBlockNumber = ethLog.topics[2].toULongFromLast8Bytes(), shnarf = ethLog.topics[3], parentStateRootHash = dataBytes.sliceOf32(sliceNumber = 0), - finalStateRootHash = dataBytes.sliceOf32(sliceNumber = 1) + finalStateRootHash = dataBytes.sliceOf32(sliceNumber = 1), ), - log = ethLog + log = ethLog, ) } } @@ -124,17 +124,17 @@ data class DataFinalizedV3( data class FinalizationAndDataEventsV3( val dataSubmittedEvents: List>, - val dataFinalizedEvent: EthLogEvent + val dataFinalizedEvent: EthLogEvent, ) interface LineaRollupSubmissionEventsClient { fun findFinalizationAndDataSubmissionV3Events( fromL1BlockNumber: BlockParameter, - finalizationStartBlockNumber: ULong + finalizationStartBlockNumber: ULong, ): SafeFuture fun findFinalizationAndDataSubmissionV3EventsContainingL2BlockNumber( fromL1BlockNumber: BlockParameter, - l2BlockNumber: ULong + l2BlockNumber: ULong, ): SafeFuture } diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClientImpl.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClientImpl.kt index 1684deab..01d106f0 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClientImpl.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LineaSubmissionEventsClientImpl.kt @@ -13,7 +13,7 @@ class LineaSubmissionEventsClientImpl( private val logsSearcher: EthLogsSearcher, private val smartContractAddress: String, private val l1LatestSearchBlock: BlockParameter = BlockParameter.Tag.FINALIZED, - private val logsBlockChunkSize: Int + private val logsBlockChunkSize: Int, ) : LineaRollupSubmissionEventsClient { init { require(logsBlockChunkSize > 0) { "logsBlockChunkSize=$logsBlockChunkSize must be greater than 0" } @@ -21,7 +21,7 @@ class LineaSubmissionEventsClientImpl( private fun findDataFinalizedEventContainingBlock( fromBlock: BlockParameter, - l2BlockNumber: ULong + l2BlockNumber: ULong, ): SafeFuture?> { return logsSearcher.findLog( fromBlock = fromBlock, @@ -36,18 +36,18 @@ class LineaSubmissionEventsClientImpl( l2BlockNumber > event.endBlockNumber -> SearchDirection.FORWARD else -> null } - } + }, ).thenApply { it?.let { DataFinalizedV3.fromEthLog(it) } } } override fun findFinalizationAndDataSubmissionV3Events( fromL1BlockNumber: BlockParameter, - finalizationStartBlockNumber: ULong + finalizationStartBlockNumber: ULong, ): SafeFuture { return findDataFinalizedV3Event( fromL1BlockNumber = fromL1BlockNumber, toL1BlockNumber = l1LatestSearchBlock, - startBlockNumber = finalizationStartBlockNumber + startBlockNumber = finalizationStartBlockNumber, ) .thenCompose { finalizationEvent -> finalizationEvent @@ -63,7 +63,7 @@ class LineaSubmissionEventsClientImpl( override fun findFinalizationAndDataSubmissionV3EventsContainingL2BlockNumber( fromL1BlockNumber: BlockParameter, - l2BlockNumber: ULong + l2BlockNumber: ULong, ): SafeFuture { return findDataFinalizedEventContainingBlock(fromL1BlockNumber, l2BlockNumber) .thenCompose { finalizationEvent -> @@ -82,7 +82,7 @@ class LineaSubmissionEventsClientImpl( fromL1BlockNumber: BlockParameter, toL1BlockNumber: BlockParameter, startBlockNumber: ULong? = null, - endBlockNumber: ULong? = null + endBlockNumber: ULong? = null, ): SafeFuture?> { assert(startBlockNumber != null || endBlockNumber != null) { "Either startBlockNumber or endBlockNumber must be provided" @@ -104,8 +104,8 @@ class LineaSubmissionEventsClientImpl( topics = listOf( DataFinalizedV3.topic, startBlockNumber?.toHexStringUInt256(), - endBlockNumber?.toHexStringUInt256() - ) + endBlockNumber?.toHexStringUInt256(), + ), ).thenCompose { rawLogs -> val finalizedEvents = rawLogs.map(DataFinalizedV3::fromEthLog) @@ -122,7 +122,7 @@ class LineaSubmissionEventsClientImpl( } private fun findAggregationDataSubmittedV3Events( - finalizationEvent: EthLogEvent + finalizationEvent: EthLogEvent, ): SafeFuture>> { val dataEvents = mutableListOf>() val futureResult = SafeFuture>>() @@ -140,7 +140,7 @@ class LineaSubmissionEventsClientImpl( findDataSubmittedV3EventByShnarf( fromL1BlockParameter = BlockParameter.Tag.EARLIEST, tol1BlockParameter = dataSubmission.log.blockNumber.toLong().toBlockParameter(), - shnarf = dataSubmission.event.parentShnarf + shnarf = dataSubmission.event.parentShnarf, ).thenPeek(::fetchParentDataSubmission) } } @@ -148,7 +148,7 @@ class LineaSubmissionEventsClientImpl( getDataSubmittedV3EventByShnarf( fromL1BlockParameter = BlockParameter.Tag.EARLIEST, tol1BlockParameter = finalizationEvent.log.blockNumber.toLong().toBlockParameter(), - shnarf = finalizationEvent.event.shnarf + shnarf = finalizationEvent.event.shnarf, ).thenPeek(::fetchParentDataSubmission) return futureResult @@ -157,7 +157,7 @@ class LineaSubmissionEventsClientImpl( private fun getDataSubmittedV3EventByShnarf( fromL1BlockParameter: BlockParameter, tol1BlockParameter: BlockParameter, - shnarf: ByteArray + shnarf: ByteArray, ): SafeFuture> { return findDataSubmittedV3EventByShnarf(fromL1BlockParameter, tol1BlockParameter, shnarf) .thenApply { event -> @@ -168,7 +168,7 @@ class LineaSubmissionEventsClientImpl( private fun findDataSubmittedV3EventByShnarf( fromL1BlockParameter: BlockParameter, tol1BlockParameter: BlockParameter, - shnarf: ByteArray + shnarf: ByteArray, ): SafeFuture?> { return logsSearcher .getLogs( @@ -177,8 +177,8 @@ class LineaSubmissionEventsClientImpl( address = smartContractAddress, topics = listOf( DataSubmittedV3.topic, - shnarf.encodeHex() - ) + shnarf.encodeHex(), + ), ) .thenApply { rawLogs -> val events = rawLogs.map(DataSubmittedV3::fromEthLog) diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LookBackBlockHashesFetcher.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LookBackBlockHashesFetcher.kt index 284ef8fb..c5e27b13 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LookBackBlockHashesFetcher.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/LookBackBlockHashesFetcher.kt @@ -12,28 +12,28 @@ import kotlin.time.Duration.Companion.seconds class LookBackBlockHashesFetcher( private val vertx: Vertx, private val elClient: ExecutionLayerClient, - private val submissionsFetcher: SubmissionsFetchingTask + private val submissionsFetcher: SubmissionsFetchingTask, ) { fun getLookBackHashes( - status: StateRecoveryStatus + status: StateRecoveryStatus, ): SafeFuture> { val intervals = lookbackFetchingIntervals( headBlockNumber = status.headBlockNumber, recoveryStartBlockNumber = status.stateRecoverStartBlockNumber, - lookbackWindow = 256UL + lookbackWindow = 256UL, ) return SafeFuture.collectAll( listOf( intervals.elInterval?.let(::getLookBackHashesFromLocalEl) ?: SafeFuture.completedFuture(emptyMap()), - intervals.l1Interval?.let(::getLookBackHashesFromL1) ?: SafeFuture.completedFuture(emptyMap()) - ).stream() + intervals.l1Interval?.let(::getLookBackHashesFromL1) ?: SafeFuture.completedFuture(emptyMap()), + ).stream(), ) .thenApply { (blockHashesFromEl, blockHashesFromL1) -> blockHashesFromEl + blockHashesFromL1 } } fun getLookBackHashesFromLocalEl( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture> { return SafeFuture .collectAll(blockInterval.blocksRange.map { elClient.getBlockNumberAndHash(it.toBlockParameter()) }.stream()) @@ -43,7 +43,7 @@ class LookBackBlockHashesFetcher( } fun getLookBackHashesFromL1( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture> { return AsyncRetryer.retry( vertx, @@ -51,7 +51,7 @@ class LookBackBlockHashesFetcher( stopRetriesPredicate = { submissions -> submissions.isNotEmpty() && submissions.last().submissionEvents.dataFinalizedEvent.event.endBlockNumber >= blockInterval.endBlockNumber - } + }, ) { // get the data without removing it from the queue // it must still be in the queue until is imported to the EL @@ -75,7 +75,7 @@ class LookBackBlockHashesFetcher( fun shallIncreaseQueueLimit( availableSubmissions: List>, - blockInterval: BlockInterval + blockInterval: BlockInterval, ): Boolean { if (availableSubmissions.isEmpty()) { return false diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StartingBlockCalculator.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StartingBlockCalculator.kt index 68af9cf9..772f078e 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StartingBlockCalculator.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StartingBlockCalculator.kt @@ -6,7 +6,7 @@ import linea.kotlin.minusCoercingUnderflow fun startBlockToFetchFromL1( headBlockNumber: ULong, recoveryStartBlockNumber: ULong?, - lookbackWindow: ULong + lookbackWindow: ULong, ): ULong { if (recoveryStartBlockNumber == null) { return headBlockNumber + 1UL @@ -19,24 +19,24 @@ fun startBlockToFetchFromL1( data class FetchingIntervals( val elInterval: BlockInterval?, - val l1Interval: BlockInterval? + val l1Interval: BlockInterval?, ) fun lookbackFetchingIntervals( headBlockNumber: ULong, recoveryStartBlockNumber: ULong?, - lookbackWindow: ULong + lookbackWindow: ULong, ): FetchingIntervals { if (recoveryStartBlockNumber == null || recoveryStartBlockNumber > headBlockNumber) { return FetchingIntervals( l1Interval = null, - elInterval = BlockInterval(headBlockNumber.minusCoercingUnderflow(lookbackWindow - 1UL), headBlockNumber) + elInterval = BlockInterval(headBlockNumber.minusCoercingUnderflow(lookbackWindow - 1UL), headBlockNumber), ) } if (headBlockNumber - lookbackWindow > recoveryStartBlockNumber) { return FetchingIntervals( l1Interval = BlockInterval(headBlockNumber.minusCoercingUnderflow(lookbackWindow - 1UL), headBlockNumber), - elInterval = null + elInterval = null, ) } @@ -44,7 +44,7 @@ fun lookbackFetchingIntervals( l1Interval = BlockInterval(recoveryStartBlockNumber, headBlockNumber), elInterval = BlockInterval( headBlockNumber.minusCoercingUnderflow(lookbackWindow - 1UL), - recoveryStartBlockNumber - 1UL - ) + recoveryStartBlockNumber - 1UL, + ), ) } diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateRecoveryApp.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateRecoveryApp.kt index 50ec5c30..ed941e60 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateRecoveryApp.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateRecoveryApp.kt @@ -28,7 +28,7 @@ class StateRecoveryApp( private val transactionDetailsClient: TransactionDetailsClient, private val blockHeaderStaticFields: BlockHeaderStaticFields, // configs - private val config: Config + private val config: Config, ) : LongRunningService { data class Config( val smartContractAddress: String, @@ -43,7 +43,7 @@ class StateRecoveryApp( * this is meant for testing purposes, not production */ val overridingRecoveryStartBlockNumber: ULong? = null, - val debugForceSyncStopBlockNumber: ULong? = null + val debugForceSyncStopBlockNumber: ULong? = null, ) { companion object { val lineaMainnet = Config( @@ -53,7 +53,7 @@ class StateRecoveryApp( l1LatestSearchBlock = BlockParameter.Tag.FINALIZED, l1PollingInterval = 12.seconds, l1getLogsChunkSize = 10_000u, - executionClientPollingInterval = 2.seconds + executionClientPollingInterval = 2.seconds, ) val lineaSepolia = Config( smartContractAddress = "0xb218f8a4bc926cf1ca7b3423c154a0d627bdb7e5", @@ -61,7 +61,7 @@ class StateRecoveryApp( l1LatestSearchBlock = BlockParameter.Tag.FINALIZED, l1PollingInterval = 12.seconds, l1getLogsChunkSize = 10_000u, - executionClientPollingInterval = 2.seconds + executionClientPollingInterval = 2.seconds, ) } } @@ -76,19 +76,19 @@ class StateRecoveryApp( logsSearcher = ethLogsSearcher, smartContractAddress = config.smartContractAddress, l1LatestSearchBlock = config.l1LatestSearchBlock, - logsBlockChunkSize = config.l1getLogsChunkSize.toInt() + logsBlockChunkSize = config.l1getLogsChunkSize.toInt(), ) private val log = LogManager.getLogger(this::class.java) private val blockImporterAndStateVerifier = BlockImporterAndStateVerifierV1( vertx = vertx, elClient = elClient, stateManagerClient = stateManagerClient, - stateManagerImportTimeoutPerBlock = 2.seconds + stateManagerImportTimeoutPerBlock = 2.seconds, ) private val blobDecompressor: BlobDecompressorAndDeserializer = BlobDecompressorToDomainV1( decompressor = GoNativeBlobDecompressorFactory.getInstance(config.blobDecompressorVersion), staticFields = blockHeaderStaticFields, - vertx = vertx + vertx = vertx, ) private val stateSynchronizerService = StateSynchronizerService( vertx = vertx, @@ -100,7 +100,7 @@ class StateRecoveryApp( blobDecompressor = blobDecompressor, blockImporterAndStateVerifier = blockImporterAndStateVerifier, pollingInterval = config.l1PollingInterval, - debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber, ) val stateRootMismatchFound: Boolean get() = stateSynchronizerService.stateRootMismatchFound @@ -119,7 +119,7 @@ class StateRecoveryApp( updateLabel, newStatus.headBlockNumber, statusBeforeUpdate.stateRecoverStartBlockNumber, - newStatus.stateRecoverStartBlockNumber + newStatus.stateRecoverStartBlockNumber, ) } } @@ -138,7 +138,7 @@ class StateRecoveryApp( log.info( "starting recovery mode already enabled: stateRecoverStartBlockNumber={} headBlockNumber={}", status.stateRecoverStartBlockNumber, - status.headBlockNumber + status.headBlockNumber, ) SafeFuture.completedFuture(Unit) } else { @@ -153,7 +153,7 @@ class StateRecoveryApp( "L1 lastFinalizedBlockNumber={}", stateRecoverStartBlockNumber, status.headBlockNumber, - lastFinalizedBlockNumber + lastFinalizedBlockNumber, ) elClient.lineaEnableStateRecovery(stateRecoverStartBlockNumber) }.thenApply { } @@ -175,17 +175,17 @@ class StateRecoveryApp( log.info( "node reached recovery target block: stateRecoverStartBlockNumber={} headBlockNumber={}", recoveryStatus.stateRecoverStartBlockNumber, - recoveryStatus.headBlockNumber + recoveryStatus.headBlockNumber, ) } else { log.info( "waiting for node to sync until stateRecoverStartBlockNumber={} - 1, headBlockNumber={}", recoveryStatus.stateRecoverStartBlockNumber, - recoveryStatus.headBlockNumber + recoveryStatus.headBlockNumber, ) } hasReachedTargetBlock - } + }, ) { elClient.lineaGetStateRecoveryStatus() } diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateSynchronizerService.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateSynchronizerService.kt index 1bd896ee..6add6aa0 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateSynchronizerService.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/StateSynchronizerService.kt @@ -22,11 +22,11 @@ class StateSynchronizerService( private val blockImporterAndStateVerifier: BlockImporterAndStateVerifier, private val pollingInterval: Duration, private val debugForceSyncStopBlockNumber: ULong?, - private val log: Logger = LogManager.getLogger(StateSynchronizerService::class.java) + private val log: Logger = LogManager.getLogger(StateSynchronizerService::class.java), ) : PeriodicPollingService( vertx = vertx, log = log, - pollingIntervalMs = pollingInterval.inWholeMilliseconds + pollingIntervalMs = pollingInterval.inWholeMilliseconds, ) { @get:Synchronized @set:Synchronized @@ -48,7 +48,7 @@ class StateSynchronizerService( val l2StartBlockNumberToFetchInclusive = startBlockToFetchFromL1( headBlockNumber = status.headBlockNumber, recoveryStartBlockNumber = status.stateRecoverStartBlockNumber, - lookbackWindow = 256UL + lookbackWindow = 256UL, ) this.blobsFetcherTask = SubmissionsFetchingTask( @@ -63,7 +63,7 @@ class StateSynchronizerService( submissionEventsQueueLimit = 10, compressedBlobsQueueLimit = 10, targetDecompressedBlobsQueueLimit = 10, - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, ) blobsFetcherTask.start() } @@ -91,7 +91,7 @@ class StateSynchronizerService( val loobackHasheFetcher = LookBackBlockHashesFetcher( vertx = vertx, elClient = elClient, - submissionsFetcher = blobsFetcherTask + submissionsFetcher = blobsFetcherTask, ) return this.elClient @@ -116,30 +116,30 @@ class StateSynchronizerService( if (blocksToImport.isEmpty()) { log.debug( "no blocks to import for finalization={}", - nexFinalization.submissionEvents.dataFinalizedEvent.event + nexFinalization.submissionEvents.dataFinalizedEvent.event, ) return@thenCompose SafeFuture.completedFuture(Unit) } importBlocksAndAssertStateroot( decompressedBlocksToImport = blocksToImport, - dataFinalizedV3 = nexFinalization.submissionEvents.dataFinalizedEvent.event + dataFinalizedV3 = nexFinalization.submissionEvents.dataFinalizedEvent.event, ) } .thenPeek { blobsFetcherTask.pruneQueueForElementsUpToInclusive( - nexFinalization.submissionEvents.dataFinalizedEvent.event.endBlockNumber + nexFinalization.submissionEvents.dataFinalizedEvent.event.endBlockNumber, ) } } private fun importBlocksAndAssertStateroot( decompressedBlocksToImport: List, - dataFinalizedV3: DataFinalizedV3 + dataFinalizedV3: DataFinalizedV3, ): SafeFuture { val blockInterval = CommonDomainFunctions.blockIntervalString( decompressedBlocksToImport.first().header.blockNumber, - decompressedBlocksToImport.last().header.blockNumber + decompressedBlocksToImport.last().header.blockNumber, ) log.debug("importing blocks={} from finalization={}", blockInterval, dataFinalizedV3.intervalString()) return blockImporterAndStateVerifier @@ -151,7 +151,7 @@ class StateSynchronizerService( } private fun filterOutBlocksAlreadyImportedAndBeyondStopSync( - blocks: List + blocks: List, ): SafeFuture> { return elClient.getBlockNumberAndHash(blockParameter = BlockParameter.Tag.LATEST) .thenApply { headBlock -> @@ -165,14 +165,14 @@ class StateSynchronizerService( private fun assertStateMatches( importResult: ImportResult, - finalizedV3: DataFinalizedV3 + finalizedV3: DataFinalizedV3, ): SafeFuture { if (importResult.blockNumber != finalizedV3.endBlockNumber) { log.info( "cannot compare stateroot: last imported block={} finalization={} debugForceSyncStopBlockNumber={}", importResult.blockNumber, finalizedV3.intervalString(), - debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber, ) if (importResult.blockNumber == debugForceSyncStopBlockNumber) { // this means debugForceSyncStopBlockNumber was set and we stopped before reaching the target block @@ -183,7 +183,7 @@ class StateSynchronizerService( log.info( "state recovered up to finalization={} zkStateRootHash={}", finalizedV3.intervalString(), - importResult.zkStateRootHash.encodeHex() + importResult.zkStateRootHash.encodeHex(), ) } else { log.error( @@ -193,7 +193,7 @@ class StateSynchronizerService( finalizedV3.intervalString(), importResult.blockNumber, importResult.zkStateRootHash.encodeHex(), - finalizedV3.finalStateRootHash.encodeHex() + finalizedV3.finalStateRootHash.encodeHex(), ) stateRootMismatchFound = true this.stop() diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobDecompressionTask.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobDecompressionTask.kt index 8464558b..dca0184d 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobDecompressionTask.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobDecompressionTask.kt @@ -18,11 +18,11 @@ internal class BlobDecompressionTask( private val rawBlobsQueue: ConcurrentLinkedQueue>, private val decompressedBlocksQueue: ConcurrentLinkedQueue>, private val decompressedFinalizationQueueLimit: Supplier, - private val log: Logger = LogManager.getLogger(SubmissionsFetchingTask::class.java) + private val log: Logger = LogManager.getLogger(SubmissionsFetchingTask::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { override fun action(): SafeFuture<*> { return decompressAndDeserializeBlobs() @@ -38,10 +38,10 @@ internal class BlobDecompressionTask( return blobDecompressor .decompress( startBlockNumber = submissionEventsAndData.submissionEvents.dataFinalizedEvent.event.startBlockNumber, - blobs = submissionEventsAndData.data + blobs = submissionEventsAndData.data, ).thenCompose { decompressedBlocks -> decompressedBlocksQueue.add( - SubmissionEventsAndData(submissionEventsAndData.submissionEvents, decompressedBlocks) + SubmissionEventsAndData(submissionEventsAndData.submissionEvents, decompressedBlocks), ) decompressAndDeserializeBlobs() } diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobsFetchingTask.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobsFetchingTask.kt index b9b2f451..d7159dbe 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobsFetchingTask.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/BlobsFetchingTask.kt @@ -19,11 +19,11 @@ internal class BlobsFetchingTask( private val submissionEventsQueue: ConcurrentLinkedQueue, private val compressedBlobsQueue: ConcurrentLinkedQueue>, private val compressedBlobsQueueLimit: Int, - private val log: Logger = LogManager.getLogger(BlobsFetchingTask::class.java) + private val log: Logger = LogManager.getLogger(BlobsFetchingTask::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { override fun action(): SafeFuture<*> { @@ -50,13 +50,13 @@ internal class BlobsFetchingTask( } private fun fetchBlobsOfSubmissionEvents( - submissionEvents: FinalizationAndDataEventsV3 + submissionEvents: FinalizationAndDataEventsV3, ): SafeFuture> { return SafeFuture.collectAll( submissionEvents.dataSubmittedEvents .map { transactionDetailsClient.getBlobVersionedHashesByTransactionHash(it.log.transactionHash) - }.stream() + }.stream(), ) .thenCompose { blobsVersionedHashesByTransaction -> blobsFetcher.fetchBlobsByHash(blobsVersionedHashesByTransaction.flatten()) diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionEventsFetchingTask.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionEventsFetchingTask.kt index d335b342..d0bb9ccc 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionEventsFetchingTask.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionEventsFetchingTask.kt @@ -24,11 +24,11 @@ internal class SubmissionEventsFetchingTask( private val submissionEventsQueue: ConcurrentLinkedQueue, private val queueLimit: Int, private val debugForceSyncStopBlockNumber: ULong?, - private val log: Logger = LogManager.getLogger(SubmissionEventsFetchingTask::class.java) + private val log: Logger = LogManager.getLogger(SubmissionEventsFetchingTask::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = l1PollingInterval.inWholeMilliseconds, - log = log + log = log, ) { val latestFetchedFinalization: AtomicReference> = AtomicReference(null) @@ -38,7 +38,7 @@ internal class SubmissionEventsFetchingTask( ) { log.debug( "Force stop fetching submission events from L1, reached debugForceSyncStopBlockNumber={}", - debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber, ) return this.stop() } @@ -51,7 +51,7 @@ internal class SubmissionEventsFetchingTask( // Queue is full, no need to fetch more log.debug( "skipping fetching submission events from L1, internal queue is full size={}", - submissionEventsQueue.size + submissionEventsQueue.size, ) return SafeFuture.completedFuture(Unit) } @@ -74,21 +74,21 @@ internal class SubmissionEventsFetchingTask( return if (latestFetchedFinalization.get() != null) { log.trace( "fetching submission events from L1 startBlockNumber={}", - latestFetchedFinalization.get().event.endBlockNumber + 1u + latestFetchedFinalization.get().event.endBlockNumber + 1u, ) submissionEventsClient.findFinalizationAndDataSubmissionV3Events( fromL1BlockNumber = latestFetchedFinalization.get().log.blockNumber.toBlockParameter(), - finalizationStartBlockNumber = latestFetchedFinalization.get().event.endBlockNumber + 1u + finalizationStartBlockNumber = latestFetchedFinalization.get().event.endBlockNumber + 1u, ) } else { log.trace( "fetching submission events from L1 startBlockNumber={}", - l2StartBlockNumber + l2StartBlockNumber, ) submissionEventsClient .findFinalizationAndDataSubmissionV3EventsContainingL2BlockNumber( fromL1BlockNumber = l1EarliestBlockWithFinalizationThatSupportRecovery, - l2BlockNumber = l2StartBlockNumber + l2BlockNumber = l2StartBlockNumber, ) } } diff --git a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTask.kt b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTask.kt index 1595fd65..56067284 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTask.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/main/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTask.kt @@ -28,7 +28,7 @@ import kotlin.time.Duration.Companion.seconds */ data class SubmissionEventsAndData( val submissionEvents: FinalizationAndDataEventsV3, - val data: List + val data: List, ) class SubmissionsFetchingTask( @@ -44,11 +44,11 @@ class SubmissionsFetchingTask( private val compressedBlobsQueueLimit: Int, private val targetDecompressedBlobsQueueLimit: Int, private val debugForceSyncStopBlockNumber: ULong?, - private val log: Logger = LogManager.getLogger(SubmissionsFetchingTask::class.java) + private val log: Logger = LogManager.getLogger(SubmissionsFetchingTask::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = l1PollingInterval.inWholeMilliseconds, - log = log + log = log, ) { init { require(submissionEventsQueueLimit >= 1) { @@ -84,7 +84,7 @@ class SubmissionsFetchingTask( l2StartBlockNumber = l2StartBlockNumberToFetchInclusive, submissionEventsQueue = submissionEventsQueue, queueLimit = submissionEventsQueueLimit, - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, ) private val blobFetchingTask = BlobsFetchingTask( vertx = vertx, @@ -93,7 +93,7 @@ class SubmissionsFetchingTask( blobsFetcher = blobsFetcher, transactionDetailsClient = transactionDetailsClient, compressedBlobsQueue = compressedBlobsQueue, - compressedBlobsQueueLimit = compressedBlobsQueueLimit + compressedBlobsQueueLimit = compressedBlobsQueueLimit, ) private val blobDecompressionTask = BlobDecompressionTask( vertx = vertx, @@ -101,7 +101,7 @@ class SubmissionsFetchingTask( blobDecompressor = blobDecompressor, rawBlobsQueue = compressedBlobsQueue, decompressedBlocksQueue = decompressedBlocksQueue, - decompressedFinalizationQueueLimit = dynamicDecompressedBlobsQueueLimit::get + decompressedFinalizationQueueLimit = dynamicDecompressedBlobsQueueLimit::get, ) @Synchronized @@ -109,7 +109,7 @@ class SubmissionsFetchingTask( return SafeFuture.allOf( submissionEventsFetchingTask.start(), blobFetchingTask.start(), - blobDecompressionTask.start() + blobDecompressionTask.start(), ).thenCompose { super.start() } } @@ -118,7 +118,7 @@ class SubmissionsFetchingTask( return SafeFuture.allOf( submissionEventsFetchingTask.stop(), blobFetchingTask.stop(), - blobDecompressionTask.stop() + blobDecompressionTask.stop(), ).thenCompose { super.stop() } } @@ -136,7 +136,7 @@ class SubmissionsFetchingTask( @Synchronized fun pruneQueueForElementsUpToInclusive( - elHeadBlockNumber: ULong + elHeadBlockNumber: ULong, ) { decompressedBlocksQueue.removeIf { it.submissionEvents.dataFinalizedEvent.event.endBlockNumber <= elHeadBlockNumber diff --git a/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/BlobDecompressorAndDeserializerV1Test.kt b/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/BlobDecompressorAndDeserializerV1Test.kt index 9ebe09e0..58d471ab 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/BlobDecompressorAndDeserializerV1Test.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/BlobDecompressorAndDeserializerV1Test.kt @@ -29,7 +29,7 @@ class BlobDecompressorAndDeserializerV1Test { private val blockStaticFields = BlockHeaderStaticFields( coinbase = Address.ZERO.toArray(), gasLimit = 30_000_000UL, - difficulty = 0UL + difficulty = 0UL, ) private lateinit var decompressorToDomain: BlobDecompressorAndDeserializer private lateinit var vertx: Vertx @@ -39,7 +39,7 @@ class BlobDecompressorAndDeserializerV1Test { vertx = Vertx.vertx() compressor = GoBackedBlobCompressor.getInstance( compressorVersion = BlobCompressorVersion.V1_2, - dataLimit = 124 * 1024 + dataLimit = 124 * 1024, ) val decompressor = GoNativeBlobDecompressorFactory.getInstance(BlobDecompressorVersion.V1_2_0) decompressorToDomain = BlobDecompressorToDomainV1(decompressor, blockStaticFields, vertx) @@ -57,7 +57,7 @@ class BlobDecompressorAndDeserializerV1Test { } private fun assertBlockCompressionAndDecompression( - blocksRLP: List + blocksRLP: List, ) { val blocks = blocksRLP.map(RLP::decodeBlockWithMainnetFunctions) val startingBlockNumber = blocks[0].header.number.toULong() @@ -66,7 +66,7 @@ class BlobDecompressorAndDeserializerV1Test { val recoveredBlocks = decompressorToDomain.decompress( startBlockNumber = startingBlockNumber, - blobs = blobs + blobs = blobs, ).get() assertThat(recoveredBlocks[0].header.blockNumber).isEqualTo(startingBlockNumber) @@ -77,7 +77,7 @@ class BlobDecompressorAndDeserializerV1Test { private fun assertBlockData( uncompressed: BlockFromL1RecoveredData, - original: Block + original: Block, ) { try { assertThat(uncompressed.header.blockNumber).isEqualTo(original.header.number.toULong()) @@ -94,14 +94,14 @@ class BlobDecompressorAndDeserializerV1Test { "uncompressed block does not match expected original: blockNumber: ${e.message} " + "\n original =$original " + "\n uncompressed=$uncompressed ", - e + e, ) } } private fun assertTransactionData( uncompressed: TransactionFromL1RecoveredData, - original: Transaction + original: Transaction, ) { assertThat(uncompressed.type).isEqualTo(original.type.serializedType.toUByte()) assertThat(uncompressed.from).isEqualTo(original.sender.toArray()) diff --git a/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/StartingBlockCalculatorTest.kt b/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/StartingBlockCalculatorTest.kt index 151e0b58..90c784f1 100644 --- a/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/StartingBlockCalculatorTest.kt +++ b/besu-plugins/state-recovery/appcore/logic/src/test/kotlin/linea/staterecovery/StartingBlockCalculatorTest.kt @@ -13,7 +13,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 50UL, recoveryStartBlockNumber = null, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isNull() assertThat(intervals.elInterval).isEqualTo(BlockInterval(41UL, 50UL)) @@ -23,7 +23,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 5UL, recoveryStartBlockNumber = null, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isNull() assertThat(intervals.elInterval).isEqualTo(BlockInterval(0UL, 5UL)) @@ -35,7 +35,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 50UL, recoveryStartBlockNumber = 51UL, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isNull() assertThat(intervals.elInterval).isEqualTo(BlockInterval(41UL, 50UL)) @@ -47,7 +47,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 0UL, recoveryStartBlockNumber = 1UL, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isNull() assertThat(intervals.elInterval).isEqualTo(BlockInterval(0UL, 0UL)) @@ -59,7 +59,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 50UL, recoveryStartBlockNumber = 10UL, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isEqualTo(BlockInterval(41UL, 50UL)) assertThat(intervals.elInterval).isNull() @@ -71,7 +71,7 @@ class StartingBlockCalculatorTest { lookbackFetchingIntervals( headBlockNumber = 50UL, recoveryStartBlockNumber = 45UL, - lookbackWindow = 10UL + lookbackWindow = 10UL, ).also { intervals -> assertThat(intervals.l1Interval).isEqualTo(BlockInterval(45UL, 50UL)) assertThat(intervals.elInterval).isEqualTo(BlockInterval(41UL, 44UL)) @@ -86,7 +86,7 @@ class StartingBlockCalculatorTest { startBlockToFetchFromL1( headBlockNumber = 500UL, recoveryStartBlockNumber = null, - lookbackWindow = 256UL + lookbackWindow = 256UL, ).also { result -> // Then assertThat(result).isEqualTo(501UL) @@ -95,7 +95,7 @@ class StartingBlockCalculatorTest { startBlockToFetchFromL1( headBlockNumber = 200UL, recoveryStartBlockNumber = null, - lookbackWindow = 256UL + lookbackWindow = 256UL, ).also { result -> // Then assertThat(result).isEqualTo(201UL) @@ -107,7 +107,7 @@ class StartingBlockCalculatorTest { startBlockToFetchFromL1( headBlockNumber = 500UL, recoveryStartBlockNumber = 250UL, - lookbackWindow = 100UL + lookbackWindow = 100UL, ).also { result -> // Then assertThat(result).isEqualTo(400UL) @@ -119,7 +119,7 @@ class StartingBlockCalculatorTest { startBlockToFetchFromL1( headBlockNumber = 500UL, recoveryStartBlockNumber = 450UL, - lookbackWindow = 100UL + lookbackWindow = 100UL, ).also { result -> // Then assertThat(result).isEqualTo(450UL) @@ -129,7 +129,7 @@ class StartingBlockCalculatorTest { startBlockToFetchFromL1( headBlockNumber = 50UL, recoveryStartBlockNumber = 45UL, - lookbackWindow = 100UL + lookbackWindow = 100UL, ).also { result -> // Then assertThat(result).isEqualTo(45UL) diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/clients/ExecutionLayerInProcessClient.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/clients/ExecutionLayerInProcessClient.kt index e341369d..edc18be8 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/clients/ExecutionLayerInProcessClient.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/clients/ExecutionLayerInProcessClient.kt @@ -21,7 +21,7 @@ class ExecutionLayerInProcessClient( private val blockchainService: BlockchainService, private val stateRecoveryModeManager: RecoveryModeManager, private val stateRecoveryStatusPersistence: RecoveryStatusPersistence, - private val blockImporter: BlockImporter + private val blockImporter: BlockImporter, ) : ExecutionLayerClient { companion object { fun create( @@ -29,7 +29,7 @@ class ExecutionLayerInProcessClient( simulatorService: BlockSimulationService, synchronizationService: SynchronizationService, stateRecoveryModeManager: RecoveryModeManager, - stateRecoveryStatusPersistence: RecoveryStatusPersistence + stateRecoveryStatusPersistence: RecoveryStatusPersistence, ): ExecutionLayerInProcessClient { return ExecutionLayerInProcessClient( blockchainService = blockchainService, @@ -38,8 +38,8 @@ class ExecutionLayerInProcessClient( blockImporter = BlockImporter( blockchainService = blockchainService, simulatorService = simulatorService, - synchronizationService = synchronizationService - ) + synchronizationService = synchronizationService, + ), ) } } @@ -71,8 +71,8 @@ class ExecutionLayerInProcessClient( SafeFuture.completedFuture( BlockNumberAndHash( it.number.toULong(), - it.blockHash.toArray() - ) + it.blockHash.toArray(), + ), ) } ?: SafeFuture.failedFuture(IllegalArgumentException("Block not found for parameter: $blockParameter")) @@ -91,8 +91,8 @@ class ExecutionLayerInProcessClient( .completedFuture( StateRecoveryStatus( headBlockNumber = stateRecoveryModeManager.headBlockNumber, - stateRecoverStartBlockNumber = stateRecoveryModeManager.targetBlockNumber - ) + stateRecoverStartBlockNumber = stateRecoveryModeManager.targetBlockNumber, + ), ) } @@ -102,8 +102,8 @@ class ExecutionLayerInProcessClient( return SafeFuture.completedFuture( StateRecoveryStatus( headBlockNumber = stateRecoveryModeManager.headBlockNumber, - stateRecoverStartBlockNumber = stateRecoveryStatusPersistence.getRecoveryStartBlockNumber() - ) + stateRecoverStartBlockNumber = stateRecoveryStatusPersistence.getRecoveryStartBlockNumber(), + ), ) } @@ -113,7 +113,7 @@ class ExecutionLayerInProcessClient( } else { log.debug( "importing blocks from blob: blocks={}", - CommonDomainFunctions.blockIntervalString(blocks.first().header.blockNumber, blocks.last().header.blockNumber) + CommonDomainFunctions.blockIntervalString(blocks.first().header.blockNumber, blocks.last().header.blockNumber), ) } } diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/AppConfigurator.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/AppConfigurator.kt index 381b71dc..ab77042e 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/AppConfigurator.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/AppConfigurator.kt @@ -37,7 +37,7 @@ fun createAppAllInProcess( blobScanRequestRetryConfig: RetryConfig, blobscanRequestRatelimitBackoffDelay: Duration?, blockHeaderStaticFields: BlockHeaderStaticFields, - appConfig: StateRecoveryApp.Config + appConfig: StateRecoveryApp.Config, ): StateRecoveryApp { return createAppClients( vertx = vertx, @@ -49,7 +49,7 @@ fun createAppAllInProcess( l1RequestRetryConfig = l1RequestRetryConfig, blobScanEndpoint = blobScanEndpoint, blobScanRequestRetryConfig = blobScanRequestRetryConfig, - blobscanRequestRateLimitBackoffDelay = blobscanRequestRatelimitBackoffDelay + blobscanRequestRateLimitBackoffDelay = blobscanRequestRatelimitBackoffDelay, ).let { clients -> val app = StateRecoveryApp( vertx = vertx, @@ -60,7 +60,7 @@ fun createAppAllInProcess( stateManagerClient = clients.stateManagerClient, transactionDetailsClient = clients.transactionDetailsClient, blockHeaderStaticFields = blockHeaderStaticFields, - config = appConfig + config = appConfig, ) app } @@ -71,7 +71,7 @@ data class AppClients( val ethLogsSearcher: EthLogsSearcherImpl, val blobScanClient: BlobScanClient, val stateManagerClient: StateManagerClientV1, - val transactionDetailsClient: TransactionDetailsClient + val transactionDetailsClient: TransactionDetailsClient, ) fun RetryConfig.toRequestRetryConfig(): RequestRetryConfig { @@ -79,7 +79,7 @@ fun RetryConfig.toRequestRetryConfig(): RequestRetryConfig { maxRetries = this.maxRetries, timeout = this.timeout, backoffDelay = this.backoffDelay, - failuresWarningThreshold = this.failuresWarningThreshold + failuresWarningThreshold = this.failuresWarningThreshold, ) } @@ -95,14 +95,14 @@ fun createAppClients( stateManagerClientEndpoint: URI, blobscanRequestRateLimitBackoffDelay: Duration? = null, stateManagerRequestRetry: RetryConfig = RetryConfig(backoffDelay = 1.seconds), - zkStateManagerVersion: String = "2.3.0" + zkStateManagerVersion: String = "2.3.0", ): AppClients { val lineaContractClient = Web3JLineaRollupSmartContractClientReadOnly( contractAddress = smartContractAddress, web3j = createWeb3jHttpClient( rpcUrl = l1RpcEndpoint.toString(), - log = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.smart-contract") - ) + log = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.smart-contract"), + ), ) val ethLogsSearcher = run { val log = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.logs-searcher") @@ -110,15 +110,15 @@ fun createAppClients( vertx = vertx, rpcUrl = l1RpcEndpoint.toString(), requestRetryConfig = l1RequestRetryConfig, - log = log + log = log, ) EthLogsSearcherImpl( vertx = vertx, ethApiClient = web3jEthApiClient, config = EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = l1SuccessBackoffDelay + loopSuccessBackoffDelay = l1SuccessBackoffDelay, ), - log = log + log = log, ) } val blobScanClient = BlobScanClient.create( @@ -126,7 +126,7 @@ fun createAppClients( endpoint = blobScanEndpoint, requestRetryConfig = blobScanRequestRetryConfig, logger = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.blob-scan"), - rateLimitBackoffDelay = blobscanRequestRateLimitBackoffDelay + rateLimitBackoffDelay = blobscanRequestRateLimitBackoffDelay, ) val jsonRpcClientFactory = VertxHttpJsonRpcClientFactory(vertx, MicrometerMetricsFacade(meterRegistry)) val stateManagerClient: StateManagerClientV1 = StateManagerV1JsonRpcClient.create( @@ -135,19 +135,19 @@ fun createAppClients( maxInflightRequestsPerClient = 10u, requestRetry = stateManagerRequestRetry.toRequestRetryConfig(), zkStateManagerVersion = zkStateManagerVersion, - logger = LogManager.getLogger("linea.plugin.staterecovery.clients.state-manager") + logger = LogManager.getLogger("linea.plugin.staterecovery.clients.state-manager"), ) val transactionDetailsClient: TransactionDetailsClient = VertxTransactionDetailsClient.create( jsonRpcClientFactory = jsonRpcClientFactory, endpoint = l1RpcEndpoint, retryConfig = l1RequestRetryConfig.toRequestRetryConfig(), - logger = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.transaction-details") + logger = LogManager.getLogger("linea.plugin.staterecovery.clients.l1.transaction-details"), ) return AppClients( lineaContractClient = lineaContractClient, ethLogsSearcher = ethLogsSearcher, blobScanClient = blobScanClient, stateManagerClient = stateManagerClient, - transactionDetailsClient = transactionDetailsClient + transactionDetailsClient = transactionDetailsClient, ) } diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockContextData.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockContextData.kt index 2e873080..86f38021 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockContextData.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockContextData.kt @@ -6,7 +6,7 @@ import org.hyperledger.besu.plugin.data.BlockHeader data class BlockContextData( private val blockHeader: BlockHeader, - private val blockBody: BlockBody + private val blockBody: BlockBody, ) : BlockContext { override fun getBlockHeader(): BlockHeader = blockHeader override fun getBlockBody(): BlockBody = blockBody diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupport.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupport.kt index fa1c8bd1..ad2bb616 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupport.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupport.kt @@ -13,7 +13,7 @@ import java.util.concurrent.ConcurrentHashMap class BlockHashLookupWithRecoverySupport( val lookbackWindow: ULong, - private val log: Logger = LogManager.getLogger(BlockHashLookupWithRecoverySupport::class.java) + private val log: Logger = LogManager.getLogger(BlockHashLookupWithRecoverySupport::class.java), ) : BlockHashLookup { private val lookbackHashesMap = ConcurrentHashMap() diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockImporter.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockImporter.kt index 5ff0dc3f..5e4537db 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockImporter.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/BlockImporter.kt @@ -22,8 +22,8 @@ class BlockImporter( private val simulatorService: BlockSimulationService, private val synchronizationService: SynchronizationService, private val blockHashLookup: BlockHashLookupWithRecoverySupport = BlockHashLookupWithRecoverySupport( - lookbackWindow = 256UL - ) + lookbackWindow = 256UL, + ), ) { private val log = LogManager.getLogger(BlockImporter::class.java) private val chainId = blockchainService.chainId.orElseThrow().toULong() @@ -40,16 +40,16 @@ class BlockImporter( } private fun executeBlockWithTransactionsWithoutSignature( - block: BlockFromL1RecoveredData + block: BlockFromL1RecoveredData, ): PluginBlockSimulationResult { log.trace( "simulating import block={} blockHash={}", block.header.blockNumber, - block.header.blockHash.encodeHex() + block.header.blockHash.encodeHex(), ) val transactions = TransactionMapper.mapToBesu( block.transactions, - chainId + chainId, ) val parentBlockNumber = block.header.blockNumber.toLong() - 1 @@ -58,13 +58,13 @@ class BlockImporter( parentBlockNumber, transactions, createOverrides(block, blockHashLookup::getHash), - StateOverrideMap() + StateOverrideMap(), ) log.trace( " import simulation result: block={} blockHeader={}", executedBlockResult.blockHeader.number, - executedBlockResult.blockHeader + executedBlockResult.blockHeader, ) return executedBlockResult } @@ -73,7 +73,7 @@ class BlockImporter( log.trace( "calling simulateAndPersistWorldState block={} blockHeader={}", context.blockHeader.number, - context.blockHeader + context.blockHeader, ) val parentBlockNumber = context.blockHeader.number - 1 val importedBlockResult = @@ -81,12 +81,12 @@ class BlockImporter( parentBlockNumber, context.blockBody.transactions, createOverrides(context.blockHeader, blockHashLookup::getHash), - StateOverrideMap() + StateOverrideMap(), ) log.trace( "simulateAndPersistWorldState result: block={} blockHeader={}", context.blockHeader.number, - importedBlockResult.blockHeader + importedBlockResult.blockHeader, ) storeAndSetHead(importedBlockResult) return importedBlockResult @@ -95,12 +95,12 @@ class BlockImporter( private fun storeAndSetHead(block: PluginBlockSimulationResult) { log.debug( "storeAndSetHead result: blockHeader={}", - block.blockHeader + block.blockHeader, ) blockchainService.storeBlock( block.blockHeader, block.blockBody, - block.receipts + block.receipts, ) synchronizationService.setHeadUnsafe(block.blockHeader, block.blockBody) } @@ -108,7 +108,7 @@ class BlockImporter( companion object { fun createOverrides( blockFromBlob: BlockFromL1RecoveredData, - blockHashLookup: (Long) -> Hash + blockHashLookup: (Long) -> Hash, ): BlockOverrides { return BlockOverrides.builder() .blockHash(Hash.wrap(Bytes32.wrap(blockFromBlob.header.blockHash))) @@ -124,7 +124,7 @@ class BlockImporter( fun createOverrides( blockHeader: BlockHeader, - blockHashLookup: (Long) -> Hash + blockHashLookup: (Long) -> Hash, ): BlockOverrides { return BlockOverrides.builder() .feeRecipient(blockHeader.coinbase) diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/LineaStateRecoveryPlugin.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/LineaStateRecoveryPlugin.kt index c4e61207..cf655f69 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/LineaStateRecoveryPlugin.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/LineaStateRecoveryPlugin.kt @@ -36,7 +36,7 @@ open class LineaStateRecoveryPlugin : BesuPlugin { warningExceptionTime = 5.minutes, jvmMetricsEnabled = false, prometheusMetricsEnabled = false, - preferNativeTransport = false + preferNativeTransport = false, ) private val cliOptions = PluginCliOptions() private lateinit var serviceManager: ServiceManager @@ -59,18 +59,18 @@ open class LineaStateRecoveryPlugin : BesuPlugin { val blockHeaderStaticFields = BlockHeaderStaticFields( coinbase = config.lineaSequencerBeneficiaryAddress.toArray(), gasLimit = config.lineaBlockGasLimit, - difficulty = config.lineaBlockDifficulty + difficulty = config.lineaBlockDifficulty, ) this.recoveryStatusPersistence = FileBasedRecoveryStatusPersistence( serviceManager.getServiceOrThrow(BesuConfiguration::class.java) .dataPath - .resolve("plugin-staterecovery-status.json") + .resolve("plugin-staterecovery-status.json"), ) log.info( "starting: config={} blockHeaderStaticFields={} previousRecoveryStartBlockNumber={}", config, blockHeaderStaticFields, - this.recoveryStatusPersistence.getRecoveryStartBlockNumber() + this.recoveryStatusPersistence.getRecoveryStartBlockNumber(), ) val synchronizationService = serviceManager.getServiceOrThrow(SynchronizationService::class.java) @@ -80,7 +80,7 @@ open class LineaStateRecoveryPlugin : BesuPlugin { recoveryStatePersistence = this.recoveryStatusPersistence, synchronizationService = synchronizationService, headBlockNumber = blockchainService.chainHeadHeader.number.toULong(), - debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber, ) val simulatorService = serviceManager.getServiceOrThrow(BlockSimulationService::class.java) val executionLayerClient = ExecutionLayerInProcessClient.create( @@ -88,7 +88,7 @@ open class LineaStateRecoveryPlugin : BesuPlugin { stateRecoveryModeManager = this.recoveryModeManager, stateRecoveryStatusPersistence = this.recoveryStatusPersistence, simulatorService = simulatorService, - synchronizationService = synchronizationService + synchronizationService = synchronizationService, ) this.stateRecoverApp = run { @@ -112,8 +112,8 @@ open class LineaStateRecoveryPlugin : BesuPlugin { l1LatestSearchBlock = config.l1HighestSearchBlock, l1PollingInterval = config.l1PollingInterval, overridingRecoveryStartBlockNumber = config.overridingRecoveryStartBlockNumber, - debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber - ) + debugForceSyncStopBlockNumber = config.debugForceSyncStopBlockNumber, + ), ) } // add recoverty mode manager as listener to block added events @@ -129,7 +129,7 @@ open class LineaStateRecoveryPlugin : BesuPlugin { this.recoveryModeManager.enableRecoveryModeIfNecessary() log.info( "started: recoveryStartBlockNumber={}", - this.recoveryStatusPersistence.getRecoveryStartBlockNumber() + this.recoveryStatusPersistence.getRecoveryStartBlockNumber(), ) this.stateRecoverApp.start().get() } diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/PluginOptions.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/PluginOptions.kt index 21502443..2acc9a6a 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/PluginOptions.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/PluginOptions.kt @@ -25,7 +25,7 @@ data class PluginConfig( val blobscanRequestRatelimitBackoffDelay: kotlin.time.Duration?, val shomeiEndpoint: URI, val overridingRecoveryStartBlockNumber: ULong? = null, - val debugForceSyncStopBlockNumber: ULong? = null + val debugForceSyncStopBlockNumber: ULong? = null, ) { init { require(l1PollingInterval >= 1.milliseconds) { "Polling interval=$l1PollingInterval must be greater than 1ms." } @@ -43,7 +43,7 @@ class PluginCliOptions { description = ["Linea sequencer beneficiary address"], required = true, converter = [AddressConverter::class], - defaultValue = "\${env:LINEA_SEQUENCER_BENEFICIARY_ADDRESS}" + defaultValue = "\${env:LINEA_SEQUENCER_BENEFICIARY_ADDRESS}", ) lateinit var lineaSequencerBeneficiaryAddress: Address @@ -51,7 +51,7 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-linea-block-gas-limit"], description = ["Linea Block gas limit. Default 2B (2_000_000_000)"], required = false, - defaultValue = "\${env:LINEA_BLOCK_GAS_LIMIT}" + defaultValue = "\${env:LINEA_BLOCK_GAS_LIMIT}", ) var lineaBlockGasLimit: Long = 2_000_000_000L @@ -59,7 +59,7 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-linea-block-difficulty"], description = ["Linea Block difficulty. Default 2"], required = false, - defaultValue = "\${env:LINEA_BLOCK_DIFFICULTY}" + defaultValue = "\${env:LINEA_BLOCK_DIFFICULTY}", ) var lineaBlockDifficulty: Long = 2 @@ -68,14 +68,14 @@ class PluginCliOptions { description = ["L1 smart contract address"], required = true, converter = [AddressConverter::class], - defaultValue = "\${env:L1_ROLLUP_CONTRACT_ADDRESS}" + defaultValue = "\${env:L1_ROLLUP_CONTRACT_ADDRESS}", ) lateinit var l1SmartContractAddress: Address @CommandLine.Option( names = ["--$cliOptionsPrefix-l1-endpoint"], description = ["L1 RPC endpoint"], - required = true + required = true, ) lateinit var l1RpcEndpoint: URI @@ -83,7 +83,7 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-polling-interval"], defaultValue = "PT12S", description = ["L1 polling interval for new finalized blobs"], - required = false + required = false, ) var l1PollingInterval: java.time.Duration = java.time.Duration.ofSeconds(12) @@ -91,7 +91,7 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-get-logs-chunk-size"], defaultValue = "10000", description = ["Chuck size (fromBlock..toBlock) for eth_getLogs initial search loop"], - required = false + required = false, ) var l1GetLogsChunkSize: Int = 10_000 @@ -100,10 +100,10 @@ class PluginCliOptions { defaultValue = "EARLIEST", description = [ "Earliest L1 Block to search for new finalizations on startup.", - "Optional, if defined it shall match L1 block with 1st finalization that supports recovery." + "Optional, if defined it shall match L1 block with 1st finalization that supports recovery.", ], converter = [BlockParameterConverter::class], - required = false + required = false, ) var l1EarliestSearchBlock: BlockParameter = BlockParameter.Tag.EARLIEST @@ -112,10 +112,10 @@ class PluginCliOptions { defaultValue = "FINALIZED", description = [ "Highest L1 Block to search for new finalizations.", - "Finalized is highly recommended, otherwise if state is reverted it may require a full resync. " + "Finalized is highly recommended, otherwise if state is reverted it may require a full resync. ", ], converter = [BlockParameterConverter::class], - required = false + required = false, ) var l1HighestSearchBlock: BlockParameter = BlockParameter.Tag.FINALIZED @@ -123,9 +123,9 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-success-backoff-delay"], description = [ "L1 RPC api retry backoff delay, default none. ", - "Request will fire as soon as previous response is received" + "Request will fire as soon as previous response is received", ], - required = false + required = false, ) var l1RequestSuccessBackoffDelay: java.time.Duration? = null @@ -133,7 +133,7 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-retry-backoff-delay"], defaultValue = "PT1S", description = ["L1 RPC api retry backoff delay, default 1s"], - required = false + required = false, ) var l1RequestRetryBackoffDelay: java.time.Duration = java.time.Duration.ofSeconds(1) @@ -141,9 +141,9 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-retry-timeout"], description = [ "L1 RPC api stop retrying as soon as timeout has elapsed or limit is reached", - "default will retry indefinitely" + "default will retry indefinitely", ], - required = false + required = false, ) var l1RequestRetryTimeout: java.time.Duration? = null @@ -151,37 +151,37 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-l1-retry-limit"], description = [ "L1 RPC api stop retrying when limit is reached or timeout has elapsed", - "default will retry indefinitely" + "default will retry indefinitely", ], - required = false + required = false, ) var l1RequestRetryLimit: Int? = null @CommandLine.Option( names = ["--$cliOptionsPrefix-shomei-endpoint"], description = ["shomei (state manager) endpoint"], - required = true + required = true, ) lateinit var shomeiEndpoint: URI @CommandLine.Option( names = ["--$cliOptionsPrefix-blobscan-endpoint"], description = ["blobscan api endpoint"], - required = true + required = true, ) lateinit var blobscanEndpoint: URI @CommandLine.Option( names = ["--$cliOptionsPrefix-blobscan-retry-backoff-delay"], description = ["blobscan api retry backoff delay, default 1s"], - required = false + required = false, ) var blobscanRequestRetryBackoffDelay: java.time.Duration = java.time.Duration.ofSeconds(1) @CommandLine.Option( names = ["--$cliOptionsPrefix-blobscan-ratelimit-backoff-delay"], description = ["blobscan api retry ratelimit backoff delay, default is disabled"], - required = false + required = false, ) var blobscanRequestRatelimitBackoffDelay: java.time.Duration? = null @@ -189,9 +189,9 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-blobscan-retry-timeout"], description = [ "Blobscan api stop retrying as soon as timeout has elapsed or limit is reached.", - "default will retry indefinitely" + "default will retry indefinitely", ], - required = false + required = false, ) var blobscanRequestRetryTimeout: java.time.Duration? = null @@ -199,9 +199,9 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-blobscan-retry-limit"], description = [ "Blobscan api stop retrying when limit is reached or timeout has elapsed", - "default will retry indefinitely" + "default will retry indefinitely", ], - required = false + required = false, ) var blobscanRequestRetryLimit: Int? = null @@ -209,10 +209,10 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-overriding-recovery-start-block-number"], description = [ "Tries to force the recovery start block number to the given value. " + - "This is mean for testing purposes, not production. Must be greater than or equal to 1." + "This is mean for testing purposes, not production. Must be greater than or equal to 1.", ], defaultValue = "\${env:STATERECOVERY_OVERRIDE_START_BLOCK_NUMBER}", - required = false + required = false, ) var overridingRecoveryStartBlockNumber: Long? = null @@ -220,10 +220,10 @@ class PluginCliOptions { names = ["--$cliOptionsPrefix-debug-force-sync-stop-block-number"], description = [ "Forces Besu to stop syncing at the given block number. " + - "This is mean for testing purposes, not production. Must be greater than or equal to 1." + "This is mean for testing purposes, not production. Must be greater than or equal to 1.", ], defaultValue = "\${env:STATERECOVERY_DEBUG_FORCE_STOP_SYNC_BLOCK_NUMBER}", - required = false + required = false, ) var debugForceSyncStopBlockNumber: Long? = null @@ -252,25 +252,25 @@ class PluginCliOptions { l1RequestRetryConfig = RetryConfig( backoffDelay = l1RequestRetryBackoffDelay.toKotlinDuration(), timeout = l1RequestRetryTimeout?.toKotlinDuration(), - maxRetries = l1RequestRetryLimit?.toUInt() + maxRetries = l1RequestRetryLimit?.toUInt(), ), blobscanEndpoint = blobscanEndpoint, blobScanRequestRetryConfig = RetryConfig( backoffDelay = blobscanRequestRetryBackoffDelay.toKotlinDuration(), timeout = blobscanRequestRetryTimeout?.toKotlinDuration(), - maxRetries = blobscanRequestRetryLimit?.toUInt() + maxRetries = blobscanRequestRetryLimit?.toUInt(), ), blobscanRequestRatelimitBackoffDelay = blobscanRequestRatelimitBackoffDelay?.toKotlinDuration(), shomeiEndpoint = shomeiEndpoint, overridingRecoveryStartBlockNumber = overridingRecoveryStartBlockNumber?.toULong(), - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber?.toULong() + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber?.toULong(), ) } class AddressConverter : CommandLine.ITypeConverter
{ override fun convert(value: String): Address { return Address.fromHexStringStrict(value) ?: throw CommandLine.TypeConversionException( - "Invalid address: $value" + "Invalid address: $value", ) } } diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/RecoveryModeManager.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/RecoveryModeManager.kt index ecee7864..e877ac34 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/RecoveryModeManager.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/RecoveryModeManager.kt @@ -16,7 +16,7 @@ class RecoveryModeManager( private val miningService: MiningService, private val recoveryStatePersistence: RecoveryStatusPersistence, private val debugForceSyncStopBlockNumber: ULong? = null, - headBlockNumber: ULong + headBlockNumber: ULong, ) : BesuEvents.BlockAddedListener { private val log: Logger = LogManager.getLogger(RecoveryModeManager::class.java.name) @@ -37,7 +37,7 @@ class RecoveryModeManager( log.info( "enabling recovery mode immediately at blockNumber={} recoveryTargetBlockNumber={}", headBlockNumber, - targetBlockNumber + targetBlockNumber, ) switchToRecoveryMode() } @@ -56,14 +56,14 @@ class RecoveryModeManager( log.info( "Stopping synchronization services at block={} recoveryTargetBlockNumber={} was reached", headBlockNumber, - targetBlockNumber + targetBlockNumber, ) switchToRecoveryMode() } else if (debugForceSyncStopBlockNumber != null && headBlockNumber >= debugForceSyncStopBlockNumber) { log.info( "Stopping synchronization services at block={} debugForceSyncStopBlockNumber={}", headBlockNumber, - debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber, ) stopBesuServices() } @@ -71,7 +71,7 @@ class RecoveryModeManager( private fun hasReachedTargetBlock( headBlockNumber: ULong = this.headBlockNumber, - targetBlockNumber: ULong? = this.targetBlockNumber + targetBlockNumber: ULong? = this.targetBlockNumber, ): Boolean { return (headBlockNumber + 1u) >= (targetBlockNumber ?: ULong.MAX_VALUE) } diff --git a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/TransactionMapper.kt b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/TransactionMapper.kt index d96a8fd7..d438c99e 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/TransactionMapper.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/main/kotlin/linea/staterecovery/plugin/TransactionMapper.kt @@ -25,7 +25,7 @@ object TransactionMapper { */ fun mapToBesu( transaction: TransactionFromL1RecoveredData, - chainId: ULong + chainId: ULong, ): Transaction { val builder = Transaction.builder() builder @@ -48,13 +48,13 @@ object TransactionMapper { } private fun mapAccessListEntries( - accessList: List? + accessList: List?, ): List? { return accessList ?.map { accessTupleParameter -> AccessListEntry.createAccessListEntry( accessTupleParameter.address.toBesuAddress(), - accessTupleParameter.storageKeys.map { it.encodeHex() } + accessTupleParameter.storageKeys.map { it.encodeHex() }, ) } } @@ -69,7 +69,7 @@ object TransactionMapper { */ fun mapToBesu( transactions: List, - defaultChainId: ULong + defaultChainId: ULong, ): List { return transactions.map { tx -> mapToBesu(tx, defaultChainId) } } diff --git a/besu-plugins/state-recovery/besu-plugin/src/test/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupportTest.kt b/besu-plugins/state-recovery/besu-plugin/src/test/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupportTest.kt index f2516ba1..4df18b13 100644 --- a/besu-plugins/state-recovery/besu-plugin/src/test/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupportTest.kt +++ b/besu-plugins/state-recovery/besu-plugin/src/test/kotlin/linea/staterecovery/plugin/BlockHashLookupWithRecoverySupportTest.kt @@ -15,16 +15,16 @@ class BlockHashLookupWithRecoverySupportTest { lookback.addLookbackHashes( mapOf( 1UL to hashOf(1UL), - 2UL to hashOf(3UL) - ) + 2UL to hashOf(3UL), + ), ) assertThatThrownBy { lookback.addLookbackHashes( mapOf( 1UL to hashOf(1UL), - 3UL to hashOf(3UL) - ) + 3UL to hashOf(3UL), + ), ) } .isInstanceOf(IllegalArgumentException::class.java) @@ -34,7 +34,7 @@ class BlockHashLookupWithRecoverySupportTest { @Test fun `addHeadBlockHash should update and prune the lookback hashes outside the lookback window`() { val lookback = BlockHashLookupWithRecoverySupport( - lookbackWindow = 3UL + lookbackWindow = 3UL, ) lookback.addHeadBlockHash(0UL, hashOf(123UL)) diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiter.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiter.kt index 09e5e857..60eafcee 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiter.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiter.kt @@ -24,11 +24,11 @@ class StaticVertxHttpRequestRateLimiter( .div(5) .coerceAtLeast(1.milliseconds), private val requestLogFormatter: VertxHttpLoggingFormatter, - private val logger: Logger = LogManager.getLogger(StaticVertxHttpRequestRateLimiter::class.java) + private val logger: Logger = LogManager.getLogger(StaticVertxHttpRequestRateLimiter::class.java), ) : VertxHttpRequestSender { private data class RequestAndFutureResponse( val request: HttpRequest, - val future: SafeFuture> + val future: SafeFuture>, ) private val rateLimitPerSecond = 1.seconds.div(rateLimitBackoffDelay).toInt() @@ -54,7 +54,7 @@ class StaticVertxHttpRequestRateLimiter( rateLimitPerSecond, requestQueue.size, rateLimitBackoffDelay - elapsedTimeSinceLastRequest, - requestLogFormatter.toLogString(requestQueue.peek().request) + requestLogFormatter.toLogString(requestQueue.peek().request), ) return } @@ -93,7 +93,7 @@ class StaticVertxHttpRequestRateLimiter( rateLimitPerSecond, requestQueue.size, rateLimitBackoffDelay - lastRequestFiredTime.elapsedNow(), - requestLogFormatter.toLogString(request) + requestLogFormatter.toLogString(request), ) requestQueue.add(req) diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpLoggingFormatter.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpLoggingFormatter.kt index 0315927d..8bb5ed76 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpLoggingFormatter.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpLoggingFormatter.kt @@ -9,7 +9,7 @@ interface VertxHttpLoggingFormatter { fun toLogString( request: HttpRequest, response: HttpResponse? = null, - failureCause: Throwable? = null + failureCause: Throwable? = null, ): String } @@ -22,14 +22,14 @@ fun HttpRequest<*>.fullUri(): String { scheme, this.host(), this.port(), - path + path, ) } class VertxRestLoggingFormatter( private val includeFullUri: Boolean = false, private val uriTransformer: (String) -> String = { it }, - private val responseLogMaxSize: UInt? = null + private val responseLogMaxSize: UInt? = null, ) : VertxHttpLoggingFormatter { fun HttpRequest<*>.uriToLog(): String { return if (includeFullUri) { @@ -46,14 +46,14 @@ class VertxRestLoggingFormatter( override fun toLogString( request: HttpRequest, response: HttpResponse?, - failureCause: Throwable? + failureCause: Throwable?, ): String { return if (failureCause != null) { String.format( "<-- %s %s %s", request.method(), uriTransformer.invoke(request.uriToLog()), - failureCause.message?.let { errorMsg -> "error=$errorMsg" } ?: "" + failureCause.message?.let { errorMsg -> "error=$errorMsg" } ?: "", ) } else { val responseToLog = response?.bodyAsString()?.let { bodyStr -> @@ -68,7 +68,7 @@ class VertxRestLoggingFormatter( request.method(), uriTransformer.invoke(request.uriToLog()), response?.statusCode() ?: "", - responseToLog + responseToLog, ) } } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSender.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSender.kt index 81b4e4ff..ae1c0b52 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSender.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSender.kt @@ -16,7 +16,7 @@ interface VertxHttpRequestSender { * Handy to avoid creating anonymous classes. */ class SimpleVertxHttpRequestSender( - private val requestLogger: VertxRequestLogger + private val requestLogger: VertxRequestLogger, ) : VertxHttpRequestSender { override fun makeRequest(request: HttpRequest): SafeFuture> { requestLogger.logRequest(request) diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSenderFactory.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSenderFactory.kt index 7f2d2763..69c1cbfb 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSenderFactory.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxHttpRequestSenderFactory.kt @@ -13,7 +13,7 @@ object VertxHttpRequestSenderFactory { rateLimitBackoffDelay: Duration? = null, retryableErrorCodes: Set = setOf(429, 503, 504), logFormatter: VertxHttpLoggingFormatter, - baseRequestSender: VertxHttpRequestSender + baseRequestSender: VertxHttpRequestSender, ): VertxHttpRequestSender { val rateLimitedSender = rateLimitBackoffDelay ?.let { @@ -21,7 +21,7 @@ object VertxHttpRequestSenderFactory { vertx = vertx, requestSender = baseRequestSender, rateLimitBackoffDelay = rateLimitBackoffDelay, - requestLogFormatter = logFormatter + requestLogFormatter = logFormatter, ) } ?: baseRequestSender val sender = requestRetryConfig @@ -30,7 +30,7 @@ object VertxHttpRequestSenderFactory { vertx = vertx, requestSender = rateLimitedSender, requestRetryConfig = requestRetryConfig, - retryableErrorCodes = retryableErrorCodes + retryableErrorCodes = retryableErrorCodes, ) } ?: rateLimitedSender @@ -45,13 +45,13 @@ object VertxHttpRequestSenderFactory { requestResponseLogLevel: Level = Level.TRACE, failuresLogLevel: Level = Level.DEBUG, retryableErrorCodes: Set = setOf(429, 503, 504), - logFormatter: VertxHttpLoggingFormatter + logFormatter: VertxHttpLoggingFormatter, ): VertxHttpRequestSender { val requestLogger = VertxRestRequestLogger( log = logger, requestResponseLogLevel = requestResponseLogLevel, failuresLogLevel = failuresLogLevel, - logFormatter = logFormatter + logFormatter = logFormatter, ) return createWithBaseSender( vertx = vertx, @@ -59,7 +59,7 @@ object VertxHttpRequestSenderFactory { rateLimitBackoffDelay = rateLimitBackoffDelay, retryableErrorCodes = retryableErrorCodes, logFormatter = logFormatter, - baseRequestSender = SimpleVertxHttpRequestSender(requestLogger) + baseRequestSender = SimpleVertxHttpRequestSender(requestLogger), ) } } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestLogger.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestLogger.kt index 53e1c513..3191f812 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestLogger.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestLogger.kt @@ -11,7 +11,7 @@ interface VertxRequestLogger { fun logResponse( request: HttpRequest, response: HttpResponse? = null, - failureCause: Throwable? = null + failureCause: Throwable? = null, ) } @@ -19,18 +19,18 @@ class VertxRestRequestLogger( private val log: Logger, private val logFormatter: VertxHttpLoggingFormatter, private val requestResponseLogLevel: Level = Level.TRACE, - private val failuresLogLevel: Level = Level.DEBUG + private val failuresLogLevel: Level = Level.DEBUG, ) : VertxRequestLogger { constructor( log: Logger, responseLogMaxSize: UInt? = null, requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ) : this( log = log, logFormatter = VertxRestLoggingFormatter(responseLogMaxSize = responseLogMaxSize), requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) private fun logRequest(request: HttpRequest, logLevel: Level = requestResponseLogLevel) { @@ -46,7 +46,7 @@ class VertxRestRequestLogger( override fun logResponse( request: HttpRequest, response: HttpResponse?, - failureCause: Throwable? + failureCause: Throwable?, ) { val isError = response?.statusCode()?.let(::isNotSuccessStatusCode) ?: true val logLevel = if (isError) failuresLogLevel else requestResponseLogLevel diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestRetrier.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestRetrier.kt index ad99d301..39597113 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestRetrier.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/http/vertx/VertxRequestRetrier.kt @@ -17,15 +17,15 @@ class VertxRequestRetrier( backoffDelay = requestRetryConfig.backoffDelay, maxRetries = requestRetryConfig.maxRetries?.toInt(), timeout = requestRetryConfig.timeout, - vertx = vertx - ) + vertx = vertx, + ), ) : VertxHttpRequestSender { override fun makeRequest(request: HttpRequest): SafeFuture> { return asyncRetryer .retry( stopRetriesPredicate = { response: HttpResponse -> response.statusCode() !in retryableErrorCodes - } + }, ) { requestSender.makeRequest(request) } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/BlobScanClient.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/BlobScanClient.kt index 7b2e8fa8..62c50034 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/BlobScanClient.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/BlobScanClient.kt @@ -20,7 +20,7 @@ import kotlin.time.Duration class BlobScanClient( private val restClient: RestClient, - private val log: Logger = LogManager.getLogger(BlobScanClient::class.java) + private val log: Logger = LogManager.getLogger(BlobScanClient::class.java), ) : BlobFetcher { fun getBlobById(id: String): SafeFuture { return restClient @@ -31,7 +31,7 @@ class BlobScanClient( } else { throw RuntimeException( "error fetching blobId=$id " + - "errorMessage=${response.body?.getString("message") ?: ""}" + "errorMessage=${response.body?.getString("message") ?: ""}", ) } } @@ -48,7 +48,7 @@ class BlobScanClient( requestRetryConfig: RetryConfig, rateLimitBackoffDelay: Duration? = null, logger: Logger = LogManager.getLogger(BlobScanClient::class.java), - responseLogMaxSize: UInt? = 1000u + responseLogMaxSize: UInt? = 1000u, ): BlobScanClient { val logFormatter = VertxRestLoggingFormatter(responseLogMaxSize = responseLogMaxSize) @@ -61,16 +61,16 @@ class BlobScanClient( logger = logger, requestResponseLogLevel = Level.DEBUG, failuresLogLevel = Level.DEBUG, - logFormatter = logFormatter + logFormatter = logFormatter, ) val restClient = VertxRestClient( webClient = WebClient.create(vertx, WebClientOptions().setDefaultsFrom(endpoint)), responseParser = { it.toJsonObject() }, - requestSender = requestSender + requestSender = requestSender, ) return BlobScanClient( restClient = restClient, - log = logger + log = logger, ) } } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/VertxRestClient.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/VertxRestClient.kt index c93fbdeb..52b6c4c2 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/VertxRestClient.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/main/kotlin/linea/staterecovery/clients/blobscan/VertxRestClient.kt @@ -8,7 +8,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture // TODO: move to a common module data class RestResponse( val statusCode: Int, - val body: T? + val body: T?, ) interface RestClient { @@ -20,13 +20,13 @@ class VertxRestClient( private val webClient: WebClient, private val responseParser: (Buffer) -> Response, private val requestSender: VertxHttpRequestSender, - private val requestHeaders: Map = mapOf("Accept" to "application/json") + private val requestHeaders: Map = mapOf("Accept" to "application/json"), ) : RestClient { override fun get(path: String): SafeFuture> { return requestSender.makeRequest( webClient .get(path) - .apply { requestHeaders.forEach(::putHeader) } + .apply { requestHeaders.forEach(::putHeader) }, ) .thenApply { response -> val parsedResponse = response.body()?.let(responseParser) diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/FakeRequestSender.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/FakeRequestSender.kt index 36dcd2be..cd98fb17 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/FakeRequestSender.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/FakeRequestSender.kt @@ -16,17 +16,25 @@ import kotlin.time.TimeSource fun httpResponse( statusCode: Int = 200, statusMessage: String = "OK", - body: Buffer = Buffer.buffer() + body: Buffer = Buffer.buffer(), ): HttpResponse { return HttpResponseImpl( - /* version = */ HttpVersion.HTTP_1_1, - /* statusCode = */ statusCode, - /* statusMessage = */ statusMessage, - /* headers = */ HeadersMultiMap(), - /* trailers = */ HeadersMultiMap(), - /* cookies = */ emptyList(), - /* body = */ body, - /* redirects = */ emptyList() + /* version = */ + HttpVersion.HTTP_1_1, + /* statusCode = */ + statusCode, + /* statusMessage = */ + statusMessage, + /* headers = */ + HeadersMultiMap(), + /* trailers = */ + HeadersMultiMap(), + /* cookies = */ + emptyList(), + /* body = */ + body, + /* redirects = */ + emptyList(), ) } @@ -35,8 +43,8 @@ class FakeRequestSender( VertxRestRequestLogger( responseLogMaxSize = null, requestResponseLogLevel = Level.DEBUG, - log = LogManager.getLogger(FakeRequestSender::class.java) - ) + log = LogManager.getLogger(FakeRequestSender::class.java), + ), ) : VertxHttpRequestSender { private val monotonicClock = TimeSource.Monotonic private var lastRequestTime = monotonicClock.markNow() diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiterTest.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiterTest.kt index 1facf10b..304d25fb 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiterTest.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/StaticVertxHttpRequestRateLimiterTest.kt @@ -23,7 +23,7 @@ class StaticVertxHttpRequestRateLimiterTest { vertx = vertx, requestSender = reqSender, rateLimitBackoffDelay = rateLimitBackoffDelay, - requestLogFormatter = VertxRestLoggingFormatter() + requestLogFormatter = VertxRestLoggingFormatter(), ) } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxHttpRequestRateLimiterAndRetryTest.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxHttpRequestRateLimiterAndRetryTest.kt index 34ac92fb..ef39ec9e 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxHttpRequestRateLimiterAndRetryTest.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxHttpRequestRateLimiterAndRetryTest.kt @@ -28,10 +28,10 @@ class VertxHttpRequestRateLimiterAndRetryTest { requestRetryConfig = RetryConfig( maxRetries = 5u, backoffDelay = 10.milliseconds, - timeout = rateLimitBackoffDelay * 30 + timeout = rateLimitBackoffDelay * 30, ), rateLimitBackoffDelay = rateLimitBackoffDelay, - logFormatter = VertxRestLoggingFormatter(responseLogMaxSize = 1000u) + logFormatter = VertxRestLoggingFormatter(responseLogMaxSize = 1000u), ) // Warn: this does not work in io.github.hakky54:logcaptor // don't have time to dig into it now. disabling it for now diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestLoggingFormatterTest.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestLoggingFormatterTest.kt index 75c45761..09426a86 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestLoggingFormatterTest.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestLoggingFormatterTest.kt @@ -13,7 +13,7 @@ class VertxRestLoggingFormatterTest { val request = WebClient.create( Vertx.vertx(), WebClientOptions() - .setDefaultsFrom(URI("http://service:9876/")) + .setDefaultsFrom(URI("http://service:9876/")), ) .get("/users/1?appKey=SOME_APP_KEY") @@ -21,7 +21,7 @@ class VertxRestLoggingFormatterTest { return VertxRestLoggingFormatter( includeFullUri = includeFullUri, uriTransformer = { it.replace("SOME_APP_KEY", "***") }, - responseLogMaxSize = null + responseLogMaxSize = null, ) } @@ -39,7 +39,7 @@ class VertxRestLoggingFormatterTest { val response = httpResponse( statusCode = 200, statusMessage = "OK", - body = Buffer.buffer("some-response-body") + body = Buffer.buffer("some-response-body"), ) assertThat(formatter(includeFullUri = false).toLogString(request, response)) diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestRequestLoggerTest.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestRequestLoggerTest.kt index aad315ca..186c484d 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestRequestLoggerTest.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/http/vertx/VertxRestRequestLoggerTest.kt @@ -21,7 +21,7 @@ class VertxRestRequestLoggerTest { override fun toLogString( request: HttpRequest, response: HttpResponse?, - failureCause: Throwable? + failureCause: Throwable?, ): String { return "response-log-string" } @@ -29,14 +29,14 @@ class VertxRestRequestLoggerTest { fun setUpLogger( // we need to use a different logger name for each test - loggerName: String = "request-logger-test-" + Random.nextBytes(8).encodeHex() + loggerName: String = "request-logger-test-" + Random.nextBytes(8).encodeHex(), ): Pair { val logCaptor: LogCaptor = LogCaptor.forName(loggerName) return VertxRestRequestLogger( log = LogManager.getLogger(loggerName), logFormatter = FakeLogFormatter(), requestResponseLogLevel = Level.TRACE, - failuresLogLevel = Level.DEBUG + failuresLogLevel = Level.DEBUG, ) to logCaptor } diff --git a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/staterecovery/clients/blobscan/BlobScanClientTest.kt b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/staterecovery/clients/blobscan/BlobScanClientTest.kt index 287fb30c..154d2e27 100644 --- a/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/staterecovery/clients/blobscan/BlobScanClientTest.kt +++ b/besu-plugins/state-recovery/clients/blobscan-client/src/test/kotlin/linea/staterecovery/clients/blobscan/BlobScanClientTest.kt @@ -32,13 +32,13 @@ class BlobScanClientTest { fun setUp(vertx: Vertx) { wiremock = WireMockServer( WireMockConfiguration.options() - .dynamicPort() + .dynamicPort(), ) .apply { addMockServiceRequestListener(object : RequestListener { override fun requestReceived( request: com.github.tomakehurst.wiremock.http.Request, - response: com.github.tomakehurst.wiremock.http.Response + response: com.github.tomakehurst.wiremock.http.Response, ) { // to debug // println("request: ${request.url}") @@ -55,8 +55,8 @@ class BlobScanClientTest { requestRetryConfig = RetryConfig( backoffDelay = 10.milliseconds, maxRetries = 5u, - timeout = 5.seconds - ) + timeout = 5.seconds, + ), ) } @@ -78,8 +78,8 @@ class BlobScanClientTest { .willReturn( WireMock.ok() .withHeader("Content-type", "application/json") - .withBody(successResponseBody(blobId, blobData)) - ) + .withBody(successResponseBody(blobId, blobData)), + ), ) assertThat(blobScanClient.getBlobById(blobId).get().encodeHex()).isEqualTo(blobData) @@ -99,9 +99,9 @@ class BlobScanClientTest { .withBody( """ {"message":"No blob with versioned hash or kzg commitment '$blobId'.","code":"NOT_FOUND"} - """.trimIndent() - ) - ) + """.trimIndent(), + ), + ), ) assertThatThrownBy { blobScanClient.getBlobById(blobId).get() } @@ -117,22 +117,22 @@ class BlobScanClientTest { WireMock.get("/blobs/$blobId") .inScenario("SERVER_ERROR") .willReturn(WireMock.status(503)) - .willSetStateTo("SERVER_ERROR_1") + .willSetStateTo("SERVER_ERROR_1"), ) wiremock.stubFor( WireMock.get("/blobs/$blobId") .inScenario("SERVER_ERROR") .whenScenarioStateIs("SERVER_ERROR_1") .willReturn(WireMock.status(503)) - .willSetStateTo("SERVER_OK") + .willSetStateTo("SERVER_OK"), ) wiremock.stubFor( WireMock.get("/blobs/$blobId") .inScenario("SERVER_ERROR") .whenScenarioStateIs("SERVER_OK") .willReturn( - WireMock.okJson(successResponseBody(blobId, blobData)) - ) + WireMock.okJson(successResponseBody(blobId, blobData)), + ), ) assertThat(blobScanClient.getBlobById(blobId).get().encodeHex()).isEqualTo(blobData) @@ -140,7 +140,7 @@ class BlobScanClientTest { private fun successResponseBody( blobId: String, - blobData: String + blobData: String, ): String { return """ { diff --git a/besu-plugins/state-recovery/clients/eth-api/src/main/kotlin/linea/staterecovery/clients/VertxTransactionDetailsClient.kt b/besu-plugins/state-recovery/clients/eth-api/src/main/kotlin/linea/staterecovery/clients/VertxTransactionDetailsClient.kt index b430b8c2..8a2f1f58 100644 --- a/besu-plugins/state-recovery/clients/eth-api/src/main/kotlin/linea/staterecovery/clients/VertxTransactionDetailsClient.kt +++ b/besu-plugins/state-recovery/clients/eth-api/src/main/kotlin/linea/staterecovery/clients/VertxTransactionDetailsClient.kt @@ -13,7 +13,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture import java.net.URI class VertxTransactionDetailsClient internal constructor( - private val jsonRpcClient: JsonRpcV2Client + private val jsonRpcClient: JsonRpcV2Client, ) : TransactionDetailsClient { companion object { @@ -21,14 +21,14 @@ class VertxTransactionDetailsClient internal constructor( jsonRpcClientFactory: JsonRpcClientFactory, endpoint: URI, retryConfig: RequestRetryConfig, - logger: Logger = LogManager.getLogger(TransactionDetailsClient::class.java) + logger: Logger = LogManager.getLogger(TransactionDetailsClient::class.java), ): VertxTransactionDetailsClient { return VertxTransactionDetailsClient( jsonRpcClientFactory.createJsonRpcV2Client( endpoints = listOf(endpoint), retryConfig = retryConfig, - log = logger - ) + log = logger, + ), ) } } @@ -44,7 +44,7 @@ class VertxTransactionDetailsClient internal constructor( ?.toList() ?.map { it.asText().decodeHex() } ?: emptyList() - } + }, ) } } diff --git a/besu-plugins/state-recovery/test-cases/src/e2eTest/kotlin/linea/staterecovery/StateRecoveryE2ETest.kt b/besu-plugins/state-recovery/test-cases/src/e2eTest/kotlin/linea/staterecovery/StateRecoveryE2ETest.kt index f6dd7487..54176f98 100644 --- a/besu-plugins/state-recovery/test-cases/src/e2eTest/kotlin/linea/staterecovery/StateRecoveryE2ETest.kt +++ b/besu-plugins/state-recovery/test-cases/src/e2eTest/kotlin/linea/staterecovery/StateRecoveryE2ETest.kt @@ -54,7 +54,7 @@ class StateRecoveryE2ETest { fun beforeEach(vertx: Vertx) { val jsonRpcFactory = VertxHttpJsonRpcClientFactory( vertx = vertx, - metricsFacade = MicrometerMetricsFacade(SimpleMeterRegistry()) + metricsFacade = MicrometerMetricsFacade(SimpleMeterRegistry()), ) stateManagerClient = StateManagerV1JsonRpcClient.create( @@ -63,10 +63,10 @@ class StateRecoveryE2ETest { maxInflightRequestsPerClient = 1U, requestRetry = RequestRetryConfig( backoffDelay = 10.milliseconds, - timeout = 2.seconds + timeout = 2.seconds, ), zkStateManagerVersion = "2.3.0", - logger = LogManager.getLogger("test.clients.l1.state-manager") + logger = LogManager.getLogger("test.clients.l1.state-manager"), ) configureLoggers( @@ -80,7 +80,7 @@ class StateRecoveryE2ETest { "test.clients.l1.linea-contract" to Level.INFO, "test.clients.l1.events-fetcher" to Level.INFO, "test.clients.l1.blobscan" to Level.INFO, - "net.consensys.linea.contract.l1" to Level.INFO + "net.consensys.linea.contract.l1" to Level.INFO, ) } @@ -89,16 +89,16 @@ class StateRecoveryE2ETest { Runner.executeCommandFailOnNonZeroExitCode( command = "make start-env-with-staterecovery", envVars = mapOf( - "L1_GENESIS_TIME" to Clock.System.now().plus(5.seconds).epochSeconds.toString() + "L1_GENESIS_TIME" to Clock.System.now().plus(5.seconds).epochSeconds.toString(), ), - timeout = 2.minutes + timeout = 2.minutes, ).get() log.debug("stack restarted") } @Test fun `should recover from middle of chain and be resilient to node restarts`( - vertx: Vertx + vertx: Vertx, ) { // Part A: // we shall have multiple finalizations on L1 @@ -128,15 +128,15 @@ class StateRecoveryE2ETest { Web3jClientManager.buildL1Client( log = LogManager.getLogger("test.clients.l1.events-fetcher"), requestResponseLogLevel = Level.TRACE, - failuresLogLevel = Level.WARN + failuresLogLevel = Level.WARN, ), requestRetryConfig = RetryConfig.noRetries, - vertx = null + vertx = null, ), EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = 1.milliseconds + loopSuccessBackoffDelay = 1.milliseconds, ), - log = LogManager.getLogger("test.clients.l1.events-fetcher") + log = LogManager.getLogger("test.clients.l1.events-fetcher"), ) val web3jElClient = createWeb3jHttpClient(executionLayerUrl) log.info("starting test flow: besu staterecovery block={}", web3jElClient.ethBlockNumber().send().blockNumber) @@ -167,7 +167,7 @@ class StateRecoveryE2ETest { command = "make staterecovery-replay-from-block " + "L1_ROLLUP_CONTRACT_ADDRESS=$localStackL1ContractAddress " + "STATERECOVERY_OVERRIDE_START_BLOCK_NUMBER=$stateRecoveryStartBlockNumber", - log = log + log = log, ).get() // No Errors should be logged in Besu assertThat(getBesuErrorLogs()).isEmpty() @@ -178,7 +178,7 @@ class StateRecoveryE2ETest { web3jElClient, stateManagerClient, lastFinalizationA.event.endBlockNumber, - lastFinalizationA.event.finalStateRootHash + lastFinalizationA.event.finalStateRootHash, ) // No Errors should be logged in Besu assertThat(getBesuErrorLogs()).isEmpty() @@ -200,7 +200,7 @@ class StateRecoveryE2ETest { web3jElClient, stateManagerClient, lastFinalizationB.event.endBlockNumber, - lastFinalizationB.event.finalStateRootHash + lastFinalizationB.event.finalStateRootHash, ) // No Errors should be logged in Besu assertThat(getBesuErrorLogs()).isEmpty() @@ -210,7 +210,7 @@ class StateRecoveryE2ETest { log.info("Restarting zkbesu-shomei node") execCommandAndAssertSuccess( command = "docker restart -s 9 zkbesu-shomei-sr", - log = log + log = log, ).get() // No Errors should be logged in Besu assertThat(getBesuErrorLogs()).isEmpty() @@ -237,31 +237,36 @@ class StateRecoveryE2ETest { web3jElClient, stateManagerClient, lastFinalizationC.event.endBlockNumber, - lastFinalizationC.event.finalStateRootHash + lastFinalizationC.event.finalStateRootHash, ) // No Errors should be logged in Besu assertThat(getBesuErrorLogs()).isEmpty() } private fun sendTxToL2( - keepSendingPredicate: () -> Boolean + keepSendingPredicate: () -> Boolean, ) { val account = L2AccountManager.generateAccount() val txManager = L2AccountManager.getTransactionManager(account) Thread { while (keepSendingPredicate()) { val txHash = txManager.sendTransaction( - /*gasPrice*/ 150UL.gwei.toBigInteger(), - /*gasLimit*/ 25_000UL.toBigInteger(), - /*to*/ account.address, - /*data*/ "", - /*value*/ 1UL.toBigInteger() + /*gasPrice*/ + 150UL.gwei.toBigInteger(), + /*gasLimit*/ + 25_000UL.toBigInteger(), + /*to*/ + account.address, + /*data*/ + "", + /*value*/ + 1UL.toBigInteger(), ).transactionHash log.trace("sent tx to L2, txHash={}", txHash) Web3jClientManager.l2Client.waitForTxReceipt( txHash = txHash, timeout = 5.seconds, - pollingInterval = 500.milliseconds + pollingInterval = 500.milliseconds, ) } }.start() diff --git a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/LineaSubmissionEventsClientIntTest.kt b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/LineaSubmissionEventsClientIntTest.kt index 3f8114ac..19a183a9 100644 --- a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/LineaSubmissionEventsClientIntTest.kt +++ b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/LineaSubmissionEventsClientIntTest.kt @@ -39,7 +39,7 @@ class LineaSubmissionEventsClientIntTest { private lateinit var submissionEventsFetcher: LineaRollupSubmissionEventsClient private fun setupTest( - vertx: Vertx + vertx: Vertx, ) { configureLoggers( rootLevel = Level.INFO, @@ -47,7 +47,7 @@ class LineaSubmissionEventsClientIntTest { "test.clients.l1.executionlayer" to Level.INFO, "test.clients.l1.web3j-default" to Level.INFO, "test.clients.l1.linea-contract" to Level.INFO, - "test.clients.l1.events-fetcher" to Level.DEBUG + "test.clients.l1.events-fetcher" to Level.DEBUG, ) val rollupDeploymentFuture = ContractsManager.get() @@ -57,13 +57,13 @@ class LineaSubmissionEventsClientIntTest { blobsResponsesDir = "$testDataDir/compression/responses", aggregationsResponsesDir = "$testDataDir/aggregation/responses", numberOfAggregations = 7, - extraBlobsWithoutAggregation = 3 + extraBlobsWithoutAggregation = 3, ) // wait smc deployment finishes rollupDeploymentResult = rollupDeploymentFuture.get() submissionEventsFetcher = createSubmissionEventsClient( vertx = vertx, - contractAddress = rollupDeploymentResult.contractAddress + contractAddress = rollupDeploymentResult.contractAddress, ) submitBlobsAndAggregationsAndWaitExecution( @@ -71,24 +71,24 @@ class LineaSubmissionEventsClientIntTest { contractClientForAggregationSubmission = connectToLineaRollupContract( contractAddress = rollupDeploymentResult.contractAddress, transactionManager = rollupDeploymentResult.rollupOperators[1].txManager, - smartContractErrors = lineaRollupContractErrors + smartContractErrors = lineaRollupContractErrors, ), aggregationsAndBlobs = aggregationsAndBlobs, blobChunksMaxSize = 9, l1Web3jClient = Web3jClientManager.l1Client, - waitTimeout = 4.minutes + waitTimeout = 4.minutes, ) } private fun createSubmissionEventsClient( vertx: Vertx, - contractAddress: String + contractAddress: String, ): LineaRollupSubmissionEventsClient { val log = LogManager.getLogger("test.clients.l1.events-fetcher") val eventsFetcherWeb3jClient = Web3jClientManager.buildL1Client( log = log, requestResponseLogLevel = Level.DEBUG, - failuresLogLevel = Level.WARN + failuresLogLevel = Level.WARN, ) return LineaSubmissionEventsClientImpl( logsSearcher = EthLogsSearcherImpl( @@ -96,16 +96,16 @@ class LineaSubmissionEventsClientIntTest { ethApiClient = createEthApiClient( web3jClient = eventsFetcherWeb3jClient, requestRetryConfig = RetryConfig.noRetries, - vertx = null + vertx = null, ), config = EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = 1.milliseconds + loopSuccessBackoffDelay = 1.milliseconds, ), - log = log + log = log, ), smartContractAddress = contractAddress, l1LatestSearchBlock = BlockParameter.Tag.LATEST, - logsBlockChunkSize = 100 + logsBlockChunkSize = 100, ) } @@ -125,8 +125,8 @@ class LineaSubmissionEventsClientIntTest { submissionEventsFetcher .findFinalizationAndDataSubmissionV3Events( fromL1BlockNumber = BlockParameter.Tag.EARLIEST, - finalizationStartBlockNumber = expectedFinalizationEvent.startBlockNumber - ) + finalizationStartBlockNumber = expectedFinalizationEvent.startBlockNumber, + ), ) .succeedsWithin(1.minutes.toJavaDuration()) .extracting { submissionEvents -> @@ -146,8 +146,8 @@ class LineaSubmissionEventsClientIntTest { submissionEventsFetcher .findFinalizationAndDataSubmissionV3Events( fromL1BlockNumber = BlockParameter.Tag.EARLIEST, - finalizationStartBlockNumber = invalidStartBlockNumber - ).get() + finalizationStartBlockNumber = invalidStartBlockNumber, + ).get(), ) .isNull() } @@ -159,7 +159,7 @@ class LineaSubmissionEventsClientIntTest { submissionEventsFetcher .findFinalizationAndDataSubmissionV3EventsContainingL2BlockNumber( fromL1BlockNumber = BlockParameter.Tag.EARLIEST, - l2BlockNumber = invalidStartBlockNumber + l2BlockNumber = invalidStartBlockNumber, ).get() .also { result -> assertThat(result).isNotNull @@ -169,7 +169,7 @@ class LineaSubmissionEventsClientIntTest { } private fun getExpectedSubmissionEventsFromRecords( - aggregationsAndBlobs: List + aggregationsAndBlobs: List, ): List>> { return aggregationsAndBlobs .filter { it.aggregation != null } @@ -180,7 +180,7 @@ class LineaSubmissionEventsClientIntTest { DataSubmittedV3( parentShnarf = blobsChunk.first().blobCompressionProof!!.prevShnarf, shnarf = blobsChunk.last().expectedShnarf, - finalStateRootHash = blobsChunk.last().blobCompressionProof!!.finalStateRootHash + finalStateRootHash = blobsChunk.last().blobCompressionProof!!.finalStateRootHash, ) } @@ -190,7 +190,7 @@ class LineaSubmissionEventsClientIntTest { endBlockNumber = aggregation.endBlockNumber, shnarf = aggBlobs.last().expectedShnarf, parentStateRootHash = aggBlobs.first().blobCompressionProof!!.parentStateRootHash, - finalStateRootHash = aggBlobs.last().blobCompressionProof!!.finalStateRootHash + finalStateRootHash = aggBlobs.last().blobCompressionProof!!.finalStateRootHash, ) to expectedDataSubmittedEvents } } diff --git a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryAppWithFakeExecutionClientIntTest.kt b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryAppWithFakeExecutionClientIntTest.kt index 3f8be20f..2135732c 100644 --- a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryAppWithFakeExecutionClientIntTest.kt +++ b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryAppWithFakeExecutionClientIntTest.kt @@ -65,12 +65,12 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { blobsResponsesDir = "$testDataDir/compression/responses", aggregationsResponsesDir = "$testDataDir/aggregation/responses", numberOfAggregations = 4, - extraBlobsWithoutAggregation = 0 + extraBlobsWithoutAggregation = 0, ) fakeExecutionLayerClient = FakeExecutionLayerClient( headBlock = BlockNumberAndHash(number = 0uL, hash = ByteArray(32) { 0 }), initialStateRecoverStartBlockNumber = null, - loggerName = "test.fake.clients.l1.fake-execution-layer" + loggerName = "test.fake.clients.l1.fake-execution-layer", ) fakeStateManagerClient = FakeStateManagerClientBasedOnBlobsRecords(blobRecords = aggregationsAndBlobs.flatMap { it.blobs }) @@ -84,7 +84,7 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { l1PollingInterval = 100.milliseconds, l1getLogsChunkSize = 1000u, executionClientPollingInterval = 1.seconds, - smartContractAddress = rollupDeploymentResult.contractAddress + smartContractAddress = rollupDeploymentResult.contractAddress, ) appClients = createAppClients( @@ -93,14 +93,14 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { l1RpcEndpoint = URI(l1RpcUrl), l1RequestRetryConfig = RetryConfig(backoffDelay = 2.seconds), blobScanEndpoint = URI(blobScanUrl), - stateManagerClientEndpoint = URI("http://it-does-not-matter:5432") + stateManagerClientEndpoint = URI("http://it-does-not-matter:5432"), ) contractClientForBlobSubmissions = rollupDeploymentResult.rollupOperatorClient contractClientForAggregationSubmissions = connectToLineaRollupContract( rollupDeploymentResult.contractAddress, rollupDeploymentResult.rollupOperators[1].txManager, - smartContractErrors = lineaRollupContractErrors + smartContractErrors = lineaRollupContractErrors, ) configureLoggers( @@ -113,12 +113,12 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { "test.fake.clients.l1.fake-execution-layer" to Level.DEBUG, "test.clients.l1.web3j-default" to Level.INFO, "test.clients.l1.web3j.receipt-poller" to Level.INFO, - "linea.staterecovery.datafetching" to Level.INFO + "linea.staterecovery.datafetching" to Level.INFO, ) } fun instantiateStateRecoveryApp( - debugForceSyncStopBlockNumber: ULong? = null + debugForceSyncStopBlockNumber: ULong? = null, ): StateRecoveryApp { return StateRecoveryApp( vertx = vertx, @@ -130,15 +130,15 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { blockHeaderStaticFields = BlockHeaderStaticFields.localDev, lineaContractClient = appClients.lineaContractClient, config = appConfigs.copy( - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber - ) + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, + ), ) } private fun submitDataToL1ContactAndWaitExecution( aggregationsAndBlobs: List = this.aggregationsAndBlobs, blobChunksSize: Int = 9, - waitTimeout: Duration = 4.minutes + waitTimeout: Duration = 4.minutes, ) { submitBlobsAndAggregationsAndWaitExecution( contractClientForBlobSubmission = contractClientForBlobSubmissions, @@ -148,8 +148,8 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { waitTimeout = waitTimeout, l1Web3jClient = createWeb3jHttpClient( rpcUrl = l1RpcUrl, - log = LogManager.getLogger("test.clients.l1.web3j.receipt-poller") - ) + log = LogManager.getLogger("test.clients.l1.web3j.receipt-poller"), + ), ) } @@ -162,7 +162,7 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { 2. when state recovery enabled: 2.1 recoveryStartBlockNumber > headBlockNumber: pull for head block number until is reached and start recovery there 2.2 recoveryStartBlockNumber <= headBlockNumber: resume recovery from headBlockNumber - */ + */ @Test fun `when state recovery disabled and is starting from genesis`() { instantiateStateRecoveryApp().start().get() @@ -180,8 +180,8 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { .isEqualTo( StateRecoveryStatus( headBlockNumber = lastAggregation!!.endBlockNumber, - stateRecoverStartBlockNumber = 1UL - ) + stateRecoverStartBlockNumber = 1UL, + ), ) } @@ -204,16 +204,16 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { log.debug( "finalizations={} finalizationToStartRecoveryFrom={}", aggregationsAndBlobs.map { it.aggregation?.intervalString() }, - finalizationToResumeFrom.intervalString() + finalizationToResumeFrom.intervalString(), ) submitDataToL1ContactAndWaitExecution( - aggregationsAndBlobs = finalizationsBeforeCutOff + aggregationsAndBlobs = finalizationsBeforeCutOff, ) fakeExecutionLayerClient.headBlock = BlockNumberAndHash( number = 1UL, - hash = ByteArray(32) { 0 } + hash = ByteArray(32) { 0 }, ) val lastFinalizedBlockNumber = finalizationsBeforeCutOff.last().aggregation!!.endBlockNumber @@ -227,8 +227,8 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { assertThat(fakeExecutionLayerClient.stateRecoverStatus).isEqualTo( StateRecoveryStatus( headBlockNumber = 1UL, - stateRecoverStartBlockNumber = expectedStateRecoverStartBlockNumber - ) + stateRecoverStartBlockNumber = expectedStateRecoverStartBlockNumber, + ), ) log.info("stateRecoverStatus={}", fakeExecutionLayerClient.stateRecoverStatus) } @@ -236,12 +236,12 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { // simulate that execution client has synced up to the last finalized block through P2P network fakeExecutionLayerClient.headBlock = BlockNumberAndHash( number = lastFinalizedBlockNumber, - hash = ByteArray(32) { 0 } + hash = ByteArray(32) { 0 }, ) // continue finalizing the rest of the aggregations submitDataToL1ContactAndWaitExecution( - aggregationsAndBlobs = finalizationsAfterCutOff + aggregationsAndBlobs = finalizationsAfterCutOff, ) val lastAggregation = aggregationsAndBlobs.findLast { it.aggregation != null }!!.aggregation @@ -277,18 +277,18 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { log.debug( "finalizations={} finalizationToStartRecoveryFrom={}", aggregationsAndBlobs.map { it.aggregation?.intervalString() }, - finalizationToResumeFrom.intervalString() + finalizationToResumeFrom.intervalString(), ) submitDataToL1ContactAndWaitExecution( - aggregationsAndBlobs = finalizationsBeforeCutOff + aggregationsAndBlobs = finalizationsBeforeCutOff, ) // set execution layer head block after latest finalization val headBlockNumberAtStart = finalizationsBeforeCutOff.last().aggregation!!.endBlockNumber + 1UL fakeExecutionLayerClient.headBlock = BlockNumberAndHash( number = headBlockNumberAtStart, - hash = ByteArray(32) { 0 } + hash = ByteArray(32) { 0 }, ) instantiateStateRecoveryApp().start().get() await() @@ -298,15 +298,15 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { assertThat(fakeExecutionLayerClient.stateRecoverStatus).isEqualTo( StateRecoveryStatus( headBlockNumber = headBlockNumberAtStart, - stateRecoverStartBlockNumber = headBlockNumberAtStart + 1UL - ) + stateRecoverStartBlockNumber = headBlockNumberAtStart + 1UL, + ), ) log.debug("stateRecoverStatus={}", fakeExecutionLayerClient.stateRecoverStatus) } // continue finalizing the rest of the aggregations submitDataToL1ContactAndWaitExecution( - aggregationsAndBlobs = finalizationsAfterCutOff + aggregationsAndBlobs = finalizationsAfterCutOff, ) val lastAggregation = aggregationsAndBlobs.findLast { it.aggregation != null }!!.aggregation @@ -318,8 +318,8 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { .isEqualTo( StateRecoveryStatus( headBlockNumber = lastAggregation!!.endBlockNumber, - stateRecoverStartBlockNumber = headBlockNumberAtStart + 1UL - ) + stateRecoverStartBlockNumber = headBlockNumberAtStart + 1UL, + ), ) } // assert it does not try to import blocks behind the head block @@ -331,12 +331,12 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { fun `should stop recovery as soon as stateroot mismatches`() { fakeStateManagerClient.setBlockStateRootHash( aggregationsAndBlobs[1].aggregation!!.endBlockNumber, - ByteArray(32) { 1 } + ByteArray(32) { 1 }, ) log.debug( "aggregations={} forcedMismatchAggregation={}", aggregationsAndBlobs.map { it.aggregation?.intervalString() }, - aggregationsAndBlobs[1].aggregation!!.intervalString() + aggregationsAndBlobs[1].aggregation!!.intervalString(), ) val stateRecoverApp = instantiateStateRecoveryApp() @@ -368,7 +368,7 @@ class StateRecoveryAppWithFakeExecutionClientIntTest { log.debug( "headBlockNumber={} forceSyncStopBlockNumber={}", fakeExecutionLayerClient.headBlock.number, - debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber, ) assertThat(fakeExecutionLayerClient.headBlock.number).isGreaterThanOrEqualTo(debugForceSyncStopBlockNumber) } diff --git a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryWithRealBesuAndStateManagerIntTest.kt b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryWithRealBesuAndStateManagerIntTest.kt index 79257475..b12d3b3f 100644 --- a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryWithRealBesuAndStateManagerIntTest.kt +++ b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/StateRecoveryWithRealBesuAndStateManagerIntTest.kt @@ -42,7 +42,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { private val testDataDir = "testdata/coordinator/prover/v3/stateRecovery" private val aggregationsAndBlobs: List = loadBlobsAndAggregationsSortedAndGrouped( blobsResponsesDir = "$testDataDir/compression/responses", - aggregationsResponsesDir = "$testDataDir/aggregation/responses" + aggregationsResponsesDir = "$testDataDir/aggregation/responses", ) private lateinit var rollupDeploymentResult: LineaRollupDeploymentResult private lateinit var contractClientForBlobSubmission: LineaRollupSmartContractClient @@ -54,7 +54,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { fun beforeEach(vertx: Vertx) { val jsonRpcFactory = VertxHttpJsonRpcClientFactory( vertx = vertx, - metricsFacade = MicrometerMetricsFacade(SimpleMeterRegistry()) + metricsFacade = MicrometerMetricsFacade(SimpleMeterRegistry()), ) stateManagerClient = StateManagerV1JsonRpcClient.create( @@ -63,10 +63,10 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { maxInflightRequestsPerClient = 1U, requestRetry = RequestRetryConfig( backoffDelay = 1.seconds, - timeout = 4.seconds + timeout = 4.seconds, ), zkStateManagerVersion = "2.3.0", - logger = LogManager.getLogger("test.clients.l1.state-manager") + logger = LogManager.getLogger("test.clients.l1.state-manager"), ) configureLoggers( @@ -74,7 +74,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { log.name to Level.DEBUG, "net.consensys.linea.contract.Web3JContractAsyncHelper" to Level.WARN, // silence noisy gasPrice Caps logs "test.clients.l1.state-manager" to Level.DEBUG, - "test.clients.l1.web3j-default" to Level.DEBUG + "test.clients.l1.web3j-default" to Level.DEBUG, ) } @@ -90,7 +90,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { rollupDeploymentResult.contractAddress, // index 0 is the first operator in rollupOperatorClient rollupDeploymentResult.rollupOperators[1].txManager, - smartContractErrors = lineaRollupContractErrors + smartContractErrors = lineaRollupContractErrors, ) log.info("starting stack for recovery of state pushed to L1") val staterecoveryNodesStartFuture = execCommandAndAssertSuccess( @@ -98,7 +98,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { "L1_ROLLUP_CONTRACT_ADDRESS=${rollupDeploymentResult.contractAddress} " + "STATERECOVERY_OVERRIDE_START_BLOCK_NUMBER=1", timeout = 1.minutes, - log = log + log = log, ).thenPeek { log.info("make staterecovery-replay-from-block executed") } @@ -114,7 +114,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { blobChunksMaxSize = 9, l1Web3jClient = Web3jClientManager.l1Client, waitTimeout = 4.minutes, - log = log + log = log, ) log.info("finalization={} executed on l1", lastAggregation.intervalString()) } @@ -125,13 +125,13 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { assertBesuAndShomeiRecoveredAsExpected( lastAggregationAndBlobs, - timeout = 5.minutes + timeout = 5.minutes, ) } private fun assertBesuAndShomeiRecoveredAsExpected( targetAggregationAndBlobs: AggregationAndBlobs, - timeout: Duration + timeout: Duration, ) { val targetAggregation = targetAggregationAndBlobs.aggregation!! val expectedZkEndStateRootHash = targetAggregationAndBlobs.blobs.last().blobCompressionProof!!.finalStateRootHash @@ -141,7 +141,7 @@ class StateRecoveryWithRealBesuAndStateManagerIntTest { stateManagerClient = stateManagerClient, targetAggregation.endBlockNumber, expectedZkEndStateRootHash, - timeout = timeout + timeout = timeout, ) } } diff --git a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTaskIntTest.kt b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTaskIntTest.kt index d1fbbe90..14ae1e9c 100644 --- a/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTaskIntTest.kt +++ b/besu-plugins/state-recovery/test-cases/src/integrationTest/kotlin/linea/staterecovery/datafetching/SubmissionsFetchingTaskIntTest.kt @@ -66,7 +66,7 @@ class SubmissionsFetchingTaskIntTest { blobsResponsesDir = "$testDataDir/compression/responses", aggregationsResponsesDir = "$testDataDir/aggregation/responses", numberOfAggregations = 7, - extraBlobsWithoutAggregation = 0 + extraBlobsWithoutAggregation = 0, ) val rollupDeploymentResult = ContractsManager.get() .deployLineaRollup(numberOfOperators = 2, contractVersion = LineaContractVersion.V6).get() @@ -77,14 +77,14 @@ class SubmissionsFetchingTaskIntTest { l1RpcEndpoint = URI(l1RpcUrl), l1RequestRetryConfig = RetryConfig(backoffDelay = 2.seconds), blobScanEndpoint = URI(blobScanUrl), - stateManagerClientEndpoint = URI("http://it-does-not-matter:5432") + stateManagerClientEndpoint = URI("http://it-does-not-matter:5432"), ) contractClientForBlobSubmissions = rollupDeploymentResult.rollupOperatorClient contractClientForAggregationSubmissions = connectToLineaRollupContract( rollupDeploymentResult.contractAddress, rollupDeploymentResult.rollupOperators[1].txManager, - smartContractErrors = lineaRollupContractErrors + smartContractErrors = lineaRollupContractErrors, ) configureLoggers( rootLevel = Level.INFO, @@ -95,7 +95,7 @@ class SubmissionsFetchingTaskIntTest { "linea.plugin.staterecovery.clients" to Level.DEBUG, "test.clients.l1.web3j-default" to Level.INFO, "test.clients.l1.web3j.receipt-poller" to Level.INFO, - "linea.staterecovery.datafetching" to Level.INFO + "linea.staterecovery.datafetching" to Level.INFO, ) submitDataToL1ContactAndWaitExecution() } @@ -103,18 +103,18 @@ class SubmissionsFetchingTaskIntTest { fun createFetcherTask( l2StartBlockNumber: ULong, debugForceSyncStopBlockNumber: ULong? = null, - queuesSizeLimit: Int = 2 + queuesSizeLimit: Int = 2, ): SubmissionsFetchingTask { val l1EventsClient = LineaSubmissionEventsClientImpl( logsSearcher = appClients.ethLogsSearcher, smartContractAddress = appClients.lineaContractClient.contractAddress, l1LatestSearchBlock = BlockParameter.Tag.LATEST, - logsBlockChunkSize = 5000 + logsBlockChunkSize = 5000, ) val blobDecompressor: BlobDecompressorAndDeserializer = BlobDecompressorToDomainV1( decompressor = GoNativeBlobDecompressorFactory.getInstance(BlobDecompressorVersion.V1_2_0), staticFields = BlockHeaderStaticFields.localDev, - vertx = vertx + vertx = vertx, ) return SubmissionsFetchingTask( @@ -129,14 +129,14 @@ class SubmissionsFetchingTaskIntTest { submissionEventsQueueLimit = queuesSizeLimit, compressedBlobsQueueLimit = queuesSizeLimit, targetDecompressedBlobsQueueLimit = queuesSizeLimit, - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, ) } private fun submitDataToL1ContactAndWaitExecution( aggregationsAndBlobs: List = this.aggregationsAndBlobs, blobChunksSize: Int = 9, - waitTimeout: Duration = 4.minutes + waitTimeout: Duration = 4.minutes, ) { submitBlobsAndAggregationsAndWaitExecution( contractClientForBlobSubmission = contractClientForBlobSubmissions, @@ -146,9 +146,9 @@ class SubmissionsFetchingTaskIntTest { waitTimeout = waitTimeout, l1Web3jClient = createWeb3jHttpClient( rpcUrl = l1RpcUrl, - log = LogManager.getLogger("test.clients.l1.web3j.receipt-poller") + log = LogManager.getLogger("test.clients.l1.web3j.receipt-poller"), ), - log = log + log = log, ) } @@ -171,17 +171,17 @@ class SubmissionsFetchingTaskIntTest { assertSubmissionsAreCorrectlyFetched( l2StartBlockNumber = 1UL, - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, ) } private fun assertSubmissionsAreCorrectlyFetched( l2StartBlockNumber: ULong, - debugForceSyncStopBlockNumber: ULong? = null + debugForceSyncStopBlockNumber: ULong? = null, ) { val submissionsFetcher = createFetcherTask( l2StartBlockNumber = l2StartBlockNumber, - queuesSizeLimit = 2 + queuesSizeLimit = 2, ) .also { it.start() } val expectedAggregationsAndBlobsToBeFetched = @@ -208,7 +208,7 @@ class SubmissionsFetchingTaskIntTest { ?.also { nextSubmission -> fetchedSubmissions.add(nextSubmission) submissionsFetcher.pruneQueueForElementsUpToInclusive( - elHeadBlockNumber = nextSubmission.submissionEvents.dataFinalizedEvent.event.endBlockNumber + elHeadBlockNumber = nextSubmission.submissionEvents.dataFinalizedEvent.event.endBlockNumber, ) } assertThat(submissionsFetcher.finalizationsReadyToImport()).isLessThanOrEqualTo(2) @@ -241,11 +241,11 @@ class SubmissionsFetchingTaskIntTest { fun assertFetchedData( fetchedData: SubmissionEventsAndData, - sotAggregationData: AggregationAndBlobs + sotAggregationData: AggregationAndBlobs, ) { assertEventMatchesAggregation( fetchedData.submissionEvents.dataFinalizedEvent.event, - sotAggregationData.aggregation!! + sotAggregationData.aggregation!!, ) assertThat(fetchedData.data.first().header.blockNumber) .isEqualTo(sotAggregationData.blobs.first().startBlockNumber) @@ -255,7 +255,7 @@ class SubmissionsFetchingTaskIntTest { fun assertEventMatchesAggregation( event: DataFinalizedV3, - aggregation: Aggregation + aggregation: Aggregation, ) { assertThat(event.startBlockNumber).isEqualTo(aggregation.startBlockNumber) assertThat(event.endBlockNumber).isEqualTo(aggregation.endBlockNumber) diff --git a/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeExecutionLayerClient.kt b/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeExecutionLayerClient.kt index 2ed5e367..f2c13afc 100644 --- a/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeExecutionLayerClient.kt +++ b/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeExecutionLayerClient.kt @@ -12,7 +12,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class FakeExecutionLayerClient( headBlock: BlockNumberAndHash = BlockNumberAndHash(number = 0uL, hash = ByteArray(32) { 0 }), initialStateRecoverStartBlockNumber: ULong? = null, - loggerName: String? = null + loggerName: String? = null, ) : ExecutionLayerClient { private val log = loggerName ?.let { LogManager.getLogger(loggerName) } @@ -35,7 +35,7 @@ class FakeExecutionLayerClient( val stateRecoverStatus: StateRecoveryStatus get() = StateRecoveryStatus( headBlockNumber = headBlock.number, - stateRecoverStartBlockNumber = stateRecoverStartBlockNumber + stateRecoverStartBlockNumber = stateRecoverStartBlockNumber, ) @Synchronized @@ -46,14 +46,14 @@ class FakeExecutionLayerClient( @Synchronized override fun lineaEngineImportBlocksFromBlob( - blocks: List + blocks: List, ): SafeFuture { if (log.isTraceEnabled) { log.trace("lineaEngineImportBlocksFromBlob($blocks)") } else { val interval = CommonDomainFunctions.blockIntervalString( blocks.first().header.blockNumber, - blocks.last().header.blockNumber + blocks.last().header.blockNumber, ) log.debug("lineaEngineImportBlocksFromBlob(interval=$interval)") } @@ -64,7 +64,7 @@ class FakeExecutionLayerClient( @Synchronized override fun getBlockNumberAndHash( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { log.trace("getBlockNumberAndHash($blockParameter): $headBlock") return SafeFuture.completedFuture(headBlock) @@ -78,7 +78,7 @@ class FakeExecutionLayerClient( @Synchronized override fun lineaEnableStateRecovery( - stateRecoverStartBlockNumber: ULong + stateRecoverStartBlockNumber: ULong, ): SafeFuture { this.stateRecoverStartBlockNumber = stateRecoverStartBlockNumber log.debug("lineaEnableStateRecovery($stateRecoverStartBlockNumber) = $stateRecoverStatus") diff --git a/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeStateManagerClient.kt b/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeStateManagerClient.kt index e2787bd4..2c5d9607 100644 --- a/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeStateManagerClient.kt +++ b/besu-plugins/state-recovery/test-cases/src/main/kotlin/linea/staterecovery/test/FakeStateManagerClient.kt @@ -18,7 +18,7 @@ import java.util.concurrent.ConcurrentHashMap open class FakeStateManagerClient( _blocksStateRootHashes: Map = emptyMap(), - var headBlockNumber: ULong = _blocksStateRootHashes.keys.maxOrNull() ?: 0UL + var headBlockNumber: ULong = _blocksStateRootHashes.keys.maxOrNull() ?: 0UL, ) : StateManagerClientV1 { open val blocksStateRootHashes: MutableMap = ConcurrentHashMap(_blocksStateRootHashes) @@ -33,8 +33,8 @@ open class FakeStateManagerClient( ?.let { SafeFuture.completedFuture(it) } ?: SafeFuture.failedFuture( RuntimeException( - "StateRootHash not found for block=$blockNumber. available blocks: ${blocksStateRootHashes.keys}" - ) + "StateRootHash not found for block=$blockNumber. available blocks: ${blocksStateRootHashes.keys}", + ), ) } @@ -43,7 +43,7 @@ open class FakeStateManagerClient( } override fun rollupGetStateMerkleProofWithTypedError( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture>> { // For state recovery, we just need the endStateRootHash return getStateRootHash(blockInterval.endBlockNumber) @@ -53,26 +53,26 @@ open class FakeStateManagerClient( zkStateMerkleProof = ArrayNode(null), zkParentStateRootHash = ByteArray(32), zkEndStateRootHash = stateRootHash, - zkStateManagerVersion = "fake-version" - ) + zkStateManagerVersion = "fake-version", + ), ) } } } class FakeStateManagerClientBasedOnBlobsRecords( - val blobRecords: List + val blobRecords: List, ) : FakeStateManagerClient( _blocksStateRootHashes = blobRecords - .associate { it.endBlockNumber to it.blobCompressionProof!!.finalStateRootHash } + .associate { it.endBlockNumber to it.blobCompressionProof!!.finalStateRootHash }, ) class FakeStateManagerClientReadFromL1( headBlockNumber: ULong, val logsSearcher: EthLogsSearcher, - val contractAddress: String + val contractAddress: String, ) : FakeStateManagerClient( - headBlockNumber = headBlockNumber + headBlockNumber = headBlockNumber, ) { override fun getStateRootHash(blockNumber: ULong): SafeFuture { @@ -87,8 +87,8 @@ class FakeStateManagerClientReadFromL1( topics = listOf( DataFinalizedV3.topic, null, - blockNumber.toHexStringUInt256() - ) + blockNumber.toHexStringUInt256(), + ), ).thenApply { logs -> logs.firstOrNull()?.let { finalizationLog -> DataFinalizedV3.fromEthLog(finalizationLog).event.finalStateRootHash diff --git a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/ManualTestWithFakeExecutionClient.kt b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/ManualTestWithFakeExecutionClient.kt index 6c81ca60..27ce622d 100644 --- a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/ManualTestWithFakeExecutionClient.kt +++ b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/ManualTestWithFakeExecutionClient.kt @@ -34,7 +34,7 @@ open class TestRunner( private val l1RpcUrl: String, private val blobScanUrl: String, private val blobScanRatelimitBackoffDelay: Duration? = 1.seconds, - private val debugForceSyncStopBlockNumber: ULong = ULong.MAX_VALUE + private val debugForceSyncStopBlockNumber: ULong = ULong.MAX_VALUE, ) { private val log = LogManager.getLogger("test.case.TestRunner") val appConfig = StateRecoveryApp.Config( @@ -45,7 +45,7 @@ open class TestRunner( executionClientPollingInterval = 1.seconds, smartContractAddress = smartContractAddress, l1getLogsChunkSize = 10_000u, - debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber + debugForceSyncStopBlockNumber = debugForceSyncStopBlockNumber, ) val appClients = createAppClients( vertx = vertx, @@ -56,17 +56,17 @@ open class TestRunner( blobScanEndpoint = URI(blobScanUrl), blobScanRequestRetryConfig = RetryConfig(backoffDelay = 10.milliseconds, timeout = 2.minutes), blobscanRequestRateLimitBackoffDelay = blobScanRatelimitBackoffDelay, - stateManagerClientEndpoint = URI("http://it-does-not-matter:5432") + stateManagerClientEndpoint = URI("http://it-does-not-matter:5432"), ) private val fakeExecutionLayerClient = FakeExecutionLayerClient( headBlock = BlockNumberAndHash(number = l2RecoveryStartBlockNumber - 1UL, hash = ByteArray(32) { 0 }), initialStateRecoverStartBlockNumber = l2RecoveryStartBlockNumber, - loggerName = "test.fake.clients.execution-layer" + loggerName = "test.fake.clients.execution-layer", ) var fakeStateManagerClient: StateManagerClientV1 = FakeStateManagerClientReadFromL1( headBlockNumber = ULong.MAX_VALUE, logsSearcher = appClients.ethLogsSearcher, - contractAddress = StateRecoveryApp.Config.lineaSepolia.smartContractAddress + contractAddress = StateRecoveryApp.Config.lineaSepolia.smartContractAddress, ) var stateRecoverApp: StateRecoveryApp = StateRecoveryApp( vertx = vertx, @@ -77,7 +77,7 @@ open class TestRunner( transactionDetailsClient = appClients.transactionDetailsClient, blockHeaderStaticFields = BlockHeaderStaticFields.localDev, lineaContractClient = appClients.lineaContractClient, - config = appConfig + config = appConfig, ) init { @@ -86,12 +86,12 @@ open class TestRunner( "linea.staterecovery" to Level.TRACE, "linea.plugin.staterecovery" to Level.INFO, "linea.plugin.staterecovery.clients.l1.blob-scan" to Level.TRACE, - "linea.plugin.staterecovery.clients.l1.logs-searcher" to Level.INFO + "linea.plugin.staterecovery.clients.l1.logs-searcher" to Level.INFO, ) } fun run( - timeout: kotlin.time.Duration = 10.minutes + timeout: kotlin.time.Duration = 10.minutes, ) { log.info("Running test case") stateRecoverApp.start().get() @@ -113,7 +113,7 @@ fun main() { l2RecoveryStartBlockNumber = 18_504_528UL, l1RpcUrl = "https://mainnet.infura.io/v3/$infuraAppKey", blobScanUrl = "https://api.blobscan.com/", - blobScanRatelimitBackoffDelay = 1.seconds + blobScanRatelimitBackoffDelay = 1.seconds, ) // val sepoliaTestRunner = TestRunner( // l1RpcUrl = "https://sepolia.infura.io/v3/$infuraAppKey", diff --git a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/AssertionsHelper.kt b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/AssertionsHelper.kt index bea921cb..abb6e99d 100644 --- a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/AssertionsHelper.kt +++ b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/AssertionsHelper.kt @@ -19,7 +19,7 @@ import kotlin.time.toJavaDuration fun execCommandAndAssertSuccess( command: String, timeout: Duration = 1.minutes, - log: Logger + log: Logger, ): SafeFuture { return Runner .executeCommandFailOnNonZeroExitCode(command, timeout = timeout, log = log) @@ -35,7 +35,7 @@ fun assertBesuAndShomeiRecoveredAsExpected( stateManagerClient: StateManagerClientV1, expectedBlockNumber: ULong, expectedZkEndStateRootHash: ByteArray, - timeout: Duration = 60.seconds + timeout: Duration = 60.seconds, ) { await() .pollInterval(1.seconds.toJavaDuration()) @@ -53,7 +53,7 @@ fun waitExecutionLayerToBeUpAndRunning( executionLayerUrl: String, expectedHeadBlockNumber: ULong = 0UL, log: Logger, - timeout: Duration = 2.minutes + timeout: Duration = 2.minutes, ) { val web3jElClient = createWeb3jHttpClient(executionLayerUrl) await() diff --git a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/LogEventsFetchHelper.kt b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/LogEventsFetchHelper.kt index f84e33a5..b2fd669b 100644 --- a/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/LogEventsFetchHelper.kt +++ b/besu-plugins/state-recovery/test-cases/src/test/kotlin/linea/staterecovery/test/LogEventsFetchHelper.kt @@ -7,7 +7,7 @@ import linea.staterecovery.DataFinalizedV3 fun getLastFinalizationOnL1( logsSearcher: EthLogsSearcherImpl, - contractAddress: String + contractAddress: String, ): EthLogEvent { return getFinalizationsOnL1(logsSearcher, contractAddress) .lastOrNull() @@ -16,12 +16,12 @@ fun getLastFinalizationOnL1( fun getFinalizationsOnL1( logsSearcher: EthLogsSearcherImpl, - contractAddress: String + contractAddress: String, ): List> { return logsSearcher.getLogs( fromBlock = BlockParameter.Tag.EARLIEST, toBlock = BlockParameter.Tag.LATEST, address = contractAddress, - topics = listOf(DataFinalizedV3.topic) + topics = listOf(DataFinalizedV3.topic), ).get().map(DataFinalizedV3.Companion::fromEthLog) } diff --git a/build.gradle b/build.gradle index 2d57354c..53fd7278 100644 --- a/build.gradle +++ b/build.gradle @@ -118,18 +118,13 @@ allprojects { indentWithSpaces(2) endWithNewline() } - } - // TODO in later ticket - apply these linting rules to all monorepo projects - if (subproject.path.startsWith(':besu-plugins:linea-sequencer')) { - subproject.spotless { - java { - target 'src/**/*.java' - targetExclude '**/src/test/java/**ReferenceTest**', '**/src/main/generated/**', '**/src/test/generated/**', '**/src/jmh/generated/**' - removeUnusedImports() - trimTrailingWhitespace() - endWithNewline() - } + java { + target 'src/**/*.java' + targetExclude '**/src/test/java/**ReferenceTest**', '**/src/main/generated/**', '**/src/test/generated/**', '**/src/jmh/generated/**' + removeUnusedImports() + trimTrailingWhitespace() + endWithNewline() } } } diff --git a/coordinator/app/src/main/kotlin/linea/coordinator/config/ConfigLoader.kt b/coordinator/app/src/main/kotlin/linea/coordinator/config/ConfigLoader.kt index 0bf4a34f..ef327cef 100644 --- a/coordinator/app/src/main/kotlin/linea/coordinator/config/ConfigLoader.kt +++ b/coordinator/app/src/main/kotlin/linea/coordinator/config/ConfigLoader.kt @@ -19,7 +19,7 @@ import org.apache.logging.log4j.Logger import java.nio.file.Path inline fun loadConfigsOrError( - configFiles: List + configFiles: List, ): Result { val confBuilder: ConfigLoaderBuilder = ConfigLoaderBuilder.Companion .empty() @@ -43,7 +43,7 @@ fun logErrorIfPresent( configName: String, configFiles: List, configLoadingResult: Result, - logger: Logger + logger: Logger, ) { if (configLoadingResult is Err) { logger.error("Failed to load $configName from files=$configFiles with error=${configLoadingResult.error}") @@ -53,7 +53,7 @@ fun logErrorIfPresent( inline fun loadConfigsAndLogErrors( configFiles: List, configName: String, - logger: Logger = LogManager.getLogger("linea.coordinator.config") + logger: Logger = LogManager.getLogger("linea.coordinator.config"), ): Result { return loadConfigsOrError(configFiles) .also { logErrorIfPresent(configName, configFiles, it, logger) } @@ -64,7 +64,7 @@ fun loadConfigsOrError( tracesLimitsFileV2: Path, gasPriceCapTimeOfDayMultipliersFile: Path, smartContractErrorsFile: Path, - logger: Logger = LogManager.getLogger("linea.coordinator.config") + logger: Logger = LogManager.getLogger("linea.coordinator.config"), ): Result { val coordinatorBaseConfigs = loadConfigsAndLogErrors(coordinatorConfigFiles, "coordinator", logger) @@ -74,18 +74,18 @@ fun loadConfigsOrError( loadConfigsAndLogErrors( listOf(gasPriceCapTimeOfDayMultipliersFile), "l1 submission gas prices caps", - logger + logger, ) val smartContractErrorsConfig = loadConfigsAndLogErrors( listOf(smartContractErrorsFile), "smart contract errors", - logger + logger, ) val configError = listOf( coordinatorBaseConfigs, tracesLimitsV2Configs, gasPriceCapTimeOfDayMultipliersConfig, - smartContractErrorsConfig + smartContractErrorsConfig, ) .find { it is Err } @@ -98,13 +98,13 @@ fun loadConfigsOrError( val finalConfig = baseConfig.copy( conflation = baseConfig.conflation.copy( _tracesLimitsV2 = tracesLimitsV2Configs.get()?.tracesLimits?.let { TracesCountersV2(it) }, - _smartContractErrors = smartContractErrorsConfig.get()!!.smartContractErrors + _smartContractErrors = smartContractErrorsConfig.get()!!.smartContractErrors, ), l1DynamicGasPriceCapService = baseConfig.l1DynamicGasPriceCapService.copy( gasPriceCapCalculation = baseConfig.l1DynamicGasPriceCapService.gasPriceCapCalculation.copy( - timeOfDayMultipliers = gasPriceCapTimeOfDayMultipliersConfig.get()?.gasPriceCapTimeOfDayMultipliers - ) - ) + timeOfDayMultipliers = gasPriceCapTimeOfDayMultipliersConfig.get()?.gasPriceCapTimeOfDayMultipliers, + ), + ), ) return Ok(finalConfig) } @@ -114,14 +114,14 @@ fun loadConfigs( tracesLimitsFileV2: Path, gasPriceCapTimeOfDayMultipliersFile: Path, smartContractErrorsFile: Path, - logger: Logger = LogManager.getLogger("linea.coordinator.config") + logger: Logger = LogManager.getLogger("linea.coordinator.config"), ): CoordinatorConfig { loadConfigsOrError( coordinatorConfigFiles, tracesLimitsFileV2, gasPriceCapTimeOfDayMultipliersFile, smartContractErrorsFile, - logger + logger, ).let { return it .getOrElse { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/api/Api.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/api/Api.kt index 26b685f9..daeb2d9a 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/api/Api.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/api/Api.kt @@ -6,10 +6,10 @@ import net.consensys.linea.vertx.ObservabilityServer class Api( private val configs: Config, - private val vertx: Vertx + private val vertx: Vertx, ) { data class Config( - val observabilityPort: UInt + val observabilityPort: UInt, ) private var observabilityServerId: String? = null diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/BlockchainClientHelper.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/BlockchainClientHelper.kt index fabbce1e..f3983b72 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/BlockchainClientHelper.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/BlockchainClientHelper.kt @@ -23,7 +23,7 @@ import java.net.URI fun createTransactionManager( vertx: Vertx, signerConfig: SignerConfig, - client: Web3j + client: Web3j, ): AsyncFriendlyTransactionManager { val transactionSignService = when (signerConfig.type) { SignerConfig.Type.Web3j -> { @@ -57,7 +57,7 @@ fun createLineaRollupContractClient( contractGasProvider: ContractGasProvider, web3jClient: Web3j, smartContractErrors: SmartContractErrors, - useEthEstimateGas: Boolean + useEthEstimateGas: Boolean, ): LineaRollupSmartContractClient { return Web3JLineaRollupSmartContractClient.load( contractAddress = l1Config.zkEvmContractAddress, @@ -65,6 +65,6 @@ fun createLineaRollupContractClient( transactionManager = transactionManager, contractGasProvider = contractGasProvider, smartContractErrors = smartContractErrors, - useEthEstimateGas = useEthEstimateGas + useEthEstimateGas = useEthEstimateGas, ) } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorApp.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorApp.kt index 25260af1..752d73c7 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorApp.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorApp.kt @@ -51,20 +51,20 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { vertx = vertx, metricsFacade = MicrometerMetricsFacade(meterRegistry), requestResponseLogLevel = Level.TRACE, - failuresLogLevel = Level.WARN + failuresLogLevel = Level.WARN, ) private val api = Api( Api.Config( - configs.api.observabilityPort + configs.api.observabilityPort, ), - vertx + vertx, ) private val l2Web3jClient: Web3j = createWeb3jHttpClient( rpcUrl = configs.l2.rpcEndpoint.toString(), log = LogManager.getLogger("clients.l2.eth-api.rpc-node"), pollingInterval = 1.seconds, requestResponseLogLevel = Level.TRACE, - failuresLogLevel = Level.DEBUG + failuresLogLevel = Level.DEBUG, ) private val persistenceRetryer = PersistenceRetryer( @@ -72,8 +72,8 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { config = PersistenceRetryer.Config( backoffDelay = configs.persistenceRetry.backoffDelay.toKotlinDuration(), maxRetries = configs.persistenceRetry.maxRetries, - timeout = configs.persistenceRetry.timeout?.toKotlinDuration() - ) + timeout = configs.persistenceRetry.timeout?.toKotlinDuration(), + ), ) private val sqlClient: SqlClient = initDb(configs.database) @@ -81,10 +81,10 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { PostgresBatchesRepository( batchesDao = RetryingBatchesPostgresDao( delegate = BatchesPostgresDao( - connection = sqlClient + connection = sqlClient, ), - persistenceRetryer = persistenceRetryer - ) + persistenceRetryer = persistenceRetryer, + ), ) private val blobsRepository = @@ -92,21 +92,21 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { blobsDao = RetryingBlobsPostgresDao( delegate = BlobsPostgresDao( config = BlobsPostgresDao.Config( - maxBlobsToReturn = configs.blobSubmission.maxBlobsToReturn.toUInt() + maxBlobsToReturn = configs.blobSubmission.maxBlobsToReturn.toUInt(), ), - connection = sqlClient + connection = sqlClient, ), - persistenceRetryer = persistenceRetryer - ) + persistenceRetryer = persistenceRetryer, + ), ) private val aggregationsRepository = AggregationsRepositoryImpl( aggregationsPostgresDao = RetryingPostgresAggregationsDao( delegate = PostgresAggregationsDao( - connection = sqlClient + connection = sqlClient, ), - persistenceRetryer = persistenceRetryer - ) + persistenceRetryer = persistenceRetryer, + ), ) private val l1FeeHistoriesRepository = @@ -116,11 +116,11 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { minBaseFeePerBlobGasToCache = configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.historicBaseFeePerBlobGasLowerBound, fixedAverageRewardToCache = - configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.historicAvgRewardConstant + configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.historicAvgRewardConstant, ), FeeHistoriesPostgresDao( - sqlClient - ) + sqlClient, + ), ) private val l1App = L1DependentApp( @@ -133,7 +133,7 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { aggregationsRepository = aggregationsRepository, l1FeeHistoriesRepository = l1FeeHistoriesRepository, smartContractErrors = configs.conflation.smartContractErrors, - metricsFacade = micrometerMetricsFacade + metricsFacade = micrometerMetricsFacade, ) private val requestFileCleanup = DirectoryCleaner( @@ -144,7 +144,7 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { configs.proversConfig.proverA.proofAggregation.requestsDirectory, configs.proversConfig.proverB?.execution?.requestsDirectory, configs.proversConfig.proverB?.blobCompression?.requestsDirectory, - configs.proversConfig.proverB?.proofAggregation?.requestsDirectory + configs.proversConfig.proverB?.proofAggregation?.requestsDirectory, ), fileFilters = DirectoryCleaner.getSuffixFileFilters( listOfNotNull( @@ -153,9 +153,9 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { configs.proversConfig.proverA.proofAggregation.inprogressRequestWritingSuffix, configs.proversConfig.proverB?.execution?.inprogressRequestWritingSuffix, configs.proversConfig.proverB?.blobCompression?.inprogressRequestWritingSuffix, - configs.proversConfig.proverB?.proofAggregation?.inprogressRequestWritingSuffix - ) - ) + DirectoryCleaner.JSON_FILE_FILTER + configs.proversConfig.proverB?.proofAggregation?.inprogressRequestWritingSuffix, + ), + ) + DirectoryCleaner.JSON_FILE_FILTER, ) init { @@ -176,7 +176,7 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { SafeFuture.allOf( l1App.stop(), SafeFuture.fromRunnable { l2Web3jClient.shutdown() }, - api.stop().toSafeFuture() + api.stop().toSafeFuture(), ).thenApply { LoadBalancingJsonRpcClient.stop() }.thenCompose { @@ -201,7 +201,7 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { database = dbConfig.schema, target = dbVersion, username = dbConfig.username, - password = dbConfig.password.value + password = dbConfig.password.value, ) return Db.vertxSqlClient( vertx = vertx, @@ -211,7 +211,7 @@ class CoordinatorApp(private val configs: CoordinatorConfig) { username = dbConfig.username, password = dbConfig.password.value, maxPoolSize = dbConfig.transactionalPoolSize, - pipeliningLimit = dbConfig.readPipeliningLimit + pipeliningLimit = dbConfig.readPipeliningLimit, ) } } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppCli.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppCli.kt index c8a5d7d7..7fcba128 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppCli.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppCli.kt @@ -20,7 +20,7 @@ import java.util.concurrent.Callable synopsisHeading = "%n", descriptionHeading = "%nDescription:%n%n", optionListHeading = "%nOptions:%n", - footerHeading = "%n" + footerHeading = "%n", ) class CoordinatorAppCli internal constructor(private val errorWriter: PrintWriter, private val startAction: StartAction) : @@ -32,7 +32,7 @@ internal constructor(private val errorWriter: PrintWriter, private val startActi names = ["--traces-limits-v2"], paramLabel = "", description = ["Prover traces limits for linea besu"], - arity = "1" + arity = "1", ) private val tracesLimitsV2File: File? = null @@ -40,27 +40,24 @@ internal constructor(private val errorWriter: PrintWriter, private val startActi names = ["--smart-contract-errors"], paramLabel = "", description = ["Smart contract error codes"], - arity = "1" + arity = "1", ) - private val smartContractErrorsFile: File? = null @CommandLine.Option( names = ["--gas-price-cap-time-of-day-multipliers"], paramLabel = "", description = ["Time-of-day multipliers for calculation of L1 dynamic gas price caps"], - arity = "1" + arity = "1", ) - private val gasPriceCapTimeOfDayMultipliersFile: File? = null @CommandLine.Option( names = ["--check-configs-only"], paramLabel = "", description = ["Validates configuration files only, without starting the application."], - arity = "0..1" + arity = "0..1", ) - private var checkConfigsOnly: Boolean = false override fun call(): Int { @@ -97,7 +94,7 @@ internal constructor(private val errorWriter: PrintWriter, private val startActi tracesLimitsFileV2 = tracesLimitsV2File.toPath(), smartContractErrorsFile = smartContractErrorsFile.toPath(), gasPriceCapTimeOfDayMultipliersFile = gasPriceCapTimeOfDayMultipliersFile.toPath(), - logger = logger + logger = logger, ) if (checkConfigsOnly) { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppMain.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppMain.kt index 348e895a..829cb984 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppMain.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/CoordinatorAppMain.kt @@ -39,7 +39,7 @@ class CoordinatorAppMain { // Messages in App.stop won't appear in the logs Configurator.shutdown(LogManager.getContext() as LoggerContext) } - } + }, ) app.start() } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L1DependentApp.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L1DependentApp.kt index 948f4e1e..bf6d893f 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L1DependentApp.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L1DependentApp.kt @@ -116,7 +116,7 @@ class L1DependentApp( private val aggregationsRepository: AggregationsRepository, l1FeeHistoriesRepository: FeeHistoriesRepositoryWithCache, private val smartContractErrors: SmartContractErrors, - private val metricsFacade: MetricsFacade + private val metricsFacade: MetricsFacade, ) : LongRunningService { private val log = LogManager.getLogger(this::class.java) @@ -132,13 +132,13 @@ class L1DependentApp( private val l2TransactionManager = createTransactionManager( vertx, configs.l2Signer, - l2Web3jClient + l2Web3jClient, ) private val l1Web3jClient = createWeb3jHttpClient( rpcUrl = configs.l1.rpcEndpoint.toString(), log = LogManager.getLogger("clients.l1.eth-api"), - pollingInterval = 1.seconds + pollingInterval = 1.seconds, ) private val l1Web3jService = Web3jBlobExtended(HttpService(configs.l1.ethFeeHistoryEndpoint.toString())) @@ -147,7 +147,7 @@ class L1DependentApp( private val proverClientFactory = ProverClientFactory( vertx = vertx, config = configs.proversConfig, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) private val l2ExtendedWeb3j = ExtendedWeb3JImpl(l2Web3jClient) @@ -155,32 +155,32 @@ class L1DependentApp( private val finalizationTransactionManager = createTransactionManager( vertx, configs.finalizationSigner, - l1Web3jClient + l1Web3jClient, ) private val l1MinPriorityFeeCalculator: FeesCalculator = WMAFeesCalculator( WMAFeesCalculator.Config( baseFeeCoefficient = 0.0, - priorityFeeWmaCoefficient = 1.0 - ) + priorityFeeWmaCoefficient = 1.0, + ), ) private val l1DataSubmissionPriorityFeeCalculator: FeesCalculator = BoundableFeeCalculator( BoundableFeeCalculator.Config( feeUpperBound = configs.blobSubmission.priorityFeePerGasUpperBound.toDouble(), feeLowerBound = configs.blobSubmission.priorityFeePerGasLowerBound.toDouble(), - feeMargin = 0.0 + feeMargin = 0.0, ), - l1MinPriorityFeeCalculator + l1MinPriorityFeeCalculator, ) private val l1FinalizationPriorityFeeCalculator: FeesCalculator = BoundableFeeCalculator( BoundableFeeCalculator.Config( feeUpperBound = configs.l1.maxPriorityFeePerGasCap.toDouble() * configs.l1.gasPriceCapMultiplierForFinalization, feeLowerBound = 0.0, - feeMargin = 0.0 + feeMargin = 0.0, ), - l1MinPriorityFeeCalculator + l1MinPriorityFeeCalculator, ) private val feesFetcher: FeesFetcher = FeeHistoryFetcherImpl( @@ -188,13 +188,13 @@ class L1DependentApp( l1Web3jService, FeeHistoryFetcherImpl.Config( configs.l1.feeHistoryBlockCount.toUInt(), - configs.l1.feeHistoryRewardPercentile - ) + configs.l1.feeHistoryRewardPercentile, + ), ) private val lineaRollupClient: LineaRollupSmartContractClientReadOnly = Web3JLineaRollupSmartContractClientReadOnly( contractAddress = configs.l1.zkEvmContractAddress, - web3j = l1Web3jClient + web3j = l1Web3jClient, ) private val l1FinalizationMonitor = run { @@ -202,11 +202,11 @@ class L1DependentApp( config = FinalizationMonitorImpl.Config( pollingInterval = configs.l1.finalizationPollingInterval.toKotlinDuration(), - l1QueryBlockTag = configs.l1.l1QueryBlockTag + l1QueryBlockTag = configs.l1.l1QueryBlockTag, ), contract = lineaRollupClient, l2Client = l2Web3jClient, - vertx = vertx + vertx = vertx, ) } @@ -215,7 +215,7 @@ class L1DependentApp( httpJsonRpcClientFactory = httpJsonRpcClientFactory, lineaRollupClient = lineaRollupClient, l2Web3jClient = l2Web3jClient, - vertx = vertx + vertx = vertx, ) private val gasPriceCapProvider = @@ -246,11 +246,11 @@ class L1DependentApp( finalizationTargetMaxDelay = configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.finalizationTargetMaxDelay.toKotlinDuration(), gasPriceCapsCoefficient = - configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.gasPriceCapsCheckCoefficient + configs.l1DynamicGasPriceCapService.gasPriceCapCalculation.gasPriceCapsCheckCoefficient, ), l2ExtendedWeb3JClient = l2ExtendedWeb3j, feeHistoriesRepository = l1FeeHistoriesRepository, - gasPriceCapCalculator = l1GasPriceCapCalculator + gasPriceCapCalculator = l1GasPriceCapCalculator, ) } else { null @@ -261,10 +261,10 @@ class L1DependentApp( config = GasPriceCapProviderForDataSubmission.Config( maxPriorityFeePerGasCap = configs.l1.maxPriorityFeePerGasCap, maxFeePerGasCap = configs.l1.maxFeePerGasCap, - maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap + maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap, ), gasPriceCapProvider = gasPriceCapProvider!!, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) } else { null @@ -275,10 +275,10 @@ class L1DependentApp( config = GasPriceCapProviderForFinalization.Config( maxPriorityFeePerGasCap = configs.l1.maxPriorityFeePerGasCap, maxFeePerGasCap = configs.l1.maxFeePerGasCap, - gasPriceCapMultiplier = configs.l1.gasPriceCapMultiplierForFinalization + gasPriceCapMultiplier = configs.l1.gasPriceCapMultiplierForFinalization, ), gasPriceCapProvider = gasPriceCapProvider!!, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) } else { null @@ -287,11 +287,11 @@ class L1DependentApp( private val lastFinalizedBlock = lastFinalizedBlock().get() private val lastProcessedBlockNumber = resumeConflationFrom( aggregationsRepository, - lastFinalizedBlock + lastFinalizedBlock, ).get() private val lastConsecutiveAggregatedBlockNumber = resumeAggregationFrom( aggregationsRepository, - lastFinalizedBlock + lastFinalizedBlock, ).get() private fun createDeadlineConflationCalculatorRunner(): DeadlineConflationCalculatorRunner { @@ -301,15 +301,15 @@ class L1DependentApp( config = ConflationCalculatorByTimeDeadline.Config( conflationDeadline = configs.conflation.conflationDeadline.toKotlinDuration(), conflationDeadlineLastBlockConfirmationDelay = - configs.conflation.conflationDeadlineLastBlockConfirmationDelay.toKotlinDuration() + configs.conflation.conflationDeadlineLastBlockConfirmationDelay.toKotlinDuration(), ), lastBlockNumber = lastProcessedBlockNumber, clock = Clock.System, latestBlockProvider = GethCliqueSafeBlockProvider( l2ExtendedWeb3j.web3jClient, - GethCliqueSafeBlockProvider.Config(configs.l2.blocksToFinalization.toLong()) - ) - ) + GethCliqueSafeBlockProvider.Config(configs.l2.blocksToFinalization.toLong()), + ), + ), ) } @@ -320,8 +320,8 @@ class L1DependentApp( if (configs.conflation.blocksLimit != null) { calculators.add( ConflationCalculatorByBlockLimit( - blockLimit = configs.conflation.blocksLimit.toUInt() - ) + blockLimit = configs.conflation.blocksLimit.toUInt(), + ), ) } } @@ -330,15 +330,15 @@ class L1DependentApp( if (configs.conflation.conflationTargetEndBlockNumbers.isNotEmpty()) { calculators.add( ConflationCalculatorByTargetBlockNumbers( - targetEndBlockNumbers = configs.conflation.conflationTargetEndBlockNumbers - ) + targetEndBlockNumbers = configs.conflation.conflationTargetEndBlockNumbers, + ), ) } } private fun createCalculatorsForBlobsAndConflation( logger: Logger, - compressedBlobCalculator: ConflationCalculatorByDataCompressed + compressedBlobCalculator: ConflationCalculatorByDataCompressed, ): List { val calculators: MutableList = mutableListOf( @@ -346,9 +346,9 @@ class L1DependentApp( tracesCountersLimit = configs.conflation.tracesLimitsV2, emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, metricsFacade = metricsFacade, - log = logger + log = logger, ), - compressedBlobCalculator + compressedBlobCalculator, ) addBlocksLimitCalculatorIfDefined(calculators) addTargetEndBlockConflationCalculatorIfDefined(calculators) @@ -363,18 +363,18 @@ class L1DependentApp( val blobCompressor = GoBackedBlobCompressor.getInstance( compressorVersion = compressorVersion, dataLimit = configs.blobCompression.blobSizeLimit.toUInt(), - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) val compressedBlobCalculator = ConflationCalculatorByDataCompressed( - blobCompressor = blobCompressor + blobCompressor = blobCompressor, ) val globalCalculator = GlobalBlockConflationCalculator( lastBlockNumber = lastProcessedBlockNumber, syncCalculators = createCalculatorsForBlobsAndConflation(logger, compressedBlobCalculator), deferredTriggerConflationCalculators = listOf(deadlineConflationCalculatorRunnerNew), emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, - log = logger + log = logger, ) val batchesLimit = @@ -384,7 +384,7 @@ class L1DependentApp( conflationCalculator = globalCalculator, blobCalculator = compressedBlobCalculator, metricsFacade = metricsFacade, - batchesLimit = batchesLimit + batchesLimit = batchesLimit, ) } private val conflationService: ConflationService = @@ -396,7 +396,7 @@ class L1DependentApp( maxInflightRequestsPerClient = configs.stateManager.requestLimitPerEndpoint, requestRetry = configs.stateManager.requestRetryConfig, zkStateManagerVersion = configs.stateManager.version, - logger = LogManager.getLogger("clients.StateManagerShomeiClient") + logger = LogManager.getLogger("clients.StateManagerShomeiClient"), ) private val lineaSmartContractClientForDataSubmission: LineaRollupSmartContractClient = run { @@ -411,26 +411,26 @@ class L1DependentApp( gasLimit = configs.l1.gasLimit, maxFeePerGasCap = configs.l1.maxFeePerGasCap, maxPriorityFeePerGasCap = configs.l1.maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap, + ), ) createLineaRollupContractClient( l1Config = configs.l1, transactionManager = createTransactionManager( vertx, configs.dataSubmissionSigner, - l1Web3jClient + l1Web3jClient, ), contractGasProvider = primaryOrFallbackGasProvider, web3jClient = l1Web3jClient, smartContractErrors = smartContractErrors, - useEthEstimateGas = configs.blobSubmission.useEthEstimateGas + useEthEstimateGas = configs.blobSubmission.useEthEstimateGas, ) } private val genesisStateProvider = GenesisStateProvider( configs.l1.genesisStateRootHash, - configs.l1.genesisShnarfV6 + configs.l1.genesisShnarfV6, ) private val blobCompressionProofCoordinator = run { @@ -440,14 +440,14 @@ class L1DependentApp( category = LineaMetricsCategory.BLOB, name = "proven.highest.block.number", description = "Highest proven blob compression block number", - measurementSupplier = highestProvenBlobTracker + measurementSupplier = highestProvenBlobTracker, ) highestProvenBlobTracker } val blobCompressionProofHandler: (BlobCompressionProofUpdate) -> SafeFuture<*> = SimpleCompositeSafeFutureHandler( listOf( - maxProvenBlobCache - ) + maxProvenBlobCache, + ), ) val blobCompressionProofCoordinator = BlobCompressionProofCoordinator( @@ -457,33 +457,33 @@ class L1DependentApp( rollingBlobShnarfCalculator = RollingBlobShnarfCalculator( blobShnarfCalculator = GoBackedBlobShnarfCalculator( version = ShnarfCalculatorVersion.V1_2, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ), blobsRepository = blobsRepository, - genesisShnarf = genesisStateProvider.shnarf + genesisShnarf = genesisStateProvider.shnarf, ), blobZkStateProvider = BlobZkStateProviderImpl( - zkStateClient = zkStateClient + zkStateClient = zkStateClient, ), config = BlobCompressionProofCoordinator.Config( - pollingInterval = configs.blobCompression.handlerPollingInterval.toKotlinDuration() + pollingInterval = configs.blobCompression.handlerPollingInterval.toKotlinDuration(), ), blobCompressionProofHandler = blobCompressionProofHandler, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) val highestUnprovenBlobTracker = HighestUnprovenBlobTracker(lastProcessedBlockNumber) metricsFacade.createGauge( category = LineaMetricsCategory.BLOB, name = "unproven.highest.block.number", description = "Block number of highest unproven blob produced", - measurementSupplier = highestUnprovenBlobTracker + measurementSupplier = highestUnprovenBlobTracker, ) val compositeSafeFutureHandler = SimpleCompositeSafeFutureHandler( listOf( blobCompressionProofCoordinator::handleBlob, - highestUnprovenBlobTracker - ) + highestUnprovenBlobTracker, + ), ) conflationCalculator.onBlobCreation(compositeSafeFutureHandler) blobCompressionProofCoordinator @@ -494,14 +494,14 @@ class L1DependentApp( category = LineaMetricsCategory.BLOB, name = "highest.accepted.block.number", description = "Highest accepted blob end block number", - measurementSupplier = it + measurementSupplier = it, ) } private val alreadySubmittedBlobsFilter = L1ShnarfBasedAlreadySubmittedBlobsFilter( lineaRollup = lineaSmartContractClientForDataSubmission, - acceptedBlobEndBlockNumberConsumer = { highestAcceptedBlobTracker(it) } + acceptedBlobEndBlockNumberConsumer = { highestAcceptedBlobTracker(it) }, ) private val latestBlobSubmittedBlockNumberTracker = LatestBlobSubmittedBlockNumberTracker(0UL) @@ -513,14 +513,14 @@ class L1DependentApp( category = LineaMetricsCategory.BLOB, name = "highest.submitted.on.l1", description = "Highest submitted blob end block number on l1", - measurementSupplier = { latestBlobSubmittedBlockNumberTracker.get() } + measurementSupplier = { latestBlobSubmittedBlockNumberTracker.get() }, ) val blobSubmissionDelayHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "submission.delay", description = "Delay between blob submission and end block timestamps", - baseUnit = "seconds" + baseUnit = "seconds", ) val blobSubmittedEventConsumers: Map, String> = mapOf( @@ -529,7 +529,7 @@ class L1DependentApp( } to "Submitted Blob Tracker Consumer", Consumer { blobSubmission -> blobSubmissionDelayHistogram.record(blobSubmission.getSubmissionDelay().toDouble()) - } to "Blob Submission Delay Consumer" + } to "Blob Submission Delay Consumer", ) BlobSubmissionCoordinator.create( @@ -537,7 +537,7 @@ class L1DependentApp( configs.blobSubmission.dbPollingInterval.toKotlinDuration(), configs.blobSubmission.proofSubmissionDelay.toKotlinDuration(), configs.blobSubmission.maxBlobsToSubmitPerTick.toUInt(), - configs.blobSubmission.targetBlobsToSendPerTransaction.toUInt() + configs.blobSubmission.targetBlobsToSendPerTransaction.toUInt(), ), blobsRepository = blobsRepository, aggregationsRepository = aggregationsRepository, @@ -546,7 +546,7 @@ class L1DependentApp( alreadySubmittedBlobsFilter = alreadySubmittedBlobsFilter, blobSubmittedEventDispatcher = EventDispatcher(blobSubmittedEventConsumers), vertx = vertx, - clock = Clock.System + clock = Clock.System, ) } } @@ -554,14 +554,14 @@ class L1DependentApp( private val proofAggregationCoordinatorService: LongRunningService = run { val maxBlobEndBlockNumberTracker = ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker( aggregationsRepository, - lastProcessedBlockNumber + lastProcessedBlockNumber, ) metricsFacade.createGauge( category = LineaMetricsCategory.BLOB, name = "proven.highest.consecutive.block.number", description = "Highest consecutive proven blob compression block number", - measurementSupplier = maxBlobEndBlockNumberTracker + measurementSupplier = maxBlobEndBlockNumberTracker, ) val highestAggregationTracker = HighestULongTracker(lastProcessedBlockNumber) @@ -569,7 +569,7 @@ class L1DependentApp( category = LineaMetricsCategory.AGGREGATION, name = "proven.highest.block.number", description = "Highest proven aggregation block number", - measurementSupplier = highestAggregationTracker + measurementSupplier = highestAggregationTracker, ) ProofAggregationCoordinatorService @@ -581,7 +581,7 @@ class L1DependentApp( aggregationDeadline = configs.proofAggregation.aggregationDeadline.toKotlinDuration(), latestBlockProvider = GethCliqueSafeBlockProvider( l2ExtendedWeb3j.web3jClient, - GethCliqueSafeBlockProvider.Config(configs.l2.blocksToFinalization.toLong()) + GethCliqueSafeBlockProvider.Config(configs.l2.blocksToFinalization.toLong()), ), maxProofsPerAggregation = configs.proofAggregation.aggregationProofsLimit.toUInt(), startBlockNumberInclusive = lastConsecutiveAggregatedBlockNumber + 1u, @@ -592,9 +592,9 @@ class L1DependentApp( l2Web3jClient, requestRetryConfig = linea.domain.RetryConfig( backoffDelay = 1.seconds, - failuresWarningThreshold = 3u + failuresWarningThreshold = 3u, ), - vertx = vertx + vertx = vertx, ), l2MessageService = Web3JL2MessageServiceSmartContractClient.create( web3jClient = l2Web3jClient, @@ -605,13 +605,13 @@ class L1DependentApp( feeHistoryRewardPercentile = configs.l2.feeHistoryRewardPercentile, transactionManager = l2TransactionManager, smartContractErrors = smartContractErrors, - smartContractDeploymentBlockNumber = configs.l2.messageServiceDeploymentBlockNumber + smartContractDeploymentBlockNumber = configs.l2.messageServiceDeploymentBlockNumber, ), aggregationDeadlineDelay = configs.conflation.conflationDeadlineLastBlockConfirmationDelay.toKotlinDuration(), targetEndBlockNumbers = configs.proofAggregation.targetEndBlocks, metricsFacade = metricsFacade, provenAggregationEndBlockNumberConsumer = { highestAggregationTracker(it) }, - aggregationSizeMultipleOf = configs.proofAggregation.aggregationSizeMultipleOf.toUInt() + aggregationSizeMultipleOf = configs.proofAggregation.aggregationSizeMultipleOf.toUInt(), ) } @@ -636,8 +636,8 @@ class L1DependentApp( configs.l1.maxPriorityFeePerGasCap.toDouble() * configs.l1.gasPriceCapMultiplierForFinalization ).toULong(), - maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = configs.l1.maxFeePerBlobGasCap, + ), ) val lineaSmartContractClientForFinalization: LineaRollupSmartContractClient = createLineaRollupContractClient( l1Config = configs.l1, @@ -645,7 +645,7 @@ class L1DependentApp( contractGasProvider = primaryOrFallbackGasProvider, web3jClient = l1Web3jClient, smartContractErrors = smartContractErrors, - useEthEstimateGas = configs.aggregationFinalization.useEthEstimateGas + useEthEstimateGas = configs.aggregationFinalization.useEthEstimateGas, ) val latestFinalizationSubmittedBlockNumberTracker = LatestFinalizationSubmittedBlockNumberTracker(0UL) @@ -653,14 +653,14 @@ class L1DependentApp( category = LineaMetricsCategory.AGGREGATION, name = "highest.submitted.on.l1", description = "Highest submitted finalization end block number on l1", - measurementSupplier = { latestFinalizationSubmittedBlockNumberTracker.get() } + measurementSupplier = { latestFinalizationSubmittedBlockNumberTracker.get() }, ) val finalizationSubmissionDelayHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.AGGREGATION, name = "submission.delay", description = "Delay between finalization submission and end block timestamps", - baseUnit = "seconds" + baseUnit = "seconds", ) val submittedFinalizationConsumers: Map, String> = mapOf( @@ -669,13 +669,13 @@ class L1DependentApp( } to "Finalization Submission Consumer", Consumer { finalizationSubmission -> finalizationSubmissionDelayHistogram.record(finalizationSubmission.getSubmissionDelay().toDouble()) - } to "Finalization Submission Delay Consumer" + } to "Finalization Submission Delay Consumer", ) AggregationFinalizationCoordinator.create( config = AggregationFinalizationCoordinator.Config( configs.aggregationFinalization.dbPollingInterval.toKotlinDuration(), - configs.aggregationFinalization.proofSubmissionDelay.toKotlinDuration() + configs.aggregationFinalization.proofSubmissionDelay.toKotlinDuration(), ), aggregationsRepository = aggregationsRepository, blobsRepository = blobsRepository, @@ -684,10 +684,10 @@ class L1DependentApp( aggregationSubmitter = AggregationSubmitterImpl( lineaRollup = lineaSmartContractClientForFinalization, gasPriceCapProvider = gasPriceCapProviderForFinalization, - aggregationSubmittedEventConsumer = EventDispatcher(submittedFinalizationConsumers) + aggregationSubmittedEventConsumer = EventDispatcher(submittedFinalizationConsumers), ), vertx = vertx, - clock = Clock.System + clock = Clock.System, ) } } @@ -702,13 +702,13 @@ class L1DependentApp( rpcClient = httpJsonRpcClientFactory.createWithLoadBalancing( endpoints = tracesCounterV2Config.endpoints.toSet(), maxInflightRequestsPerClient = tracesCounterV2Config.requestLimitPerEndpoint, - log = tracesCountersLog + log = tracesCountersLog, ), config = TracesGeneratorJsonRpcClientV2.Config( - expectedTracesApiVersion = expectedTracesApiVersionV2 + expectedTracesApiVersion = expectedTracesApiVersionV2, ), retryConfig = tracesCounterV2Config.requestRetryConfig, - log = tracesCountersLog + log = tracesCountersLog, ) } @@ -721,13 +721,13 @@ class L1DependentApp( rpcClient = httpJsonRpcClientFactory.createWithLoadBalancing( endpoints = tracesConflationConfigV2.endpoints.toSet(), maxInflightRequestsPerClient = tracesConflationConfigV2.requestLimitPerEndpoint, - log = tracesConflationLog + log = tracesConflationLog, ), config = TracesGeneratorJsonRpcClientV2.Config( - expectedTracesApiVersion = expectedTracesApiVersionV2 + expectedTracesApiVersion = expectedTracesApiVersionV2, ), retryConfig = tracesConflationConfigV2.requestRetryConfig, - log = tracesConflationLog + log = tracesConflationLog, ) } @@ -738,7 +738,7 @@ class L1DependentApp( category = LineaMetricsCategory.BATCH, name = "proven.highest.block.number", description = "Highest proven batch execution block number", - measurementSupplier = highestProvenBatchTracker + measurementSupplier = highestProvenBatchTracker, ) highestProvenBatchTracker } @@ -746,12 +746,12 @@ class L1DependentApp( val batchProofHandler = SimpleCompositeSafeFutureHandler( listOf( maxProvenBatchCache, - BatchProofHandlerImpl(batchesRepository)::acceptNewBatch - ) + BatchProofHandlerImpl(batchesRepository)::acceptNewBatch, + ), ) val executionProverClient: ExecutionProverClientV2 = proverClientFactory.executionProverClient( tracesVersion = configs.traces.rawExecutionTracesVersion, - stateManagerVersion = configs.stateManager.version + stateManagerVersion = configs.stateManager.version, ) val proofGeneratingConflationHandlerImpl = ProofGeneratingConflationHandlerImpl( @@ -762,15 +762,15 @@ class L1DependentApp( web3jClient = l2Web3jClient, requestRetryConfig = linea.domain.RetryConfig( backoffDelay = 1.seconds, - failuresWarningThreshold = 3u + failuresWarningThreshold = 3u, ), - vertx = vertx + vertx = vertx, ), - messageServiceAddress = configs.l2.messageServiceAddress + messageServiceAddress = configs.l2.messageServiceAddress, ), batchProofHandler = batchProofHandler, vertx = vertx, - config = ProofGeneratingConflationHandlerImpl.Config(5.seconds) + config = ProofGeneratingConflationHandlerImpl.Config(5.seconds), ) val highestConflationTracker = HighestConflationTracker(lastProcessedBlockNumber) @@ -778,12 +778,12 @@ class L1DependentApp( category = LineaMetricsCategory.CONFLATION, name = "last.block.number", description = "Last conflated block number", - measurementSupplier = highestConflationTracker + measurementSupplier = highestConflationTracker, ) val conflationsCounter = metricsFacade.createCounter( category = LineaMetricsCategory.CONFLATION, name = "counter", - description = "Counter of new conflations" + description = "Counter of new conflations", ) SimpleCompositeSafeFutureHandler( @@ -793,8 +793,8 @@ class L1DependentApp( { conflationsCounter.increment() SafeFuture.COMPLETE - } - ) + }, + ), ) } @@ -804,20 +804,20 @@ class L1DependentApp( conflationService = conflationService, tracesCountersClient = tracesCountersClient, vertx = vertx, - encoder = BlockRLPEncoder + encoder = BlockRLPEncoder, ) } private val lastProvenBlockNumberProvider = run { val lastProvenConsecutiveBatchBlockNumberProvider = BatchesRepoBasedLastProvenBlockNumberProvider( lastProcessedBlockNumber.toLong(), - batchesRepository + batchesRepository, ) metricsFacade.createGauge( category = LineaMetricsCategory.BATCH, name = "proven.highest.consecutive.block.number", description = "Highest proven consecutive execution batch block number", - measurementSupplier = { lastProvenConsecutiveBatchBlockNumberProvider.getLastKnownProvenBlockNumber() } + measurementSupplier = { lastProvenConsecutiveBatchBlockNumberProvider.getLastKnownProvenBlockNumber() }, ) lastProvenConsecutiveBatchBlockNumberProvider } @@ -837,8 +837,8 @@ class L1DependentApp( // We need to add 1 to l2InclusiveBlockNumberToStopAndFlushAggregation because conflation calculator requires // block_number = l2InclusiveBlockNumberToStopAndFlushAggregation + 1 to trigger conflation at // l2InclusiveBlockNumberToStopAndFlushAggregation - lastL2BlockNumberToProcessInclusive = configs.l2InclusiveBlockNumberToStopAndFlushAggregation?.let { it + 1uL } - ) + lastL2BlockNumberToProcessInclusive = configs.l2InclusiveBlockNumberToStopAndFlushAggregation?.let { it + 1uL }, + ), ) blockCreationMonitor } @@ -847,7 +847,7 @@ class L1DependentApp( val l1BasedLastFinalizedBlockProvider = L1BasedLastFinalizedBlockProvider( vertx, lineaRollupClient, - configs.conflation.consistentNumberOfBlocksOnL1ToWait.toUInt() + configs.conflation.consistentNumberOfBlocksOnL1ToWait.toUInt(), ) return l1BasedLastFinalizedBlockProvider.getLastFinalizedBlock() } @@ -867,12 +867,12 @@ class L1DependentApp( l2HighestBlockTag = configs.messageAnchoring.l2HighestBlockTag, anchoringTickInterval = configs.messageAnchoring.anchoringTickInterval, messageQueueCapacity = configs.messageAnchoring.messageQueueCapacity, - maxMessagesToAnchorPerL2Transaction = configs.messageAnchoring.maxMessagesToAnchorPerL2Transaction + maxMessagesToAnchorPerL2Transaction = configs.messageAnchoring.maxMessagesToAnchorPerL2Transaction, ), l1EthApiClient = createEthApiClient( web3jClient = l1Web3jClient, requestRetryConfig = null, - vertx = vertx + vertx = vertx, ), l2MessageService = Web3JL2MessageServiceSmartContractClient.create( web3jClient = l2Web3jClient, @@ -883,8 +883,8 @@ class L1DependentApp( feeHistoryRewardPercentile = configs.l2.feeHistoryRewardPercentile, transactionManager = l2TransactionManager, smartContractErrors = smartContractErrors, - smartContractDeploymentBlockNumber = configs.l2.messageServiceDeploymentBlockNumber - ) + smartContractDeploymentBlockNumber = configs.l2.messageServiceDeploymentBlockNumber, + ), ) } else { DisabledLongRunningService @@ -897,7 +897,7 @@ class L1DependentApp( httpJsonRpcClientFactory = httpJsonRpcClientFactory, l1Web3jClient = l1Web3jClient, l1Web3jService = l1Web3jService, - config = configs.l2NetworkGasPricingService + config = configs.l2NetworkGasPricingService, ) } else { null @@ -916,16 +916,16 @@ class L1DependentApp( val l1FeeHistoryWeb3jBlobExtClient = Web3jBlobExtended( HttpService( configs.l1DynamicGasPriceCapService.feeHistoryFetcher.endpoint?.toString() - ?: configs.l1.ethFeeHistoryEndpoint.toString() - ) + ?: configs.l1.ethFeeHistoryEndpoint.toString(), + ), ) val l1FeeHistoryFetcher: GasPriceCapFeeHistoryFetcher = GasPriceCapFeeHistoryFetcherImpl( web3jService = l1FeeHistoryWeb3jBlobExtClient, config = GasPriceCapFeeHistoryFetcherImpl.Config( maxBlockCount = configs.l1DynamicGasPriceCapService.feeHistoryFetcher.maxBlockCount, - rewardPercentiles = configs.l1DynamicGasPriceCapService.feeHistoryFetcher.rewardPercentiles - ) + rewardPercentiles = configs.l1DynamicGasPriceCapService.feeHistoryFetcher.rewardPercentiles, + ), ) FeeHistoryCachingService( @@ -939,12 +939,12 @@ class L1DependentApp( feeHistoryStoragePeriodInBlocks = feeHistoryStoragePeriodInBlocks, feeHistoryWindowInBlocks = feeHistoryPercentileWindowInBlocks, numOfBlocksBeforeLatest = - configs.l1DynamicGasPriceCapService.feeHistoryFetcher.numOfBlocksBeforeLatest + configs.l1DynamicGasPriceCapService.feeHistoryFetcher.numOfBlocksBeforeLatest, ), vertx = vertx, web3jClient = l1Web3jClient, feeHistoryFetcher = l1FeeHistoryFetcher, - feeHistoriesRepository = l1FeeHistoriesRepository + feeHistoriesRepository = l1FeeHistoriesRepository, ) } else { DisabledLongRunningService @@ -955,7 +955,7 @@ class L1DependentApp( category = LineaMetricsCategory.AGGREGATION, name = "highest.accepted.block.number", description = "Highest finalized accepted end block number", - measurementSupplier = it + measurementSupplier = it, ) } @@ -967,11 +967,11 @@ class L1DependentApp( "finalized records cleanup" to RecordsCleanupFinalizationHandler( batchesRepository = batchesRepository, blobsRepository = blobsRepository, - aggregationsRepository = aggregationsRepository + aggregationsRepository = aggregationsRepository, ), "highest_accepted_finalization_on_l1" to FinalizationHandler { update: FinalizationMonitor.FinalizationUpdate -> highestAcceptedFinalizationTracker(update.blockNumber) - } + }, ) .forEach { (handlerName, handler) -> l1FinalizationMonitor.addFinalizationHandler(handlerName, handler) @@ -984,7 +984,7 @@ class L1DependentApp( lastConsecutiveAggregatedBlockNumber = lastConsecutiveAggregatedBlockNumber, batchesRepository = batchesRepository, blobsRepository = blobsRepository, - aggregationsRepository = aggregationsRepository + aggregationsRepository = aggregationsRepository, ) .thenCompose { l1FinalizationMonitor.start() } .thenCompose { l1FinalizationHandlerForShomeiRpc.start() } @@ -1016,7 +1016,7 @@ class L1DependentApp( blockCreationMonitor.stop(), deadlineConflationCalculatorRunnerOld.stop(), deadlineConflationCalculatorRunnerNew.stop(), - blobCompressionProofCoordinator.stop() + blobCompressionProofCoordinator.stop(), ) .thenCompose { SafeFuture.fromRunnable { l1Web3jClient.shutdown() } } .thenApply { log.info("L1App Stopped") } @@ -1029,7 +1029,7 @@ class L1DependentApp( lastConsecutiveAggregatedBlockNumber: ULong, batchesRepository: BatchesRepository, blobsRepository: BlobsRepository, - aggregationsRepository: AggregationsRepository + aggregationsRepository: AggregationsRepository, ): SafeFuture<*> { val blockNumberInclusiveToDeleteFrom = lastProcessedBlockNumber + 1u val cleanupBatches = batchesRepository.deleteBatchesAfterBlockNumber(blockNumberInclusiveToDeleteFrom.toLong()) @@ -1046,7 +1046,7 @@ class L1DependentApp( */ fun resumeConflationFrom( aggregationsRepository: AggregationsRepository, - lastFinalizedBlock: ULong + lastFinalizedBlock: ULong, ): SafeFuture { return aggregationsRepository .findConsecutiveProvenBlobs(lastFinalizedBlock.toLong() + 1) @@ -1061,7 +1061,7 @@ class L1DependentApp( fun resumeAggregationFrom( aggregationsRepository: AggregationsRepository, - lastFinalizedBlock: ULong + lastFinalizedBlock: ULong, ): SafeFuture { return aggregationsRepository .findHighestConsecutiveEndBlockNumber(lastFinalizedBlock.toLong() + 1) @@ -1075,7 +1075,7 @@ class L1DependentApp( httpJsonRpcClientFactory: VertxHttpJsonRpcClientFactory, lineaRollupClient: LineaRollupSmartContractClientReadOnly, l2Web3jClient: Web3j, - vertx: Vertx + vertx: Vertx, ): LongRunningService { if (type2StateProofProviderConfig == null || type2StateProofProviderConfig.disabled || @@ -1091,7 +1091,7 @@ class L1DependentApp( vertx = vertx, rpcClient = httpJsonRpcClientFactory.create(it, log = log), retryConfig = type2StateProofProviderConfig.requestRetryConfig, - log = log + log = log, ) } @@ -1103,16 +1103,16 @@ class L1DependentApp( config = FinalizationMonitorImpl.Config( pollingInterval = type2StateProofProviderConfig.l1PollingInterval.toKotlinDuration(), - l1QueryBlockTag = type2StateProofProviderConfig.l1QueryBlockTag + l1QueryBlockTag = type2StateProofProviderConfig.l1QueryBlockTag, ), contract = lineaRollupClient, l2Client = l2Web3jClient, - vertx = vertx + vertx = vertx, ) l1FinalizationMonitor.addFinalizationHandler("type 2 state proof provider finalization updates", { finalizedBlockNotifier.updateFinalizedBlock( - BlockNumberAndHash(it.blockNumber, it.blockHash.toArray()) + BlockNumberAndHash(it.blockNumber, it.blockHash.toArray()), ) }) diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L2NetworkGasPricingService.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L2NetworkGasPricingService.kt index a860a129..dcb4abf3 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L2NetworkGasPricingService.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/L2NetworkGasPricingService.kt @@ -28,12 +28,12 @@ class L2NetworkGasPricingService( httpJsonRpcClientFactory: VertxHttpJsonRpcClientFactory, l1Web3jClient: Web3j, l1Web3jService: Web3jBlobExtended, - config: Config + config: Config, ) : LongRunningService { data class LegacyGasPricingCalculatorConfig( val transactionCostCalculatorConfig: TransactionCostCalculator.Config?, val naiveGasPricingCalculatorConfig: GasUsageRatioWeightedAverageFeesCalculator.Config?, - val legacyGasPricingCalculatorBounds: BoundableFeeCalculator.Config + val legacyGasPricingCalculatorBounds: BoundableFeeCalculator.Config, ) data class Config( @@ -46,23 +46,23 @@ class L2NetworkGasPricingService( val variableFeesCalculatorConfig: VariableFeesCalculator.Config, val variableFeesCalculatorBounds: BoundableFeeCalculator.Config, val extraDataCalculatorConfig: MinerExtraDataV1CalculatorImpl.Config, - val extraDataUpdaterConfig: ExtraDataV1UpdaterImpl.Config + val extraDataUpdaterConfig: ExtraDataV1UpdaterImpl.Config, ) private val log = LogManager.getLogger(this::class.java) private val gasPricingFeesFetcher: FeesFetcher = FeeHistoryFetcherImpl( l1Web3jClient, l1Web3jService, - config.feeHistoryFetcherConfig + config.feeHistoryFetcherConfig, ) private val boundedVariableCostCalculator = run { val variableCostCalculator = VariableFeesCalculator( - config.variableFeesCalculatorConfig + config.variableFeesCalculatorConfig, ) BoundableFeeCalculator( config = config.variableFeesCalculatorBounds, - feesCalculator = variableCostCalculator + feesCalculator = variableCostCalculator, ) } @@ -71,12 +71,12 @@ class L2NetworkGasPricingService( TransactionCostCalculator(boundedVariableCostCalculator, config.legacy.transactionCostCalculatorConfig) } else { GasUsageRatioWeightedAverageFeesCalculator( - config.legacy.naiveGasPricingCalculatorConfig!! + config.legacy.naiveGasPricingCalculatorConfig!!, ) } BoundableFeeCalculator( config.legacy.legacyGasPricingCalculatorBounds, - baseCalculator + baseCalculator, ) } @@ -84,7 +84,7 @@ class L2NetworkGasPricingService( if (config.jsonRpcGasPriceUpdaterConfig != null) { val l2SetGasPriceUpdater: GasPriceUpdater = GasPriceUpdaterImpl( httpJsonRpcClientFactory = httpJsonRpcClientFactory, - config = config.jsonRpcGasPriceUpdaterConfig + config = config.jsonRpcGasPriceUpdaterConfig, ) MinMineableFeesPricerService( @@ -92,7 +92,7 @@ class L2NetworkGasPricingService( vertx = vertx, feesFetcher = gasPricingFeesFetcher, feesCalculator = legacyGasPricingCalculator, - gasPriceUpdater = l2SetGasPriceUpdater + gasPriceUpdater = l2SetGasPriceUpdater, ) } else { null @@ -106,12 +106,12 @@ class L2NetworkGasPricingService( minerExtraDataCalculatorImpl = MinerExtraDataV1CalculatorImpl( config = config.extraDataCalculatorConfig, variableFeesCalculator = boundedVariableCostCalculator, - legacyFeesCalculator = legacyGasPricingCalculator + legacyFeesCalculator = legacyGasPricingCalculator, ), extraDataUpdater = ExtraDataV1UpdaterImpl( httpJsonRpcClientFactory = httpJsonRpcClientFactory, - config = config.extraDataUpdaterConfig - ) + config = config.extraDataUpdaterConfig, + ), ) } else { null @@ -128,7 +128,7 @@ class L2NetworkGasPricingService( override fun stop(): CompletableFuture { return SafeFuture.allOf( minMineableFeesPricerService?.stop() ?: SafeFuture.completedFuture(Unit), - extraDataPricerService?.stop() ?: SafeFuture.completedFuture(Unit) + extraDataPricerService?.stop() ?: SafeFuture.completedFuture(Unit), ) .thenApply { } .thenPeek { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/LastFinalizedBlockProvider.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/LastFinalizedBlockProvider.kt index 69b10826..5c23f3b8 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/LastFinalizedBlockProvider.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/LastFinalizedBlockProvider.kt @@ -27,7 +27,7 @@ class L1BasedLastFinalizedBlockProvider( private val lineaRollupSmartContractClient: LineaRollupSmartContractClientReadOnly, private val consistentNumberOfBlocksOnL1: UInt, private val numberOfRetries: UInt = Int.MAX_VALUE.toUInt(), - private val pollingInterval: Duration = 2.seconds + private val pollingInterval: Duration = 2.seconds, ) : LastFinalizedBlockProvider { private val log: Logger = LogManager.getLogger(this::class.java) @@ -42,7 +42,7 @@ class L1BasedLastFinalizedBlockProvider( "Rollup finalized block updated from {} to {}, waiting {} blocks for confirmation", lastObservedBlock.get(), lastPolledBlockNumber, - consistentNumberOfBlocksOnL1 + consistentNumberOfBlocksOnL1, ) numberOfObservations.set(1) lastObservedBlock.set(lastPolledBlockNumber) @@ -54,10 +54,10 @@ class L1BasedLastFinalizedBlockProvider( vertx, maxRetries = numberOfRetries.toInt(), backoffDelay = pollingInterval, - stopRetriesPredicate = isConsistentEnough + stopRetriesPredicate = isConsistentEnough, ) { lineaRollupSmartContractClient.finalizedL2BlockNumber( - blockParameter = BlockParameter.Tag.LATEST + blockParameter = BlockParameter.Tag.LATEST, ) } } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/BlockParameterDecoder.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/BlockParameterDecoder.kt index 3767d998..daad8fbe 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/BlockParameterDecoder.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/BlockParameterDecoder.kt @@ -20,14 +20,14 @@ class BlockParameterDecoder : Decoder { BlockParameter.parse(node.value) }.fold( { it.valid() }, - { ConfigFailure.DecodeError(node, type).invalid() } + { ConfigFailure.DecodeError(node, type).invalid() }, ) is LongNode -> runCatching { BlockParameter.fromNumber(node.value) }.fold( { it.valid() }, - { ConfigFailure.DecodeError(node, type).invalid() } + { ConfigFailure.DecodeError(node, type).invalid() }, ) else -> ConfigFailure.DecodeError(node, type).invalid() diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfig.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfig.kt index fbf9ef40..5de66e14 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfig.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfig.kt @@ -29,7 +29,7 @@ import kotlin.time.toJavaDuration import kotlin.time.toKotlinDuration data class ApiConfig( - val observabilityPort: UInt + val observabilityPort: UInt, ) data class ConflationConfig( @@ -42,7 +42,7 @@ data class ConflationConfig( private var _smartContractErrors: SmartContractErrors?, val fetchBlocksLimit: Int, @ConfigAlias("conflation-target-end-block-numbers") - private val _conflationTargetEndBlockNumbers: List = emptyList() + private val _conflationTargetEndBlockNumbers: List = emptyList(), ) { init { @@ -84,7 +84,7 @@ data class RequestRetryConfigTomlFriendly( override val maxRetries: Int? = null, override val timeout: Duration? = null, override val backoffDelay: Duration = 1.milliseconds.toJavaDuration(), - val failuresWarningThreshold: Int = 0 + val failuresWarningThreshold: Int = 0, ) : RetryConfig { init { maxRetries?.also { @@ -105,25 +105,25 @@ data class RequestRetryConfigTomlFriendly( maxRetries = maxRetries?.toUInt(), timeout = timeout?.toKotlinDuration(), backoffDelay = backoffDelay.toKotlinDuration(), - failuresWarningThreshold = failuresWarningThreshold.toUInt() + failuresWarningThreshold = failuresWarningThreshold.toUInt(), ) internal val asDomain: linea.domain.RetryConfig = linea.domain.RetryConfig( maxRetries = maxRetries?.toUInt(), timeout = timeout?.toKotlinDuration(), backoffDelay = backoffDelay.toKotlinDuration(), - failuresWarningThreshold = failuresWarningThreshold.toUInt() + failuresWarningThreshold = failuresWarningThreshold.toUInt(), ) companion object { fun endlessRetry( backoffDelay: Duration, - failuresWarningThreshold: Int + failuresWarningThreshold: Int, ) = RequestRetryConfigTomlFriendly( maxRetries = null, timeout = null, backoffDelay = backoffDelay, - failuresWarningThreshold = failuresWarningThreshold + failuresWarningThreshold = failuresWarningThreshold, ) } } @@ -131,7 +131,7 @@ data class RequestRetryConfigTomlFriendly( data class PersistenceRetryConfig( override val maxRetries: Int? = null, override val backoffDelay: Duration = 1.seconds.toJavaDuration(), - override val timeout: Duration? = 10.minutes.toJavaDuration() + override val timeout: Duration? = 10.minutes.toJavaDuration(), ) : RetryConfig internal interface RequestRetryConfigurable { @@ -144,7 +144,7 @@ data class BlobCompressionConfig( val blobSizeLimit: Int, @ConfigAlias("batches-limit") private val _batchesLimit: Int? = null, - val handlerPollingInterval: Duration + val handlerPollingInterval: Duration, ) { init { _batchesLimit?.also { @@ -163,7 +163,7 @@ data class AggregationConfig( val deadlineCheckInterval: Duration, val aggregationSizeMultipleOf: Int = 1, @ConfigAlias("target-end-blocks") - private val _targetEndBlocks: List = emptyList() + private val _targetEndBlocks: List = emptyList(), ) { val targetEndBlocks: List = _targetEndBlocks.map { it.toULong() } @@ -177,12 +177,12 @@ data class TracesConfig( val blobCompressorVersion: BlobCompressorVersion, val expectedTracesApiVersionV2: String, val countersV2: FunctionalityEndpoint, - val conflationV2: FunctionalityEndpoint + val conflationV2: FunctionalityEndpoint, ) { data class FunctionalityEndpoint( val endpoints: List, val requestLimitPerEndpoint: UInt, - override val requestRetry: RequestRetryConfigTomlFriendly + override val requestRetry: RequestRetryConfigTomlFriendly, ) : RequestRetryConfigurable { init { require(requestLimitPerEndpoint > 0u) { "requestLimitPerEndpoint must be greater than 0" } @@ -194,7 +194,7 @@ data class StateManagerClientConfig( val version: String, val endpoints: List, val requestLimitPerEndpoint: UInt, - override val requestRetry: RequestRetryConfigTomlFriendly + override val requestRetry: RequestRetryConfigTomlFriendly, ) : RequestRetryConfigurable { init { require(requestLimitPerEndpoint > 0u) { "requestLimitPerEndpoint must be greater than 0" } @@ -210,7 +210,7 @@ data class BlobSubmissionConfig( val maxBlobsToSubmitPerTick: Int = maxBlobsToReturn, val targetBlobsToSendPerTransaction: Int = 9, val useEthEstimateGas: Boolean = false, - override var disabled: Boolean = false + override var disabled: Boolean = false, ) : FeatureToggleable { init { require(maxBlobsToReturn > 0) { "maxBlobsToReturn must be greater than 0" } @@ -226,7 +226,7 @@ data class AggregationFinalizationConfig( val maxAggregationsToFinalizePerTick: Int, val proofSubmissionDelay: Duration, val useEthEstimateGas: Boolean = false, - override var disabled: Boolean = false + override var disabled: Boolean = false, ) : FeatureToggleable { init { require(maxAggregationsToFinalizePerTick > 0) { @@ -243,7 +243,7 @@ data class DatabaseConfig( val schema: String, val readPoolSize: Int, val readPipeliningLimit: Int, - val transactionalPoolSize: Int + val transactionalPoolSize: Int, ) data class L1Config( @@ -268,7 +268,7 @@ data class L1Config( val blockTime: Duration = Duration.parse("PT12S"), @ConfigAlias("eth-fee-history-endpoint") private val _ethFeeHistoryEndpoint: URL?, @ConfigAlias("genesis-state-root-hash") private val _genesisStateRootHash: String, - @ConfigAlias("genesis-shnarf-v6") private val _genesisShnarfV6: String + @ConfigAlias("genesis-shnarf-v6") private val _genesisShnarfV6: String, ) { val ethFeeHistoryEndpoint: URL get() = _ethFeeHistoryEndpoint ?: rpcEndpoint @@ -303,7 +303,7 @@ data class L2Config( val lastHashSearchWindow: UInt, val anchoringReceiptPollingInterval: Duration, val maxReceiptRetries: UInt, - val newBlockPollingInterval: Duration + val newBlockPollingInterval: Duration, ) { init { messageServiceAddress.assertIsValidAddress("messageServiceAddress") @@ -313,11 +313,11 @@ data class L2Config( data class SignerConfig( val type: Type, val web3signer: Web3SignerConfig?, - val web3j: Web3jConfig? + val web3j: Web3jConfig?, ) { enum class Type { Web3j, - Web3Signer + Web3Signer, } init { @@ -334,14 +334,14 @@ data class SignerConfig( } data class Web3jConfig( - val privateKey: Masked + val privateKey: Masked, ) data class Web3SignerConfig( val endpoint: String, val maxPoolSize: UInt, val keepAlive: Boolean, - val publicKey: String + val publicKey: String, ) interface FeatureToggleable { @@ -354,7 +354,7 @@ data class L1DynamicGasPriceCapServiceConfig( val gasPriceCapCalculation: GasPriceCapCalculation, val feeHistoryFetcher: FeeHistoryFetcher, val feeHistoryStorage: FeeHistoryStorage, - override var disabled: Boolean = false + override var disabled: Boolean = false, ) : FeatureToggleable { data class GasPriceCapCalculation( val adjustmentConstant: UInt, @@ -366,7 +366,7 @@ data class L1DynamicGasPriceCapServiceConfig( val gasPriceCapsCheckCoefficient: Double, val historicBaseFeePerBlobGasLowerBound: ULong, val historicAvgRewardConstant: ULong?, - val timeOfDayMultipliers: TimeOfDayMultipliers? + val timeOfDayMultipliers: TimeOfDayMultipliers?, ) { init { timeOfDayMultipliers?.also { @@ -385,7 +385,7 @@ data class L1DynamicGasPriceCapServiceConfig( require(timeOfDayMultiplier.value > 0.0) { throw IllegalStateException( "Each multiplier in timeOfDayMultipliers must be greater than 0.0." + - " Key=${timeOfDayMultiplier.key} Value=${timeOfDayMultiplier.value}" + " Key=${timeOfDayMultiplier.key} Value=${timeOfDayMultiplier.value}", ) } } @@ -404,7 +404,7 @@ data class L1DynamicGasPriceCapServiceConfig( } data class FeeHistoryStorage( - val storagePeriod: Duration + val storagePeriod: Duration, ) { init { require(storagePeriod <= MAX_FEE_HISTORIES_STORAGE_PERIOD.toJavaDuration()) { @@ -418,12 +418,12 @@ data class L1DynamicGasPriceCapServiceConfig( val maxBlockCount: UInt, val rewardPercentiles: List, val numOfBlocksBeforeLatest: UInt = 4U, - val endpoint: URL? + val endpoint: URL?, ) { init { require( maxBlockCount > 0U && - maxBlockCount <= MAX_FEE_HISTORY_BLOCK_COUNT + maxBlockCount <= MAX_FEE_HISTORY_BLOCK_COUNT, ) { "maxBlockCount must be greater than 0 and " + "less than or equal to $MAX_FEE_HISTORY_BLOCK_COUNT" @@ -431,7 +431,7 @@ data class L1DynamicGasPriceCapServiceConfig( require( rewardPercentiles.isNotEmpty() && - rewardPercentiles.size <= MAX_REWARD_PERCENTILES_SIZE + rewardPercentiles.size <= MAX_REWARD_PERCENTILES_SIZE, ) { "rewardPercentiles must be a non-empty list with " + "maximum length as $MAX_REWARD_PERCENTILES_SIZE." @@ -459,7 +459,7 @@ data class L1DynamicGasPriceCapServiceConfig( require( gasPriceCapCalculation.gasFeePercentileWindow - >= gasPriceCapCalculation.gasFeePercentileWindowLeeway + >= gasPriceCapCalculation.gasFeePercentileWindowLeeway, ) { "gasFeePercentileWindow must be at least same length as" + " gasFeePercentileWindowLeeway=${gasPriceCapCalculation.gasFeePercentileWindowLeeway}." + @@ -483,7 +483,7 @@ data class Type2StateProofProviderConfig( val endpoints: List, val l1QueryBlockTag: BlockParameter.Tag = BlockParameter.Tag.LATEST, val l1PollingInterval: Duration = Duration.ofSeconds(12), - override val requestRetry: RequestRetryConfigTomlFriendly + override val requestRetry: RequestRetryConfigTomlFriendly, ) : FeatureToggleable, RequestRetryConfigurable data class TracesLimitsV2ConfigFile(val tracesLimits: Map) @@ -515,7 +515,7 @@ data class CoordinatorConfigTomlDto( val l2NetworkGasPricing: L2NetworkGasPricingTomlDto, val l1DynamicGasPriceCapService: L1DynamicGasPriceCapServiceConfig, val testL1Disabled: Boolean = false, - val prover: ProverConfigTomlDto + val prover: ProverConfigTomlDto, ) { fun reified(): CoordinatorConfig = CoordinatorConfig( l2InclusiveBlockNumberToStopAndFlushAggregation = l2InclusiveBlockNumberToStopAndFlushAggregation, @@ -537,13 +537,13 @@ data class CoordinatorConfigTomlDto( l2Signer = l2Signer, messageAnchoring = messageAnchoring.reified( l1DefaultEndpoint = l1.rpcEndpoint, - l2DefaultEndpoint = l2.rpcEndpoint + l2DefaultEndpoint = l2.rpcEndpoint, ), l2NetworkGasPricingService = if (testL1Disabled || l2NetworkGasPricing.disabled) null else l2NetworkGasPricing.reified(), l1DynamicGasPriceCapService = l1DynamicGasPriceCapService, testL1Disabled = testL1Disabled, - proversConfig = prover.reified() + proversConfig = prover.reified(), ) } @@ -569,7 +569,7 @@ data class CoordinatorConfig( val l2NetworkGasPricingService: L2NetworkGasPricingService.Config?, val l1DynamicGasPriceCapService: L1DynamicGasPriceCapServiceConfig, val testL1Disabled: Boolean = false, - val proversConfig: ProversConfig + val proversConfig: ProversConfig, ) { init { if (l2InclusiveBlockNumberToStopAndFlushAggregation != null) { @@ -583,7 +583,7 @@ data class CoordinatorConfig( require( blobCompression.batchesLimit == null || - blobCompression.batchesLimit!! < proofAggregation.aggregationProofsLimit.toUInt() + blobCompression.batchesLimit!! < proofAggregation.aggregationProofsLimit.toUInt(), ) { "[blob-compression].batchesLimit=${blobCompression.batchesLimit} must be less than " + "[proof-aggregation].aggregationProofsLimit=${proofAggregation.aggregationProofsLimit}" diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfig.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfig.kt index 0466b27a..ae27dd10 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfig.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfig.kt @@ -19,7 +19,7 @@ import kotlin.time.toKotlinDuration data class SampleTransactionGasPricingTomlDto( val plainTransferCostMultiplier: Double = 1.0, val compressedTxSize: Int = 125, - val expectedGas: Int = 21000 + val expectedGas: Int = 21000, ) data class LegacyGasPricingTomlDto( @@ -28,11 +28,11 @@ data class LegacyGasPricingTomlDto( val naiveGasPricing: NaiveGasPricingTomlDto?, val sampleTransactionGasPricing: SampleTransactionGasPricingTomlDto = SampleTransactionGasPricingTomlDto(), val gasPriceUpperBound: ULong, - val gasPriceLowerBound: ULong + val gasPriceLowerBound: ULong, ) { enum class Type { Naive, - SampleTransaction + SampleTransaction, } init { @@ -49,7 +49,7 @@ data class LegacyGasPricingTomlDto( data class NaiveGasPricingTomlDto( val baseFeeCoefficient: Double, val priorityFeeCoefficient: Double, - val baseFeeBlobCoefficient: Double + val baseFeeBlobCoefficient: Double, ) data class VariableCostPricingTomlDto( @@ -57,7 +57,7 @@ data class VariableCostPricingTomlDto( val legacyFeesMultiplier: Double, val margin: Double, val variableCostUpperBound: ULong, - val variableCostLowerBound: ULong + val variableCostLowerBound: ULong, ) { init { require(variableCostUpperBound >= variableCostLowerBound) { @@ -69,7 +69,7 @@ data class VariableCostPricingTomlDto( data class JsonRpcPricingPropagationTomlDto( override var disabled: Boolean = false, val gethGasPriceUpdateRecipients: List, - val besuGasPriceUpdateRecipients: List + val besuGasPriceUpdateRecipients: List, ) : FeatureToggleable { init { require(disabled || (gethGasPriceUpdateRecipients.isNotEmpty() || besuGasPriceUpdateRecipients.isNotEmpty())) { @@ -81,7 +81,7 @@ data class JsonRpcPricingPropagationTomlDto( data class ExtraDataPricingPropagationTomlDto( override var disabled: Boolean = false, - val extraDataUpdateRecipient: URL + val extraDataUpdateRecipient: URL, ) : FeatureToggleable data class L2NetworkGasPricingTomlDto( @@ -99,7 +99,7 @@ data class L2NetworkGasPricingTomlDto( val legacy: LegacyGasPricingTomlDto, val variableCostPricing: VariableCostPricingTomlDto, val jsonRpcPricingPropagation: JsonRpcPricingPropagationTomlDto?, - val extraDataPricingPropagation: ExtraDataPricingPropagationTomlDto + val extraDataPricingPropagation: ExtraDataPricingPropagationTomlDto, ) : FeatureToggleable, RequestRetryConfigurable { init { require(feeHistoryBlockCount > 0) { "feeHistoryBlockCount must be greater than 0" } @@ -124,13 +124,13 @@ data class L2NetworkGasPricingTomlDto( priorityFeeCoefficient = legacy.naiveGasPricing.priorityFeeCoefficient, baseFeeBlobCoefficient = legacy.naiveGasPricing.baseFeeBlobCoefficient, blobSubmissionExpectedExecutionGas = blobSubmissionExpectedExecutionGas, - expectedBlobGas = l1BlobGas + expectedBlobGas = l1BlobGas, ), legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( legacy.gasPriceUpperBound.toDouble(), legacy.gasPriceLowerBound.toDouble(), - 0.0 - ) + 0.0, + ), ) } @@ -140,14 +140,14 @@ data class L2NetworkGasPricingTomlDto( sampleTransactionCostMultiplier = legacy.sampleTransactionGasPricing.plainTransferCostMultiplier, fixedCostWei = variableCostPricing.gasPriceFixedCost, compressedTxSize = legacy.sampleTransactionGasPricing.compressedTxSize, - expectedGas = legacy.sampleTransactionGasPricing.expectedGas + expectedGas = legacy.sampleTransactionGasPricing.expectedGas, ), naiveGasPricingCalculatorConfig = null, legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( legacy.gasPriceUpperBound.toDouble(), legacy.gasPriceLowerBound.toDouble(), - 0.0 - ) + 0.0, + ), ) } } @@ -155,7 +155,7 @@ data class L2NetworkGasPricingTomlDto( GasPriceUpdaterImpl.Config( gethEndpoints = jsonRpcPricingPropagation.gethGasPriceUpdateRecipients, besuEndPoints = jsonRpcPricingPropagation.besuGasPriceUpdateRecipients, - retryConfig = requestRetryConfig + retryConfig = requestRetryConfig, ) } else { null @@ -163,7 +163,7 @@ data class L2NetworkGasPricingTomlDto( return L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = feeHistoryBlockCount.toUInt(), - feeHistoryRewardPercentile = feeHistoryRewardPercentile + feeHistoryRewardPercentile = feeHistoryRewardPercentile, ), legacy = legacyGasPricingConfig, jsonRpcGasPriceUpdaterConfig = gasPriceUpdaterConfig, @@ -174,21 +174,21 @@ data class L2NetworkGasPricingTomlDto( blobSubmissionExpectedExecutionGas = blobSubmissionExpectedExecutionGas.toUInt(), bytesPerDataSubmission = l1BlobGas.toUInt(), expectedBlobGas = bytesPerDataSubmission.toUInt(), - margin = variableCostPricing.margin + margin = variableCostPricing.margin, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = variableCostPricing.variableCostUpperBound.toDouble(), feeLowerBound = variableCostPricing.variableCostLowerBound.toDouble(), - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = variableCostPricing.gasPriceFixedCost.toKWeiUInt(), - ethGasPriceMultiplier = variableCostPricing.legacyFeesMultiplier + ethGasPriceMultiplier = variableCostPricing.legacyFeesMultiplier, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( extraDataPricingPropagation.extraDataUpdateRecipient, - requestRetryConfig - ) + requestRetryConfig, + ), ) } } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfig.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfig.kt index 82156584..3cb8ad1b 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfig.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfig.kt @@ -14,7 +14,7 @@ data class MessageAnchoringConfigTomlDto( val l1HighestBlockTag: BlockParameter = BlockParameter.Tag.FINALIZED, val l1RequestRetries: RequestRetryConfigTomlFriendly = RequestRetryConfigTomlFriendly.endlessRetry( backoffDelay = 1.seconds.toJavaDuration(), - failuresWarningThreshold = 3 + failuresWarningThreshold = 3, ), val l1EventPollingInterval: Duration = 12.seconds.toJavaDuration(), val l1EventPollingTimeout: Duration = 6.seconds.toJavaDuration(), @@ -24,11 +24,11 @@ data class MessageAnchoringConfigTomlDto( val l2HighestBlockTag: BlockParameter = BlockParameter.Tag.LATEST, val l2RequestRetries: RequestRetryConfigTomlFriendly = RequestRetryConfigTomlFriendly.endlessRetry( backoffDelay = 1.seconds.toJavaDuration(), - failuresWarningThreshold = 3 + failuresWarningThreshold = 3, ), val anchoringTickInterval: Duration = 2.seconds.toJavaDuration(), val messageQueueCapacity: Int = 10_000, - val maxMessagesToAnchorPerL2Transaction: Int = 100 + val maxMessagesToAnchorPerL2Transaction: Int = 100, ) { init { require(messageQueueCapacity > 0) { @@ -56,7 +56,7 @@ data class MessageAnchoringConfigTomlDto( fun reified( l1DefaultEndpoint: URL, - l2DefaultEndpoint: URL + l2DefaultEndpoint: URL, ): MessageAnchoringConfig { return MessageAnchoringConfig( disabled = disabled, @@ -72,7 +72,7 @@ data class MessageAnchoringConfigTomlDto( l1EventSearchBlockChunk = l1EventSearchBlockChunk.toUInt(), anchoringTickInterval = anchoringTickInterval.toKotlinDuration(), messageQueueCapacity = messageQueueCapacity.toUInt(), - maxMessagesToAnchorPerL2Transaction = maxMessagesToAnchorPerL2Transaction.toUInt() + maxMessagesToAnchorPerL2Transaction = maxMessagesToAnchorPerL2Transaction.toUInt(), ) } } @@ -91,5 +91,5 @@ data class MessageAnchoringConfig( val l1EventSearchBlockChunk: UInt, val anchoringTickInterval: kotlin.time.Duration, val messageQueueCapacity: UInt, - val maxMessagesToAnchorPerL2Transaction: UInt + val maxMessagesToAnchorPerL2Transaction: UInt, ) : FeatureToggleable diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfig.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfig.kt index 289b0b32..128e17e0 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfig.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfig.kt @@ -19,13 +19,13 @@ data class ProverConfigTomlDto( val execution: FileSystemTomlDto, val blobCompression: FileSystemTomlDto, val proofAggregation: FileSystemTomlDto, - val new: ProverConfigTomlDto? = null + val new: ProverConfigTomlDto? = null, ) { private fun asProverConfig(): ProverConfig { return ProverConfig( execution = execution.toDomain(), blobCompression = blobCompression.toDomain(), - proofAggregation = proofAggregation.toDomain() + proofAggregation = proofAggregation.toDomain(), ) } @@ -56,7 +56,7 @@ data class ProverConfigTomlDto( return ProversConfig( proverA = this.asProverConfig(), switchBlockNumberInclusive = new?.switchBlockNumberInclusive?.toULong(), - proverB = new?.asProverConfig() + proverB = new?.asProverConfig(), ) } } @@ -67,7 +67,7 @@ data class FileSystemTomlDto( internal var fsInprogressRequestWritingSuffix: String?, internal var fsInprogressProvingSuffixPattern: String?, internal var fsPollingInterval: Duration?, - internal var fsPollingTimeout: Duration? + internal var fsPollingTimeout: Duration?, ) { internal fun reifyWithRootDefaults(rootConfig: ProverConfigTomlDto) { fsInprogressRequestWritingSuffix = fsInprogressRequestWritingSuffix @@ -85,7 +85,7 @@ data class FileSystemTomlDto( inprogressRequestWritingSuffix = fsInprogressRequestWritingSuffix!!, inprogressProvingSuffixPattern = fsInprogressProvingSuffixPattern!!, pollingInterval = fsPollingInterval!!.toKotlinDuration(), - pollingTimeout = fsPollingTimeout!!.toKotlinDuration() + pollingTimeout = fsPollingTimeout!!.toKotlinDuration(), ) } } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitor.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitor.kt index 86a3183c..828e85c1 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitor.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitor.kt @@ -25,18 +25,18 @@ class BlockCreationMonitor( private val blockCreationListener: BlockCreationListener, private val lastProvenBlockNumberProviderAsync: LastProvenBlockNumberProviderAsync, private val config: Config, - private val log: Logger = LogManager.getLogger(BlockCreationMonitor::class.java) + private val log: Logger = LogManager.getLogger(BlockCreationMonitor::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { data class Config( val pollingInterval: Duration, val blocksToFinalization: Long, val blocksFetchLimit: Long, val startingBlockWaitTimeout: Duration = 14.days, - val lastL2BlockNumberToProcessInclusive: ULong? = null + val lastL2BlockNumberToProcessInclusive: ULong? = null, ) private val _nexBlockNumberToFetch: AtomicLong = AtomicLong(startingBlockNumberExclusive + 1) @@ -76,7 +76,7 @@ class BlockCreationMonitor( log.warn( "Block {} not found yet. Retrying in {}", startingBlockNumberExclusive, - config.pollingInterval + config.pollingInterval, ) false } else { @@ -84,7 +84,7 @@ class BlockCreationMonitor( expectedParentBlockHash.set(block.hash) true } - } + }, ) { web3j.ethGetBlock(startingBlockNumberExclusive.toBlockParameter()) } @@ -104,7 +104,7 @@ class BlockCreationMonitor( lastProvenBlockNumber, _nexBlockNumberToFetch.get(), _nexBlockNumberToFetch.get() - lastProvenBlockNumber, - config.blocksFetchLimit + config.blocksFetchLimit, ) SafeFuture.COMPLETE } else if (config.lastL2BlockNumberToProcessInclusive != null && @@ -115,7 +115,7 @@ class BlockCreationMonitor( "All blocks upto and including lastL2BlockNumberInclusiveToProcess={} have been processed. " + "nextBlockNumberToFetch={}", config.lastL2BlockNumberToProcessInclusive, - nexBlockNumberToFetch + nexBlockNumberToFetch, ) SafeFuture.COMPLETE } else { @@ -128,7 +128,7 @@ class BlockCreationMonitor( log.debug( "updating nexBlockNumberToFetch from {} --> {}", _nexBlockNumberToFetch.get(), - _nexBlockNumberToFetch.incrementAndGet() + _nexBlockNumberToFetch.incrementAndGet(), ) expectedParentBlockHash.set(block.hash) } @@ -140,7 +140,7 @@ class BlockCreationMonitor( block.number, block.hash.encodeHex(), block.parentHash.encodeHex(), - expectedParentBlockHash.get().encodeHex() + expectedParentBlockHash.get().encodeHex(), ) SafeFuture.failedFuture(IllegalStateException("Reorg detected on block ${block.number}")) } @@ -164,7 +164,7 @@ class BlockCreationMonitor( .thenApply { log.debug( "blockCreationListener blockNumber={} resolved with success", - payload.number + payload.number, ) } .whenException { throwable -> @@ -172,7 +172,7 @@ class BlockCreationMonitor( "Failed to notify blockCreationListener: blockNumber={} errorMessage={}", payload.number, throwable.message, - throwable + throwable, ) } } @@ -195,7 +195,7 @@ class BlockCreationMonitor( "eth_getBlockByNumber({}) failed: errorMessage={}", blockNumber, it.message, - it + it, ) } } else { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/GethCliqueSafeBlockProvider.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/GethCliqueSafeBlockProvider.kt index 0cb93579..86ae2fd9 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/GethCliqueSafeBlockProvider.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/GethCliqueSafeBlockProvider.kt @@ -12,10 +12,10 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class GethCliqueSafeBlockProvider( private val web3j: Web3j, - private val config: Config + private val config: Config, ) : SafeBlockProvider { data class Config( - val blocksToFinalization: Long + val blocksToFinalization: Long, ) override fun getLatestSafeBlock(): SafeFuture { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/LastProvenBlockNumberProviderAsync.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/LastProvenBlockNumberProviderAsync.kt index 93185dea..5203f90b 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/LastProvenBlockNumberProviderAsync.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/coordinator/blockcreation/LastProvenBlockNumberProviderAsync.kt @@ -15,7 +15,7 @@ interface LastProvenBlockNumberProviderSync { class BatchesRepoBasedLastProvenBlockNumberProvider( startingBlockNumberExclusive: Long, - private val batchesRepository: BatchesRepository + private val batchesRepository: BatchesRepository, ) : LastProvenBlockNumberProviderAsync, LastProvenBlockNumberProviderSync { private var latestL1FinalizedBlock: AtomicLong = AtomicLong(startingBlockNumberExclusive) private var lastProvenBlock: AtomicLong = AtomicLong(startingBlockNumberExclusive) @@ -35,7 +35,7 @@ class BatchesRepoBasedLastProvenBlockNumberProvider( private fun findAndCacheLastProvenBlockNumberFromDb(): SafeFuture { return batchesRepository.findHighestConsecutiveEndBlockNumberFromBlockNumber( - latestL1FinalizedBlock.get() + 1 + latestL1FinalizedBlock.get() + 1, ).thenApply { newValue -> if (newValue != null) { diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/SimpleCompositeSafeFutureHandler.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/SimpleCompositeSafeFutureHandler.kt index 89bc9143..6b481c93 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/SimpleCompositeSafeFutureHandler.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/SimpleCompositeSafeFutureHandler.kt @@ -3,7 +3,7 @@ package net.consensys.zkevm.ethereum.coordination import tech.pegasys.teku.infrastructure.async.SafeFuture class SimpleCompositeSafeFutureHandler( - private val handlers: List<(T) -> SafeFuture<*>> + private val handlers: List<(T) -> SafeFuture<*>>, ) : (T) -> SafeFuture<*> { override fun invoke(arg: T): SafeFuture { val handlingFutures = diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker.kt index 7fb82d72..e839731f 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker.kt @@ -8,7 +8,7 @@ import java.util.function.Supplier class ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTracker( private val repository: AggregationsRepository, - initialBlockNumber: ULong + initialBlockNumber: ULong, ) : ConsecutiveProvenBlobsProvider, Supplier { private val cache = AtomicReference(initialBlockNumber) diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProviderImpl.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProviderImpl.kt index 67982a2e..352bf6bc 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProviderImpl.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProviderImpl.kt @@ -6,7 +6,7 @@ import linea.domain.BlockInterval import tech.pegasys.teku.infrastructure.async.SafeFuture class BlobZkStateProviderImpl( - private val zkStateClient: StateManagerClientV1 + private val zkStateClient: StateManagerClientV1, ) : BlobZkStateProvider { override fun getBlobZKState(blockRange: ULongRange): SafeFuture { return zkStateClient @@ -14,7 +14,7 @@ class BlobZkStateProviderImpl( .thenApply { BlobZkState( parentStateRootHash = it.zkParentStateRootHash, - finalStateRootHash = it.zkEndStateRootHash + finalStateRootHash = it.zkEndStateRootHash, ) } } diff --git a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImpl.kt b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImpl.kt index 56a027d6..0060860f 100644 --- a/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImpl.kt +++ b/coordinator/app/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImpl.kt @@ -17,7 +17,7 @@ class ForkChoiceUpdaterImpl(private val rollupForkChoiceUpdatedClients: List> = rollupForkChoiceUpdatedClients.map { rollupForkChoiceUpdatedClient -> rollupForkChoiceUpdatedClient diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1BasedLastFinalizedBlockProviderTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1BasedLastFinalizedBlockProviderTest.kt index 8a513709..30d6b8a3 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1BasedLastFinalizedBlockProviderTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1BasedLastFinalizedBlockProviderTest.kt @@ -28,7 +28,7 @@ class L1BasedLastFinalizedBlockProviderTest { whenever(lineaRollupClient.finalizedL2BlockNumber(eq(BlockParameter.Tag.LATEST))) .thenReturn( SafeFuture.completedFuture(replies[0]), - *replies.subList(1, replies.size).map { SafeFuture.completedFuture(it) }.toTypedArray() + *replies.subList(1, replies.size).map { SafeFuture.completedFuture(it) }.toTypedArray(), ) val resumerCalculator = L1BasedLastFinalizedBlockProvider( @@ -36,7 +36,7 @@ class L1BasedLastFinalizedBlockProviderTest { lineaRollupClient, consistentNumberOfBlocksOnL1 = 3u, numberOfRetries = 50u, - pollingInterval = 10.milliseconds + pollingInterval = 10.milliseconds, ) assertThat(resumerCalculator.getLastFinalizedBlock().get()).isEqualTo(101.toULong()) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1DependentAppTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1DependentAppTest.kt index 433893dc..45304a79 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1DependentAppTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/L1DependentAppTest.kt @@ -23,7 +23,7 @@ class L1DependentAppTest { val lastProcessedBlock = L1DependentApp.resumeConflationFrom( aggregationsRepository, - lastFinalizedBlock + lastFinalizedBlock, ).get() assertThat(lastProcessedBlock).isEqualTo(lastFinalizedBlock) verify(aggregationsRepository).findConsecutiveProvenBlobs(lastFinalizedBlock.toLong() + 1) @@ -49,12 +49,12 @@ class L1DependentAppTest { lastConsecutiveAggregatedBlockNumber = lastConsecutiveAggregatedBlockNumber, batchesRepository = batchesRepository, blobsRepository = blobsRepository, - aggregationsRepository = aggregationsRepository + aggregationsRepository = aggregationsRepository, ).get() verify(batchesRepository).deleteBatchesAfterBlockNumber((lastProcessedBlock + 1uL).toLong()) verify(blobsRepository).deleteBlobsAfterBlockNumber(lastProcessedBlock + 1uL) verify(aggregationsRepository).deleteAggregationsAfterBlockNumber( - (lastConsecutiveAggregatedBlockNumber + 1uL).toLong() + (lastConsecutiveAggregatedBlockNumber + 1uL).toLong(), ) } } diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfigTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfigTest.kt index abd2b97c..f15f2d7b 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfigTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/CoordinatorConfigTest.kt @@ -45,9 +45,9 @@ class CoordinatorConfigTest { _smartContractErrors = mapOf( // L1 Linea Rollup "0f06cd15" to "DataAlreadySubmitted", - "c01eab56" to "EmptySubmissionData" + "c01eab56" to "EmptySubmissionData", ), - fetchBlocksLimit = 4000 + fetchBlocksLimit = 4000, ) private val proversConfig = ProversConfig( @@ -58,7 +58,7 @@ class CoordinatorConfigTest { pollingInterval = 1.seconds, pollingTimeout = 10.minutes, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", ), blobCompression = FileBasedProverConfig( requestsDirectory = Path.of("/data/prover/v2/compression/requests"), @@ -66,7 +66,7 @@ class CoordinatorConfigTest { pollingInterval = 1.seconds, pollingTimeout = 10.minutes, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", ), proofAggregation = FileBasedProverConfig( requestsDirectory = Path.of("/data/prover/v2/aggregation/requests"), @@ -74,24 +74,24 @@ class CoordinatorConfigTest { pollingInterval = 1.seconds, pollingTimeout = 10.minutes, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" - ) + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", + ), ), switchBlockNumberInclusive = null, - proverB = null + proverB = null, ) private val blobCompressionConfig = BlobCompressionConfig( blobSizeLimit = 100 * 1024, handlerPollingInterval = Duration.parse("PT1S"), - _batchesLimit = 1 + _batchesLimit = 1, ) private val aggregationConfig = AggregationConfig( aggregationProofsLimit = 3, aggregationDeadline = Duration.parse("PT10S"), aggregationCoordinatorPollingInterval = Duration.parse("PT2S"), - deadlineCheckInterval = Duration.parse("PT8S") + deadlineCheckInterval = Duration.parse("PT8S"), ) private val tracesConfig = TracesConfig( @@ -103,38 +103,38 @@ class CoordinatorConfigTest { requestLimitPerEndpoint = 1U, requestRetry = RequestRetryConfigTomlFriendly( backoffDelay = Duration.parse("PT1S"), - failuresWarningThreshold = 2 - ) + failuresWarningThreshold = 2, + ), ), countersV2 = TracesConfig.FunctionalityEndpoint( endpoints = listOf(URI("http://traces-node:8545/").toURL()), requestLimitPerEndpoint = 1U, requestRetry = RequestRetryConfigTomlFriendly( backoffDelay = Duration.parse("PT1S"), - failuresWarningThreshold = 2 - ) - ) + failuresWarningThreshold = 2, + ), + ), ) private val type2StateProofProviderConfig = Type2StateProofProviderConfig( endpoints = listOf(URI("http://shomei-frontend:8888/").toURL()), requestRetry = RequestRetryConfigTomlFriendly( backoffDelay = Duration.parse("PT1S"), - failuresWarningThreshold = 2 + failuresWarningThreshold = 2, ), l1QueryBlockTag = BlockParameter.Tag.SAFE, - l1PollingInterval = Duration.parse("PT6S") + l1PollingInterval = Duration.parse("PT6S"), ) private val stateManagerConfig = StateManagerClientConfig( version = "2.3.0", endpoints = listOf( - URI("http://shomei:8888/").toURL() + URI("http://shomei:8888/").toURL(), ), requestLimitPerEndpoint = 2U, requestRetry = RequestRetryConfigTomlFriendly( backoffDelay = Duration.parse("PT2S"), - failuresWarningThreshold = 2 - ) + failuresWarningThreshold = 2, + ), ) private val blobSubmissionConfig = BlobSubmissionConfig( @@ -146,7 +146,7 @@ class CoordinatorConfigTest { proofSubmissionDelay = Duration.parse("PT1S"), targetBlobsToSendPerTransaction = 9, useEthEstimateGas = false, - disabled = false + disabled = false, ) private val aggregationFinalizationConfig = AggregationFinalizationConfig( @@ -154,7 +154,7 @@ class CoordinatorConfigTest { maxAggregationsToFinalizePerTick = 1, proofSubmissionDelay = Duration.parse("PT1S"), useEthEstimateGas = true, - disabled = false + disabled = false, ) private val databaseConfig = DatabaseConfig( @@ -165,12 +165,12 @@ class CoordinatorConfigTest { schema = "linea_coordinator", readPoolSize = 10, readPipeliningLimit = 10, - transactionalPoolSize = 10 + transactionalPoolSize = 10, ) private val persistenceRetryConfig = PersistenceRetryConfig( maxRetries = null, - backoffDelay = Duration.parse("PT1S") + backoffDelay = Duration.parse("PT1S"), ) private val l1Config = L1Config( @@ -194,7 +194,7 @@ class CoordinatorConfigTest { blockRangeLoopLimit = 500U, _ethFeeHistoryEndpoint = null, _genesisStateRootHash = "0x072ead6777750dc20232d1cee8dc9a395c2d350df4bbaa5096c6f59b214dcecd", - _genesisShnarfV6 = "0x47452a1b9ebadfe02bdd02f580fa1eba17680d57eec968a591644d05d78ee84f" + _genesisShnarfV6 = "0x47452a1b9ebadfe02bdd02f580fa1eba17680d57eec968a591644d05d78ee84f", ) private val l2Config = L2Config( @@ -208,7 +208,7 @@ class CoordinatorConfigTest { lastHashSearchWindow = 25U, anchoringReceiptPollingInterval = Duration.parse("PT01S"), maxReceiptRetries = 120U, - newBlockPollingInterval = Duration.parse("PT1S") + newBlockPollingInterval = Duration.parse("PT1S"), ) private val finalizationSigner = SignerConfig( @@ -219,9 +219,9 @@ class CoordinatorConfigTest { keepAlive = true, publicKey = "ba5734d8f7091719471e7f7ed6b9df170dc70cc661ca05e688601ad984f068b0d67351e5f06073092499336ab0839ef8a521afd334e5" + - "3807205fa2f08eec74f4" + "3807205fa2f08eec74f4", ), - web3j = Web3jConfig(Masked("0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d")) + web3j = Web3jConfig(Masked("0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d")), ) private val dataSubmissionSigner = SignerConfig( @@ -232,9 +232,9 @@ class CoordinatorConfigTest { keepAlive = true, publicKey = "9d9031e97dd78ff8c15aa86939de9b1e791066a0224e331bc962a2099a7b1f0464b8bbafe1535f2301c72c2cb3535b172da30b02686a" + - "b0393d348614f157fbdb" + "b0393d348614f157fbdb", ), - web3j = Web3jConfig(Masked("0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a")) + web3j = Web3jConfig(Masked("0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a")), ) private val l2SignerConfig = SignerConfig( type = SignerConfig.Type.Web3j, @@ -244,43 +244,43 @@ class CoordinatorConfigTest { keepAlive = true, publicKey = "4a788ad6fa008beed58de6418369717d7492f37d173d70e2c26d9737e2c6eeae929452ef8602a19410844db3e200a0e73f5208fd7625" + - "9a8766b73953fc3e7023" + "9a8766b73953fc3e7023", ), - web3j = Web3jConfig(Masked("0x4d01ae6487860981699236a58b68f807ee5f17b12df5740b85cf4c4653be0f55")) + web3j = Web3jConfig(Masked("0x4d01ae6487860981699236a58b68f807ee5f17b12df5740b85cf4c4653be0f55")), ) private val l2NetworkGasPricingRequestRetryConfig = RequestRetryConfig( maxRetries = 3u, timeout = 6.seconds, backoffDelay = 1.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ) private val l2NetworkGasPricingServiceConfig = L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = 50U, - feeHistoryRewardPercentile = 15.0 + feeHistoryRewardPercentile = 15.0, ), legacy = L2NetworkGasPricingService.LegacyGasPricingCalculatorConfig( legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_000.0, feeLowerBound = 90_000_000.0, - feeMargin = 0.0 + feeMargin = 0.0, ), transactionCostCalculatorConfig = TransactionCostCalculator.Config( sampleTransactionCostMultiplier = 1.0, fixedCostWei = 3000000u, compressedTxSize = 125, - expectedGas = 21000 + expectedGas = 21000, ), - naiveGasPricingCalculatorConfig = null + naiveGasPricingCalculatorConfig = null, ), jsonRpcGasPriceUpdaterConfig = GasPriceUpdaterImpl.Config( gethEndpoints = listOf( - URI("http://l2-node:8545/").toURL() + URI("http://l2-node:8545/").toURL(), ), besuEndPoints = listOf(), - retryConfig = l2NetworkGasPricingRequestRetryConfig + retryConfig = l2NetworkGasPricingRequestRetryConfig, ), jsonRpcPriceUpdateInterval = 12.seconds, extraDataPricingPropagationEnabled = true, @@ -289,21 +289,21 @@ class CoordinatorConfigTest { blobSubmissionExpectedExecutionGas = 213_000u, bytesPerDataSubmission = 131072u, expectedBlobGas = 131072u, - margin = 4.0 + margin = 4.0, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_001.0, feeLowerBound = 90_000_001.0, - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = 3000u, - ethGasPriceMultiplier = 1.2 + ethGasPriceMultiplier = 1.2, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( - sequencerEndpoint = URI(/* str = */ "http://sequencer:8545/").toURL(), - retryConfig = l2NetworkGasPricingRequestRetryConfig - ) + sequencerEndpoint = URI("http://sequencer:8545/").toURL(), + retryConfig = l2NetworkGasPricingRequestRetryConfig, + ), ) private val l1DynamicGasPriceCapServiceConfig = L1DynamicGasPriceCapServiceConfig( @@ -318,18 +318,18 @@ class CoordinatorConfigTest { gasPriceCapsCheckCoefficient = 0.9, historicBaseFeePerBlobGasLowerBound = 100_000_000u, historicAvgRewardConstant = 100_000_000u, - timeOfDayMultipliers = expectedTimeOfDayMultipliers + timeOfDayMultipliers = expectedTimeOfDayMultipliers, ), feeHistoryFetcher = L1DynamicGasPriceCapServiceConfig.FeeHistoryFetcher( fetchInterval = Duration.parse("PT1S"), maxBlockCount = 1000U, rewardPercentiles = listOf(10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0), numOfBlocksBeforeLatest = 4U, - endpoint = null + endpoint = null, ), feeHistoryStorage = L1DynamicGasPriceCapServiceConfig.FeeHistoryStorage( - storagePeriod = Duration.parse("PT2M") - ) + storagePeriod = Duration.parse("PT2M"), + ), ) private val coordinatorConfig = CoordinatorConfig( @@ -351,11 +351,11 @@ class CoordinatorConfigTest { l2Signer = l2SignerConfig, messageAnchoring = MessageAnchoringConfigTomlDto().reified( l1DefaultEndpoint = l1Config.rpcEndpoint, - l2DefaultEndpoint = l2Config.rpcEndpoint + l2DefaultEndpoint = l2Config.rpcEndpoint, ), l2NetworkGasPricingService = l2NetworkGasPricingServiceConfig, l1DynamicGasPriceCapService = l1DynamicGasPriceCapServiceConfig, - proversConfig = proversConfig + proversConfig = proversConfig, ) } @@ -371,18 +371,18 @@ class CoordinatorConfigTest { Path.of("../../config/coordinator/coordinator-docker-traces-v2-override.config.toml"), Path.of("../../config/coordinator/coordinator-docker-web3signer-override.config.toml"), Path.of("../../config/coordinator/coordinator-local-dev.config.overrides.toml"), - Path.of("../../config/coordinator/coordinator-local-dev.config-traces-v2.overrides.toml") + Path.of("../../config/coordinator/coordinator-local-dev.config-traces-v2.overrides.toml"), ), tracesLimitsFileV2 = Path.of("../../config/common/traces-limits-v2.toml"), gasPriceCapTimeOfDayMultipliersFile = Path.of("../../config/common/gas-price-cap-time-of-day-multipliers.toml"), - smartContractErrorsFile = Path.of("../../config/common/smart-contract-errors.toml") + smartContractErrorsFile = Path.of("../../config/common/smart-contract-errors.toml"), ) } private fun pathToResource(resource: String): Path { return Paths.get( this::class.java.classLoader.getResource(resource)?.toURI() - ?: error("Resource not found: $resource") + ?: error("Resource not found: $resource"), ) } @@ -392,7 +392,7 @@ class CoordinatorConfigTest { coordinatorConfigFiles = listOf(pathToResource("configs/coordinator.config.toml")), tracesLimitsFileV2 = pathToResource("configs/traces-limits-v2.toml"), gasPriceCapTimeOfDayMultipliersFile = pathToResource("configs/gas-price-cap-time-of-day-multipliers.toml"), - smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml") + smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml"), ) assertEquals(coordinatorConfig, configs) @@ -404,18 +404,18 @@ class CoordinatorConfigTest { val config = loadConfigs( coordinatorConfigFiles = listOf( pathToResource("configs/coordinator.config.toml"), - pathToResource("configs/coordinator-web3signer-override.config.toml") + pathToResource("configs/coordinator-web3signer-override.config.toml"), ), tracesLimitsFileV2 = pathToResource("configs/traces-limits-v2.toml"), gasPriceCapTimeOfDayMultipliersFile = pathToResource("configs/gas-price-cap-time-of-day-multipliers.toml"), - smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml") + smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml"), ) val expectedConfig = coordinatorConfig.copy( finalizationSigner = finalizationSigner.copy(type = SignerConfig.Type.Web3Signer), dataSubmissionSigner = dataSubmissionSigner.copy(type = SignerConfig.Type.Web3Signer), - l2Signer = l2SignerConfig.copy(type = SignerConfig.Type.Web3Signer) + l2Signer = l2SignerConfig.copy(type = SignerConfig.Type.Web3Signer), ) assertThat(config).isEqualTo(expectedConfig) @@ -426,11 +426,11 @@ class CoordinatorConfigTest { val config = loadConfigs( coordinatorConfigFiles = listOf( pathToResource("configs/coordinator.config.toml"), - pathToResource("configs/coordinator-traces-v2-override.config.toml") + pathToResource("configs/coordinator-traces-v2-override.config.toml"), ), tracesLimitsFileV2 = pathToResource("configs/traces-limits-v2.toml"), gasPriceCapTimeOfDayMultipliersFile = pathToResource("configs/gas-price-cap-time-of-day-multipliers.toml"), - smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml") + smartContractErrorsFile = pathToResource("configs/smart-contract-errors.toml"), ) val expectedConfig = @@ -441,31 +441,31 @@ class CoordinatorConfigTest { transactionCostCalculatorConfig = l2NetworkGasPricingServiceConfig.legacy.transactionCostCalculatorConfig?.copy( compressedTxSize = 350, - expectedGas = 29400 - ) - ) + expectedGas = 29400, + ), + ), ), traces = tracesConfig.copy( blobCompressorVersion = BlobCompressorVersion.V1_2, expectedTracesApiVersionV2 = "v0.8.0-rc8", conflationV2 = tracesConfig.conflationV2, - countersV2 = tracesConfig.countersV2 + countersV2 = tracesConfig.countersV2, ), proversConfig = proversConfig.copy( proverA = proversConfig.proverA.copy( execution = proversConfig.proverA.execution.copy( requestsDirectory = Path.of("/data/prover/v3/execution/requests"), - responsesDirectory = Path.of("/data/prover/v3/execution/responses") + responsesDirectory = Path.of("/data/prover/v3/execution/responses"), ), blobCompression = proversConfig.proverA.blobCompression.copy( requestsDirectory = Path.of("/data/prover/v3/compression/requests"), - responsesDirectory = Path.of("/data/prover/v3/compression/responses") + responsesDirectory = Path.of("/data/prover/v3/compression/responses"), ), proofAggregation = proversConfig.proverA.proofAggregation.copy( requestsDirectory = Path.of("/data/prover/v3/aggregation/requests"), - responsesDirectory = Path.of("/data/prover/v3/aggregation/responses") - ) - ) + responsesDirectory = Path.of("/data/prover/v3/aggregation/responses"), + ), + ), ), messageAnchoring = MessageAnchoringConfigTomlDto().copy( l1Endpoint = URI("http://l1-endpoint-for-anchoring:8545").toURL(), @@ -475,12 +475,12 @@ class CoordinatorConfigTest { anchoringTickInterval = 1.seconds.toJavaDuration(), l1RequestRetries = RequestRetryConfigTomlFriendly( maxRetries = 10, - failuresWarningThreshold = 1 - ) + failuresWarningThreshold = 1, + ), ).reified( l1DefaultEndpoint = l1Config.rpcEndpoint, - l2DefaultEndpoint = l2Config.rpcEndpoint - ) + l2DefaultEndpoint = l2Config.rpcEndpoint, + ), ) assertThat(config).isEqualTo(expectedConfig) @@ -489,7 +489,7 @@ class CoordinatorConfigTest { @Test fun invalidConfigReturnsErrorResult() { val configsResult = loadConfigsOrError( - configFiles = listOf(pathToResource("configs/coordinator.config.toml")) + configFiles = listOf(pathToResource("configs/coordinator.config.toml")), ) assertThat(configsResult.getError()).contains("'extraField': Missing String from config") @@ -498,17 +498,17 @@ class CoordinatorConfigTest { @Test fun testInvalidAggregationByTargetBlockNumberWhenL2InclusiveBlockNumberToStopAndFlushAggregationSpecified() { val aggregationConfigWithoutTargetBlockNumber = aggregationConfig.copy( - _targetEndBlocks = emptyList() + _targetEndBlocks = emptyList(), ) val conflationConfigWithTargetBlockNumber = conflationConfig.copy( - _conflationTargetEndBlockNumbers = listOf(100L) + _conflationTargetEndBlockNumbers = listOf(100L), ) val exception = assertThrows { coordinatorConfig.copy( l2InclusiveBlockNumberToStopAndFlushAggregation = 100uL, proofAggregation = aggregationConfigWithoutTargetBlockNumber, - conflation = conflationConfigWithTargetBlockNumber + conflation = conflationConfigWithTargetBlockNumber, ) } assertThat(exception.message) @@ -518,40 +518,40 @@ class CoordinatorConfigTest { @Test fun testInvalidConflationByTargetBlockNumberWhenL2InclusiveBlockNumberToStopAndFlushAggregationSpecified() { val aggregationConfigWithTargetBlockNumber = aggregationConfig.copy( - _targetEndBlocks = listOf(100L) + _targetEndBlocks = listOf(100L), ) val conflationConfigWithoutTargetBlockNumber = conflationConfig.copy( - _conflationTargetEndBlockNumbers = emptyList() + _conflationTargetEndBlockNumbers = emptyList(), ) val exception = assertThrows { coordinatorConfig.copy( l2InclusiveBlockNumberToStopAndFlushAggregation = 100uL, proofAggregation = aggregationConfigWithTargetBlockNumber, - conflation = conflationConfigWithoutTargetBlockNumber + conflation = conflationConfigWithoutTargetBlockNumber, ) } assertThat(exception.message) .isEqualTo( "conflation.conflationTargetEndBlockNumbers should contain the " + - "l2InclusiveBlockNumberToStopAndFlushAggregation" + "l2InclusiveBlockNumberToStopAndFlushAggregation", ) } @Test fun testValidAggrAndConflationByTargetBlockNumberWhenL2InclusiveBlockNumberToStopAndFlushAggregationSpecified() { val aggregationConfigWithoutSwithBlockNumber = aggregationConfig.copy( - _targetEndBlocks = listOf(10L, 100L) + _targetEndBlocks = listOf(10L, 100L), ) val conflationConfigWithTargetBlockNumber = conflationConfig.copy( - _conflationTargetEndBlockNumbers = listOf(100L) + _conflationTargetEndBlockNumbers = listOf(100L), ) assertDoesNotThrow { coordinatorConfig.copy( l2InclusiveBlockNumberToStopAndFlushAggregation = 100uL, proofAggregation = aggregationConfigWithoutSwithBlockNumber, - conflation = conflationConfigWithTargetBlockNumber + conflation = conflationConfigWithTargetBlockNumber, ) } } diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedGasPriceMultipliers.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedGasPriceMultipliers.kt index d872e96a..5913056f 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedGasPriceMultipliers.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedGasPriceMultipliers.kt @@ -168,5 +168,5 @@ val expectedTimeOfDayMultipliers = mapOf( "SATURDAY_20" to 1.5073787902995706, "SATURDAY_21" to 1.5605139580010123, "SATURDAY_22" to 1.5885303316932382, - "SATURDAY_23" to 1.6169891066719597 + "SATURDAY_23" to 1.6169891066719597, ) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedTracesLimitsV2.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedTracesLimitsV2.kt index 82f6447f..f463c525 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedTracesLimitsV2.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ExpectedTracesLimitsV2.kt @@ -55,6 +55,6 @@ val expectedTracesLimitsV2 = TracesCountersV2( TracingModuleV2.BLOCK_KECCAK to 46u, TracingModuleV2.BLOCK_L1_SIZE to 47u, TracingModuleV2.BLOCK_L2_L1_LOGS to 48u, - TracingModuleV2.BLOCK_TRANSACTIONS to 49u - ) + TracingModuleV2.BLOCK_TRANSACTIONS to 49u, + ), ) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfigTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfigTest.kt index 3b4b1337..08f87d42 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfigTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/L2NetworkGasPricingConfigTest.kt @@ -21,7 +21,7 @@ import kotlin.time.toJavaDuration class L2NetworkGasPricingConfigTest { data class Config( - val l2NetworkGasPricing: L2NetworkGasPricingTomlDto + val l2NetworkGasPricing: L2NetworkGasPricingTomlDto, ) private fun parseConfig(toml: String): L2NetworkGasPricingTomlDto { @@ -135,7 +135,7 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3, timeout = 6.seconds.toJavaDuration(), backoffDelay = 1.seconds.toJavaDuration(), - failuresWarningThreshold = 2 + failuresWarningThreshold = 2, ), priceUpdateInterval = Duration.parse("PT12S"), @@ -152,29 +152,29 @@ class L2NetworkGasPricingConfigTest { naiveGasPricing = NaiveGasPricingTomlDto( baseFeeCoefficient = 0.1, priorityFeeCoefficient = 1.0, - baseFeeBlobCoefficient = 0.1 - ) + baseFeeBlobCoefficient = 0.1, + ), ), variableCostPricing = VariableCostPricingTomlDto( gasPriceFixedCost = 3000000u, legacyFeesMultiplier = 1.2, margin = 4.0, variableCostUpperBound = 10_000_000_001u, - variableCostLowerBound = 90_000_001u + variableCostLowerBound = 90_000_001u, ), jsonRpcPricingPropagation = JsonRpcPricingPropagationTomlDto( gethGasPriceUpdateRecipients = listOf( URI("http://traces-node:8545/").toURL(), - URI("http://l2-node:8545/").toURL() + URI("http://l2-node:8545/").toURL(), ), besuGasPriceUpdateRecipients = listOf( - URI("http://sequencer:8545/").toURL() - ) + URI("http://sequencer:8545/").toURL(), + ), ), extraDataPricingPropagation = ExtraDataPricingPropagationTomlDto( - extraDataUpdateRecipient = URI("http://sequencer:8545/").toURL() - ) - ) + extraDataUpdateRecipient = URI("http://sequencer:8545/").toURL(), + ), + ), ) } @@ -187,7 +187,7 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3, timeout = 6.seconds.toJavaDuration(), backoffDelay = 1.seconds.toJavaDuration(), - failuresWarningThreshold = 2 + failuresWarningThreshold = 2, ), priceUpdateInterval = Duration.parse("PT12S"), @@ -201,28 +201,28 @@ class L2NetworkGasPricingConfigTest { type = LegacyGasPricingTomlDto.Type.SampleTransaction, gasPriceUpperBound = 10_000_000_000u, gasPriceLowerBound = 90_000_000u, - naiveGasPricing = null + naiveGasPricing = null, ), variableCostPricing = VariableCostPricingTomlDto( gasPriceFixedCost = 3000000u, legacyFeesMultiplier = 1.2, margin = 4.0, variableCostUpperBound = 10_000_000_001u, - variableCostLowerBound = 90_000_001u + variableCostLowerBound = 90_000_001u, ), jsonRpcPricingPropagation = JsonRpcPricingPropagationTomlDto( gethGasPriceUpdateRecipients = listOf( URI("http://traces-node:8545/").toURL(), - URI("http://l2-node:8545/").toURL() + URI("http://l2-node:8545/").toURL(), ), besuGasPriceUpdateRecipients = listOf( - URI("http://sequencer:8545/").toURL() - ) + URI("http://sequencer:8545/").toURL(), + ), ), extraDataPricingPropagation = ExtraDataPricingPropagationTomlDto( - extraDataUpdateRecipient = URI("http://sequencer:8545/").toURL() - ) - ) + extraDataUpdateRecipient = URI("http://sequencer:8545/").toURL(), + ), + ), ) } @@ -233,14 +233,14 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3u, timeout = 6.seconds, backoffDelay = 1.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ) assertThat(config).isEqualTo( L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = 50U, - feeHistoryRewardPercentile = 15.0 + feeHistoryRewardPercentile = 15.0, ), legacy = L2NetworkGasPricingService.LegacyGasPricingCalculatorConfig( naiveGasPricingCalculatorConfig = GasUsageRatioWeightedAverageFeesCalculator.Config( @@ -248,24 +248,24 @@ class L2NetworkGasPricingConfigTest { priorityFeeCoefficient = 1.0, baseFeeBlobCoefficient = 0.1, blobSubmissionExpectedExecutionGas = 213_000, - expectedBlobGas = 131072 + expectedBlobGas = 131072, ), legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( 10_000_000_000.0, 90_000_000.0, - 0.0 + 0.0, ), - transactionCostCalculatorConfig = null + transactionCostCalculatorConfig = null, ), jsonRpcGasPriceUpdaterConfig = GasPriceUpdaterImpl.Config( gethEndpoints = listOf( URI("http://traces-node:8545/").toURL(), - URI("http://l2-node:8545/").toURL() + URI("http://l2-node:8545/").toURL(), ), besuEndPoints = listOf( - URI("http://sequencer:8545/").toURL() + URI("http://sequencer:8545/").toURL(), ), - retryConfig = l2NetworkGasPricingRequestretryConfig + retryConfig = l2NetworkGasPricingRequestretryConfig, ), jsonRpcPriceUpdateInterval = 12.seconds, extraDataPricingPropagationEnabled = true, @@ -274,22 +274,22 @@ class L2NetworkGasPricingConfigTest { blobSubmissionExpectedExecutionGas = 213_000u, bytesPerDataSubmission = 131072u, expectedBlobGas = 131072u, - margin = 4.0 + margin = 4.0, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_001.0, feeLowerBound = 90_000_001.0, - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = 3000u, - ethGasPriceMultiplier = 1.2 + ethGasPriceMultiplier = 1.2, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( - sequencerEndpoint = URI(/* str = */ "http://sequencer:8545/").toURL(), - retryConfig = l2NetworkGasPricingRequestretryConfig - ) - ) + sequencerEndpoint = URI("http://sequencer:8545/").toURL(), + retryConfig = l2NetworkGasPricingRequestretryConfig, + ), + ), ) } @@ -300,38 +300,38 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3u, timeout = 6.seconds, backoffDelay = 1.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ) assertThat(config).isEqualTo( L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = 50U, - feeHistoryRewardPercentile = 15.0 + feeHistoryRewardPercentile = 15.0, ), legacy = L2NetworkGasPricingService.LegacyGasPricingCalculatorConfig( naiveGasPricingCalculatorConfig = null, legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( 10_000_000_000.0, 90_000_000.0, - 0.0 + 0.0, ), transactionCostCalculatorConfig = TransactionCostCalculator.Config( sampleTransactionCostMultiplier = 1.0, fixedCostWei = 3000000u, compressedTxSize = 125, - expectedGas = 21000 - ) + expectedGas = 21000, + ), ), jsonRpcGasPriceUpdaterConfig = GasPriceUpdaterImpl.Config( gethEndpoints = listOf( URI("http://traces-node:8545/").toURL(), - URI("http://l2-node:8545/").toURL() + URI("http://l2-node:8545/").toURL(), ), besuEndPoints = listOf( - URI("http://sequencer:8545/").toURL() + URI("http://sequencer:8545/").toURL(), ), - retryConfig = l2NetworkGasPricingRequestretryConfig + retryConfig = l2NetworkGasPricingRequestretryConfig, ), jsonRpcPriceUpdateInterval = 12.seconds, extraDataPricingPropagationEnabled = true, @@ -340,22 +340,22 @@ class L2NetworkGasPricingConfigTest { blobSubmissionExpectedExecutionGas = 213_000u, bytesPerDataSubmission = 131072u, expectedBlobGas = 131072u, - margin = 4.0 + margin = 4.0, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_001.0, feeLowerBound = 90_000_001.0, - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = 3000u, - ethGasPriceMultiplier = 1.2 + ethGasPriceMultiplier = 1.2, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( - sequencerEndpoint = URI(/* str = */ "http://sequencer:8545/").toURL(), - retryConfig = l2NetworkGasPricingRequestretryConfig - ) - ) + sequencerEndpoint = URI("http://sequencer:8545/").toURL(), + retryConfig = l2NetworkGasPricingRequestretryConfig, + ), + ), ) } @@ -400,28 +400,28 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3u, timeout = 6.seconds, backoffDelay = 1.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ) assertThat(config).isEqualTo( L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = 50U, - feeHistoryRewardPercentile = 15.0 + feeHistoryRewardPercentile = 15.0, ), legacy = L2NetworkGasPricingService.LegacyGasPricingCalculatorConfig( naiveGasPricingCalculatorConfig = null, legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( 10_000_000_000.0, 90_000_000.0, - 0.0 + 0.0, ), transactionCostCalculatorConfig = TransactionCostCalculator.Config( sampleTransactionCostMultiplier = 1.0, fixedCostWei = 3000000u, compressedTxSize = 125, - expectedGas = 21000 - ) + expectedGas = 21000, + ), ), jsonRpcGasPriceUpdaterConfig = null, jsonRpcPriceUpdateInterval = 12.seconds, @@ -431,22 +431,22 @@ class L2NetworkGasPricingConfigTest { blobSubmissionExpectedExecutionGas = 213_000u, bytesPerDataSubmission = 131072u, expectedBlobGas = 131072u, - margin = 4.0 + margin = 4.0, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_001.0, feeLowerBound = 90_000_001.0, - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = 3000u, - ethGasPriceMultiplier = 1.2 + ethGasPriceMultiplier = 1.2, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( - sequencerEndpoint = URI(/* str = */ "http://sequencer:8545/").toURL(), - retryConfig = l2NetworkGasPricingRequestretryConfig - ) - ) + sequencerEndpoint = URI("http://sequencer:8545/").toURL(), + retryConfig = l2NetworkGasPricingRequestretryConfig, + ), + ), ) } @@ -496,28 +496,28 @@ class L2NetworkGasPricingConfigTest { maxRetries = 3u, timeout = 6.seconds, backoffDelay = 1.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ) assertThat(config).isEqualTo( L2NetworkGasPricingService.Config( feeHistoryFetcherConfig = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount = 50U, - feeHistoryRewardPercentile = 15.0 + feeHistoryRewardPercentile = 15.0, ), legacy = L2NetworkGasPricingService.LegacyGasPricingCalculatorConfig( naiveGasPricingCalculatorConfig = null, legacyGasPricingCalculatorBounds = BoundableFeeCalculator.Config( 10_000_000_000.0, 90_000_000.0, - 0.0 + 0.0, ), transactionCostCalculatorConfig = TransactionCostCalculator.Config( sampleTransactionCostMultiplier = 1.0, fixedCostWei = 3000000u, compressedTxSize = 125, - expectedGas = 21000 - ) + expectedGas = 21000, + ), ), jsonRpcGasPriceUpdaterConfig = null, jsonRpcPriceUpdateInterval = 12.seconds, @@ -527,22 +527,22 @@ class L2NetworkGasPricingConfigTest { blobSubmissionExpectedExecutionGas = 213_000u, bytesPerDataSubmission = 131072u, expectedBlobGas = 131072u, - margin = 4.0 + margin = 4.0, ), variableFeesCalculatorBounds = BoundableFeeCalculator.Config( feeUpperBound = 10_000_000_001.0, feeLowerBound = 90_000_001.0, - feeMargin = 0.0 + feeMargin = 0.0, ), extraDataCalculatorConfig = MinerExtraDataV1CalculatorImpl.Config( fixedCostInKWei = 3000u, - ethGasPriceMultiplier = 1.2 + ethGasPriceMultiplier = 1.2, ), extraDataUpdaterConfig = ExtraDataV1UpdaterImpl.Config( - sequencerEndpoint = URI(/* str = */ "http://sequencer:8545/").toURL(), - retryConfig = l2NetworkGasPricingRequestretryConfig - ) - ) + sequencerEndpoint = URI("http://sequencer:8545/").toURL(), + retryConfig = l2NetworkGasPricingRequestretryConfig, + ), + ), ) } } diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfigTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfigTest.kt index 952c5f5e..d87caa2a 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfigTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/MessageAnchoringConfigTest.kt @@ -14,7 +14,7 @@ class MessageAnchoringConfigTest { private val l1DefaultEndpoint = URI("http://l1-default-rpc-endpoint:8545").toURL() private val l2DefaultEndpoint = URI("http://l2-default-rpc-endpoint:8545").toURL() data class Config( - val messageAnchoring: MessageAnchoringConfigTomlDto = MessageAnchoringConfigTomlDto() + val messageAnchoring: MessageAnchoringConfigTomlDto = MessageAnchoringConfigTomlDto(), ) private fun parseConfig(toml: String): MessageAnchoringConfig { @@ -27,7 +27,7 @@ class MessageAnchoringConfigTest { .let { it.messageAnchoring.reified( l1DefaultEndpoint = l1DefaultEndpoint, - l2DefaultEndpoint = l2DefaultEndpoint + l2DefaultEndpoint = l2DefaultEndpoint, ) } } @@ -74,13 +74,13 @@ class MessageAnchoringConfigTest { maxRetries = 10u, timeout = 100.seconds, backoffDelay = 11.seconds, - failuresWarningThreshold = 1u + failuresWarningThreshold = 1u, ), l2RequestRetryConfig = RetryConfig( maxRetries = 20u, timeout = 200.seconds, backoffDelay = 21.seconds, - failuresWarningThreshold = 2u + failuresWarningThreshold = 2u, ), l1EventPollingInterval = 30.seconds, l1EventPollingTimeout = 6.seconds, @@ -88,8 +88,8 @@ class MessageAnchoringConfigTest { l1EventSearchBlockChunk = 123u, anchoringTickInterval = 3.seconds, messageQueueCapacity = 321u, - maxMessagesToAnchorPerL2Transaction = 54u - ) + maxMessagesToAnchorPerL2Transaction = 54u, + ), ) } @@ -111,13 +111,13 @@ class MessageAnchoringConfigTest { maxRetries = null, timeout = null, backoffDelay = 1.seconds, - failuresWarningThreshold = 3u + failuresWarningThreshold = 3u, ), l2RequestRetryConfig = RetryConfig( maxRetries = null, timeout = null, backoffDelay = 1.seconds, - failuresWarningThreshold = 3u + failuresWarningThreshold = 3u, ), l1EventPollingInterval = 12.seconds, l1EventPollingTimeout = 6.seconds, @@ -125,8 +125,8 @@ class MessageAnchoringConfigTest { l1EventSearchBlockChunk = 1000u, anchoringTickInterval = 2.seconds, messageQueueCapacity = 10_000u, - maxMessagesToAnchorPerL2Transaction = 100u - ) + maxMessagesToAnchorPerL2Transaction = 100u, + ), ) } } diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfigTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfigTest.kt index e3511755..2bb13d88 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfigTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/app/config/ProverConfigTest.kt @@ -13,7 +13,7 @@ import kotlin.time.Duration.Companion.seconds class ProverConfigTest { data class Config( - val prover: ProverConfigTomlDto + val prover: ProverConfigTomlDto, ) private fun parseConfig(toml: String): ProversConfig { @@ -62,8 +62,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".OVERRIDE_inprogress_coordinator_writing", inprogressProvingSuffixPattern = "OVERRIDE_\\.inprogress\\.prover.*", pollingInterval = 10.seconds, - pollingTimeout = 10.minutes - ) + pollingTimeout = 10.minutes, + ), ) assertThat(config.blobCompression).isEqualTo( FileBasedProverConfig( @@ -72,8 +72,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", inprogressProvingSuffixPattern = "\\.inprogress\\.prover.*", pollingInterval = 20.seconds, - pollingTimeout = 20.minutes - ) + pollingTimeout = 20.minutes, + ), ) assertThat(config.proofAggregation).isEqualTo( FileBasedProverConfig( @@ -82,8 +82,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", inprogressProvingSuffixPattern = "\\.inprogress\\.prover.*", pollingInterval = 10.seconds, - pollingTimeout = 10.minutes - ) + pollingTimeout = 10.minutes, + ), ) } @@ -122,8 +122,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".NEW_OVERRIDE_2_inprogress_coordinator_writing", inprogressProvingSuffixPattern = "NEW_OVERRIDE_2\\.inprogress\\.prover.*", pollingInterval = 10.seconds, - pollingTimeout = 5.minutes - ) + pollingTimeout = 5.minutes, + ), ) assertThat(config.proverB!!.blobCompression).isEqualTo( FileBasedProverConfig( @@ -132,8 +132,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".NEW_OVERRIDE_inprogress_coordinator_writing", inprogressProvingSuffixPattern = "\\.inprogress\\.prover.*", pollingInterval = 12.seconds, - pollingTimeout = 12.minutes - ) + pollingTimeout = 12.minutes, + ), ) assertThat(config.proverB!!.proofAggregation).isEqualTo( FileBasedProverConfig( @@ -142,8 +142,8 @@ class ProverConfigTest { inprogressRequestWritingSuffix = ".NEW_OVERRIDE_inprogress_coordinator_writing", inprogressProvingSuffixPattern = "\\.inprogress\\.prover.*", pollingInterval = 10.seconds, - pollingTimeout = 5.minutes - ) + pollingTimeout = 5.minutes, + ), ) } } diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitorTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitorTest.kt index 802a555a..22f22316 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitorTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/coordinator/blockcreation/BlockCreationMonitorTest.kt @@ -44,7 +44,7 @@ class BlockCreationMonitorTest { pollingInterval = 100.milliseconds, blocksToFinalization = 2L, blocksFetchLimit = 500, - lastL2BlockNumberToProcessInclusive = null + lastL2BlockNumberToProcessInclusive = null, ) private lateinit var vertx: Vertx private lateinit var lastProvenBlockNumberProvider: LastProvenBlockNumberProviderDouble @@ -62,7 +62,7 @@ class BlockCreationMonitorTest { } private class LastProvenBlockNumberProviderDouble( - initialValue: ULong + initialValue: ULong, ) : LastProvenBlockNumberProviderAsync { var lastProvenBlock: AtomicLong = AtomicLong(initialValue.toLong()) override fun getLastProvenBlockNumber(): SafeFuture { @@ -73,7 +73,7 @@ class BlockCreationMonitorTest { fun createBlockCreationMonitor( startingBlockNumberExclusive: Long = 99, blockCreationListener: BlockCreationListener = this.blockCreationListener, - config: BlockCreationMonitor.Config = this.config + config: BlockCreationMonitor.Config = this.config, ): BlockCreationMonitor { return BlockCreationMonitor( this.vertx, @@ -81,7 +81,7 @@ class BlockCreationMonitorTest { startingBlockNumberExclusive = startingBlockNumberExclusive, blockCreationListener, lastProvenBlockNumberProvider, - config + config, ) } @@ -94,14 +94,14 @@ class BlockCreationMonitorTest { fakeL2RpcNode = TestingJsonRpcServer( vertx = vertx, recordRequestsResponses = true, - responseObjectMapper = ethApiObjectMapper + responseObjectMapper = ethApiObjectMapper, ) blockCreationListener = BlockCreationListenerDouble() web3jClient = ExtendedWeb3JImpl( createWeb3jHttpClient( rpcUrl = "http://localhost:${fakeL2RpcNode.boundPort}", - log = LogManager.getLogger("test.client.l2.web3j") - ) + log = LogManager.getLogger("test.client.l2.web3j"), + ), ) lastProvenBlockNumberProvider = LastProvenBlockNumberProviderDouble(99u) } @@ -116,7 +116,7 @@ class BlockCreationMonitorTest { startBlockNumber: ULong, numberOfBlocks: Int, startBlockHash: ByteArray = ByteArrayExt.random32(), - startBlockParentHash: ByteArray = ByteArrayExt.random32() + startBlockParentHash: ByteArray = ByteArrayExt.random32(), ): List { var blockHash = startBlockHash var parentHash = startBlockParentHash @@ -124,7 +124,7 @@ class BlockCreationMonitorTest { createBlock( number = startBlockNumber + i.toULong(), hash = blockHash, - parentHash = parentHash + parentHash = parentHash, ).also { blockHash = ByteArrayExt.random32() parentHash = it.hash @@ -147,7 +147,7 @@ class BlockCreationMonitorTest { fun `should stop fetching blocks after lastBlockNumberInclusiveToProcess`() { monitor = createBlockCreationMonitor( startingBlockNumberExclusive = 99, - config = config.copy(lastL2BlockNumberToProcessInclusive = 103u) + config = config.copy(lastL2BlockNumberToProcessInclusive = 103u), ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 20)) @@ -170,7 +170,7 @@ class BlockCreationMonitorTest { fun `should notify lister only after block is considered final on L2`() { monitor = createBlockCreationMonitor( startingBlockNumberExclusive = 99, - config = config.copy(blocksToFinalization = 2, blocksFetchLimit = 500) + config = config.copy(blocksToFinalization = 2, blocksFetchLimit = 500), ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 200)) @@ -217,7 +217,7 @@ class BlockCreationMonitorTest { monitor = createBlockCreationMonitor( startingBlockNumberExclusive = 99, blockCreationListener = fakeBuggyLister, - config = config.copy(blocksToFinalization = 2, lastL2BlockNumberToProcessInclusive = 112u) + config = config.copy(blocksToFinalization = 2, lastL2BlockNumberToProcessInclusive = 112u), ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 20)) @@ -232,14 +232,14 @@ class BlockCreationMonitorTest { // assert it got block only once and in order assertThat(blockCreationListener.blocksReceived.map { it.number }).containsExactly( - 100UL, 101UL, 102UL, 103UL, 104UL, 105UL, 106UL, 107UL, 108UL, 109UL, 110UL + 100UL, 101UL, 102UL, 103UL, 104UL, 105UL, 106UL, 107UL, 108UL, 109UL, 110UL, ) } @Test fun `should be resilient to connection failures`() { monitor = createBlockCreationMonitor( - startingBlockNumberExclusive = 99 + startingBlockNumberExclusive = 99, ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 200)) @@ -268,7 +268,7 @@ class BlockCreationMonitorTest { @Test fun `should stop when reorg is detected above blocksToFinalization limit - manual intervention necessary`() { monitor = createBlockCreationMonitor( - startingBlockNumberExclusive = 99 + startingBlockNumberExclusive = 99, ) // simulate reorg by changing parent hash of block 105 @@ -300,7 +300,7 @@ class BlockCreationMonitorTest { fun `should poll in order when response takes longer that polling interval`() { monitor = createBlockCreationMonitor( startingBlockNumberExclusive = 99, - config = config.copy(pollingInterval = 100.milliseconds) + config = config.copy(pollingInterval = 100.milliseconds), ) val blocks = createBlocks(startBlockNumber = 99u, numberOfBlocks = 20) @@ -318,7 +318,7 @@ class BlockCreationMonitorTest { 102UL, 103UL, 104UL, - 105UL + 105UL, ) } } @@ -326,7 +326,7 @@ class BlockCreationMonitorTest { @Test fun `start allow 2nd call when already started`() { monitor = createBlockCreationMonitor( - startingBlockNumberExclusive = 99 + startingBlockNumberExclusive = 99, ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 5)) monitor.start().get() @@ -337,7 +337,7 @@ class BlockCreationMonitorTest { fun `should stop fetching blocks when gap is greater than fetch limit and resume upon catchup`() { monitor = createBlockCreationMonitor( startingBlockNumberExclusive = 99, - config = config.copy(blocksToFinalization = 0, blocksFetchLimit = 5) + config = config.copy(blocksToFinalization = 0, blocksFetchLimit = 5), ) setupFakeExecutionLayerWithBlocks(createBlocks(startBlockNumber = 99u, numberOfBlocks = 30)) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTrackerTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTrackerTest.kt index f8f58b45..9c24f99b 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTrackerTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTrackerTest.kt @@ -27,23 +27,23 @@ class ConsecutiveProvenBlobsProviderWithLastEndBlockNumberTrackerTest { endBlockNumber = 2UL, startBlockTimestamp = Instant.DISTANT_PAST, endBlockTimestamp = Instant.DISTANT_PAST, - expectedShnarf = Random.nextBytes(32) + expectedShnarf = Random.nextBytes(32), ) val baseBlobAndBatchCounters = BlobAndBatchCounters( blobCounters = baseBlobCounters, - executionProofs = BlockIntervals(1UL, listOf(2UL, 3UL)) + executionProofs = BlockIntervals(1UL, listOf(2UL, 3UL)), ) val expectedEndBLockNumber = 10UL val lastBlobAndBatchCounters = baseBlobAndBatchCounters.copy( - blobCounters = baseBlobCounters.copy(startBlockNumber = 3UL, endBlockNumber = expectedEndBLockNumber) + blobCounters = baseBlobCounters.copy(startBlockNumber = 3UL, endBlockNumber = expectedEndBLockNumber), ) whenever(repositoryMock.findConsecutiveProvenBlobs(any())).thenReturn( SafeFuture.completedFuture( listOf( baseBlobAndBatchCounters, - lastBlobAndBatchCounters - ) - ) + lastBlobAndBatchCounters, + ), + ), ) cache.findConsecutiveProvenBlobs(expectedEndBLockNumber.toLong()) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImplTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImplTest.kt index 97ce5e3b..637eb39b 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImplTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/ForkChoiceUpdaterImplTest.kt @@ -22,12 +22,12 @@ class ForkChoiceUpdaterImplTest { fun dispatchFinalizedBlockNotification_allClientsSuccess() { val mockClient1 = mock() whenever( - mockClient1.rollupForkChoiceUpdated(any()) + mockClient1.rollupForkChoiceUpdated(any()), ) .thenReturn(SafeFuture.completedFuture(Ok(RollupForkChoiceUpdatedResponse("success")))) val mockClient2 = mock() whenever( - mockClient2.rollupForkChoiceUpdated(any()) + mockClient2.rollupForkChoiceUpdated(any()), ) .thenReturn(SafeFuture.completedFuture(Ok(RollupForkChoiceUpdatedResponse("success")))) @@ -43,12 +43,12 @@ class ForkChoiceUpdaterImplTest { fun dispatchFinalizedBlockNotification_someClientsFail() { val mockClient1 = mock() whenever( - mockClient1.rollupForkChoiceUpdated(any()) + mockClient1.rollupForkChoiceUpdated(any()), ) .thenReturn(SafeFuture.completedFuture(Ok(RollupForkChoiceUpdatedResponse("success")))) val mockClient2 = mock() whenever( - mockClient2.rollupForkChoiceUpdated(any()) + mockClient2.rollupForkChoiceUpdated(any()), ) .thenReturn(SafeFuture.completedFuture(Err(ErrorResponse(RollupForkChoiceUpdatedError.UNKNOWN, "")))) diff --git a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/common/SimpleCompositeSafeFutureHandlerTest.kt b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/common/SimpleCompositeSafeFutureHandlerTest.kt index 66d49f2e..4675ea42 100644 --- a/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/common/SimpleCompositeSafeFutureHandlerTest.kt +++ b/coordinator/app/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/common/SimpleCompositeSafeFutureHandlerTest.kt @@ -17,7 +17,7 @@ class SimpleCompositeSafeFutureHandlerTest { handler2Calls.add("handler2:$value") SafeFuture.failedFuture(RuntimeException("Handler 2 failed")) }, - { value: Long -> SafeFuture.completedFuture(handler3Calls.add("handler3:$value")) } + { value: Long -> SafeFuture.completedFuture(handler3Calls.add("handler3:$value")) }, ) SimpleCompositeSafeFutureHandler(handlers).invoke(123) @@ -34,8 +34,11 @@ class SimpleCompositeSafeFutureHandlerTest { val handler3Calls = mutableListOf() val handlers = listOf( { value: Long -> SafeFuture.completedFuture(handler1Calls.add("handler1:$value")) }, - { value: Long -> handler2Calls.add("handler2:$value"); throw RuntimeException("Forced error") }, - { value: Long -> SafeFuture.completedFuture(handler3Calls.add("handler3:$value")) } + { value: Long -> + handler2Calls.add("handler2:$value") + throw RuntimeException("Forced error") + }, + { value: Long -> SafeFuture.completedFuture(handler3Calls.add("handler3:$value")) }, ) SimpleCompositeSafeFutureHandler(handlers).invoke(123) diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ABProverClientRouter.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ABProverClientRouter.kt index 810bc858..0016853a 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ABProverClientRouter.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ABProverClientRouter.kt @@ -5,7 +5,7 @@ import net.consensys.zkevm.coordinator.clients.ProverClient import tech.pegasys.teku.infrastructure.async.SafeFuture class StartBlockNumberBasedSwitchPredicate( - private val switchStartBlockNumberInclusive: ULong + private val switchStartBlockNumberInclusive: ULong, ) where ProofRequest : BlockInterval { fun invoke(proofRequest: ProofRequest): Boolean = proofRequest.startBlockNumber >= switchStartBlockNumberInclusive } @@ -13,7 +13,7 @@ class StartBlockNumberBasedSwitchPredicate( class ABProverClientRouter( private val proverA: ProverClient, private val proverB: ProverClient, - private val switchToProverBPredicate: (ProofRequest) -> Boolean + private val switchToProverBPredicate: (ProofRequest) -> Boolean, ) : ProverClient { override fun requestProof(proofRequest: ProofRequest): SafeFuture { diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/Config.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/Config.kt index 5588f5cb..2b625934 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/Config.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/Config.kt @@ -6,13 +6,13 @@ import kotlin.time.Duration data class ProversConfig( val proverA: ProverConfig, val switchBlockNumberInclusive: ULong?, - val proverB: ProverConfig? + val proverB: ProverConfig?, ) data class ProverConfig( val execution: FileBasedProverConfig, val blobCompression: FileBasedProverConfig, - val proofAggregation: FileBasedProverConfig + val proofAggregation: FileBasedProverConfig, ) data class FileBasedProverConfig( @@ -21,5 +21,5 @@ data class FileBasedProverConfig( val inprogressProvingSuffixPattern: String, val inprogressRequestWritingSuffix: String, val pollingInterval: Duration, - val pollingTimeout: Duration + val pollingTimeout: Duration, ) diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedBlobCompressionProverClientV2.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedBlobCompressionProverClientV2.kt index d89fdff6..bfd7b20b 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedBlobCompressionProverClientV2.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedBlobCompressionProverClientV2.kt @@ -28,13 +28,13 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class FileBasedBlobCompressionProverClientV2( val config: FileBasedProverConfig, val vertx: Vertx, - jsonObjectMapper: ObjectMapper = JsonSerialization.proofResponseMapperV1 + jsonObjectMapper: ObjectMapper = JsonSerialization.proofResponseMapperV1, ) : GenericFileBasedProverClient< BlobCompressionProofRequest, BlobCompressionProof, BlobCompressionProofJsonRequest, - BlobCompressionProofJsonResponse + BlobCompressionProofJsonResponse, >( config = config, vertx = vertx, @@ -42,7 +42,7 @@ class FileBasedBlobCompressionProverClientV2( fileReader = FileReader( vertx, jsonObjectMapper, - BlobCompressionProofJsonResponse::class.java + BlobCompressionProofJsonResponse::class.java, ), requestFileNameProvider = CompressionProofRequestFileNameProvider, responseFileNameProvider = CompressionProofResponseFileNameProvider, @@ -50,7 +50,7 @@ class FileBasedBlobCompressionProverClientV2( requestMapper = FileBasedBlobCompressionProverClientV2::requestDtoMapper, responseMapper = BlobCompressionProofJsonResponse::toDomainObject, proofTypeLabel = "blob", - log = LogManager.getLogger(this::class.java) + log = LogManager.getLogger(this::class.java), ), BlobCompressionProverClientV2 { @@ -59,7 +59,7 @@ class FileBasedBlobCompressionProverClientV2( return ProofIndex( startBlockNumber = request.startBlockNumber, endBlockNumber = request.endBlockNumber, - hash = request.expectedShnarfResult.expectedShnarf + hash = request.expectedShnarfResult.expectedShnarf, ) } diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedExecutionProverClientV2.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedExecutionProverClientV2.kt index 6f049744..fb87bfa0 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedExecutionProverClientV2.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedExecutionProverClientV2.kt @@ -26,7 +26,7 @@ data class BatchExecutionProofRequestDto( val tracesEngineVersion: String, val type2StateManagerVersion: String?, val zkStateMerkleProof: ArrayNode, - val blocksData: List + val blocksData: List, ) data class RlpBridgeLogsDto(val rlp: String, val bridgeLogs: List) @@ -40,7 +40,7 @@ data class BridgeLogsDto( val blockNumber: String, val address: String, val data: String, - val topics: List + val topics: List, ) { companion object { fun fromDomainObject(ethLog: EthLog): BridgeLogsDto { @@ -53,14 +53,14 @@ data class BridgeLogsDto( blockNumber = ethLog.blockNumber.toHexString(), address = ethLog.address.encodeHex(), data = ethLog.data.encodeHex(), - topics = ethLog.topics.map { it.encodeHex() } + topics = ethLog.topics.map { it.encodeHex() }, ) } } } internal class ExecutionProofRequestDtoMapper( - private val encoder: BlockEncoder = BlockRLPEncoder + private val encoder: BlockEncoder = BlockRLPEncoder, ) : (BatchExecutionProofRequestV1) -> SafeFuture { override fun invoke(request: BatchExecutionProofRequestV1): SafeFuture { val blocksData = request.blocks.map { block -> @@ -79,8 +79,8 @@ internal class ExecutionProofRequestDtoMapper( tracesEngineVersion = request.tracesResponse.tracesEngineVersion, type2StateManagerVersion = request.type2StateData.zkStateManagerVersion, zkStateMerkleProof = request.type2StateData.zkStateMerkleProof, - blocksData = blocksData - ) + blocksData = blocksData, + ), ) } } @@ -105,15 +105,15 @@ class FileBasedExecutionProverClientV2( executionProofRequestFileNameProvider: ProverFileNameProvider = ExecutionProofRequestFileNameProvider( tracesVersion = tracesVersion, - stateManagerVersion = stateManagerVersion + stateManagerVersion = stateManagerVersion, ), - executionProofResponseFileNameProvider: ProverFileNameProvider = ExecutionProofResponseFileNameProvider + executionProofResponseFileNameProvider: ProverFileNameProvider = ExecutionProofResponseFileNameProvider, ) : GenericFileBasedProverClient< BatchExecutionProofRequestV1, BatchExecutionProofResponse, BatchExecutionProofRequestDto, - Any + Any, >( config = config, vertx = vertx, @@ -125,19 +125,19 @@ class FileBasedExecutionProverClientV2( requestMapper = ExecutionProofRequestDtoMapper(), responseMapper = { throw UnsupportedOperationException("Batch execution proof response shall not be parsed!") }, proofTypeLabel = "batch", - log = LogManager.getLogger(FileBasedExecutionProverClientV2::class.java) + log = LogManager.getLogger(FileBasedExecutionProverClientV2::class.java), ), ExecutionProverClientV2 { override fun parseResponse( responseFilePath: Path, - proofIndex: ProofIndex + proofIndex: ProofIndex, ): SafeFuture { return SafeFuture.completedFuture( BatchExecutionProofResponse( startBlockNumber = proofIndex.startBlockNumber, - endBlockNumber = proofIndex.endBlockNumber - ) + endBlockNumber = proofIndex.endBlockNumber, + ), ) } } diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedProofAggregationClientV2.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedProofAggregationClientV2.kt index daf8d714..db288136 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedProofAggregationClientV2.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/FileBasedProofAggregationClientV2.kt @@ -21,13 +21,13 @@ data class AggregationProofRequestDto( val compressionProofs: List, val parentAggregationLastBlockTimestamp: Long, val parentAggregationLastL1RollingHashMessageNumber: Long, - val parentAggregationLastL1RollingHash: String + val parentAggregationLastL1RollingHash: String, ) { companion object { fun fromDomainObject( proofsToAggregate: ProofsToAggregate, executionProofResponseFileNameProvider: ProverFileNameProvider, - compressionProofResponseFileNameProvider: ProverFileNameProvider + compressionProofResponseFileNameProvider: ProverFileNameProvider, ): AggregationProofRequestDto { val executionProofsResponseFiles = proofsToAggregate.executionProofs .toIntervalList() @@ -35,8 +35,8 @@ data class AggregationProofRequestDto( executionProofResponseFileNameProvider.getFileName( ProofIndex( startBlockNumber = blockInterval.startBlockNumber, - endBlockNumber = blockInterval.endBlockNumber - ) + endBlockNumber = blockInterval.endBlockNumber, + ), ) } @@ -46,8 +46,8 @@ data class AggregationProofRequestDto( ProofIndex( startBlockNumber = it.startBlockNumber, endBlockNumber = it.endBlockNumber, - hash = it.hash - ) + hash = it.hash, + ), ) } @@ -57,7 +57,7 @@ data class AggregationProofRequestDto( parentAggregationLastBlockTimestamp = proofsToAggregate.parentAggregationLastBlockTimestamp.epochSeconds, parentAggregationLastL1RollingHashMessageNumber = proofsToAggregate.parentAggregationLastL1RollingHashMessageNumber.toLong(), - parentAggregationLastL1RollingHash = proofsToAggregate.parentAggregationLastL1RollingHash.encodeHex() + parentAggregationLastL1RollingHash = proofsToAggregate.parentAggregationLastL1RollingHash.encodeHex(), ) } } @@ -65,15 +65,15 @@ data class AggregationProofRequestDto( internal class AggregationRequestDtoMapper( private val executionProofResponseFileNameProvider: ProverFileNameProvider, - private val compressionProofResponseFileNameProvider: ProverFileNameProvider + private val compressionProofResponseFileNameProvider: ProverFileNameProvider, ) : (ProofsToAggregate) -> SafeFuture { override fun invoke(proofsToAggregate: ProofsToAggregate): SafeFuture { return SafeFuture.completedFuture( AggregationProofRequestDto.fromDomainObject( proofsToAggregate, executionProofResponseFileNameProvider, - compressionProofResponseFileNameProvider - ) + compressionProofResponseFileNameProvider, + ), ) } } @@ -95,13 +95,13 @@ class FileBasedProofAggregationClientV2( hashFunction: HashFunction = Sha256HashFunction(), executionProofResponseFileNameProvider: ProverFileNameProvider = ExecutionProofResponseFileNameProvider, compressionProofResponseFileNameProvider: ProverFileNameProvider = CompressionProofResponseFileNameProvider, - jsonObjectMapper: ObjectMapper = JsonSerialization.proofResponseMapperV1 + jsonObjectMapper: ObjectMapper = JsonSerialization.proofResponseMapperV1, ) : GenericFileBasedProverClient< ProofsToAggregate, ProofToFinalize, AggregationProofRequestDto, - ProofToFinalizeJsonResponse + ProofToFinalizeJsonResponse, >( config = config, vertx = vertx, @@ -109,18 +109,18 @@ class FileBasedProofAggregationClientV2( fileReader = FileReader( vertx, jsonObjectMapper, - ProofToFinalizeJsonResponse::class.java + ProofToFinalizeJsonResponse::class.java, ), requestFileNameProvider = AggregationProofFileNameProvider, responseFileNameProvider = AggregationProofFileNameProvider, proofIndexProvider = createProofIndexProviderFn(hashFunction), requestMapper = AggregationRequestDtoMapper( executionProofResponseFileNameProvider = executionProofResponseFileNameProvider, - compressionProofResponseFileNameProvider = compressionProofResponseFileNameProvider + compressionProofResponseFileNameProvider = compressionProofResponseFileNameProvider, ), responseMapper = ProofToFinalizeJsonResponse::toDomainObject, proofTypeLabel = "aggregation", - log = LogManager.getLogger(this::class.java) + log = LogManager.getLogger(this::class.java), ), ProofAggregationProverClientV2 { @@ -128,20 +128,20 @@ class FileBasedProofAggregationClientV2( fun createProofIndexProviderFn( hashFunction: HashFunction, executionProofResponseFileNameProvider: ProverFileNameProvider = ExecutionProofResponseFileNameProvider, - compressionProofResponseFileNameProvider: ProverFileNameProvider = CompressionProofResponseFileNameProvider + compressionProofResponseFileNameProvider: ProverFileNameProvider = CompressionProofResponseFileNameProvider, ): (ProofsToAggregate) -> ProofIndex { return { request: ProofsToAggregate -> val requestDto = AggregationProofRequestDto.fromDomainObject( proofsToAggregate = request, executionProofResponseFileNameProvider = executionProofResponseFileNameProvider, - compressionProofResponseFileNameProvider = compressionProofResponseFileNameProvider + compressionProofResponseFileNameProvider = compressionProofResponseFileNameProvider, ) val hash = hashRequest(hashFunction, requestDto) ProofIndex( startBlockNumber = request.startBlockNumber, endBlockNumber = request.endBlockNumber, - hash = hash + hash = hash, ) } } diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClient.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClient.kt index 2c3c615b..364a7d7c 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClient.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClient.kt @@ -28,13 +28,13 @@ open class GenericFileBasedProverClient ProofIndex = ::blockIntervalProofIndex, private val requestMapper: (Request) -> SafeFuture, private val responseMapper: (ResponseDto) -> Response, private val proofTypeLabel: String, - private val log: Logger = LogManager.getLogger(GenericFileBasedProverClient::class.java) + private val log: Logger = LogManager.getLogger(GenericFileBasedProverClient::class.java), ) : Supplier where Request : BlockInterval, Response : Any, @@ -62,7 +62,7 @@ open class GenericFileBasedProverClient { return fileMonitor.monitor(responseFilePath).thenCompose { if (it is Err) { @@ -130,17 +130,17 @@ open class GenericFileBasedProverClient { return fileMonitor.findFile( directory = config.requestsDirectory, - pattern = inProgressFilePattern(requestFileName, config.inprogressProvingSuffixPattern) + pattern = inProgressFilePattern(requestFileName, config.inprogressProvingSuffixPattern), ) } protected open fun parseResponse( responseFilePath: Path, - proofIndex: ProofIndex + proofIndex: ProofIndex, ): SafeFuture { return fileReader.read(responseFilePath) .thenCompose { result -> @@ -152,7 +152,7 @@ open class GenericFileBasedProverClient blockIntervalProofIndex(request: R): ProofIndex { return ProofIndex( startBlockNumber = request.startBlockNumber, - endBlockNumber = request.endBlockNumber + endBlockNumber = request.endBlockNumber, ) } fun createDirectoryIfNotExists( directory: Path, - log: Logger = LogManager.getLogger(GenericFileBasedProverClient::class.java) + log: Logger = LogManager.getLogger(GenericFileBasedProverClient::class.java), ) { try { if (directory.notExists()) { diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactory.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactory.kt index 4fa766ad..747916da 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactory.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactory.kt @@ -13,7 +13,7 @@ import net.consensys.zkevm.coordinator.clients.ProverClient class ProverClientFactory( private val vertx: Vertx, private val config: ProversConfig, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ) { private val executionWaitingResponsesMetric = GaugeAggregator() private val blobWaitingResponsesMetric = GaugeAggregator() @@ -24,37 +24,37 @@ class ProverClientFactory( category = LineaMetricsCategory.BATCH, name = "prover.waiting", description = "Number of execution proof waiting responses", - measurementSupplier = executionWaitingResponsesMetric + measurementSupplier = executionWaitingResponsesMetric, ) metricsFacade.createGauge( category = LineaMetricsCategory.BLOB, name = "prover.waiting", description = "Number of blob compression proof waiting responses", - measurementSupplier = blobWaitingResponsesMetric + measurementSupplier = blobWaitingResponsesMetric, ) metricsFacade.createGauge( category = LineaMetricsCategory.AGGREGATION, name = "prover.waiting", description = "Number of aggregation proof waiting responses", - measurementSupplier = aggregationWaitingResponsesMetric + measurementSupplier = aggregationWaitingResponsesMetric, ) } fun executionProverClient( tracesVersion: String, - stateManagerVersion: String + stateManagerVersion: String, ): ExecutionProverClientV2 { return createClient( proverAConfig = config.proverA.execution, proverBConfig = config.proverB?.execution, - switchBlockNumberInclusive = config.switchBlockNumberInclusive + switchBlockNumberInclusive = config.switchBlockNumberInclusive, ) { proverConfig -> FileBasedExecutionProverClientV2( config = proverConfig, vertx = vertx, tracesVersion = tracesVersion, - stateManagerVersion = stateManagerVersion + stateManagerVersion = stateManagerVersion, ).also { executionWaitingResponsesMetric.addReporter(it) } } } @@ -63,11 +63,11 @@ class ProverClientFactory( return createClient( proverAConfig = config.proverA.blobCompression, proverBConfig = config.proverB?.blobCompression, - switchBlockNumberInclusive = config.switchBlockNumberInclusive + switchBlockNumberInclusive = config.switchBlockNumberInclusive, ) { proverConfig -> FileBasedBlobCompressionProverClientV2( config = proverConfig, - vertx = vertx + vertx = vertx, ).also { blobWaitingResponsesMetric.addReporter(it) } } } @@ -76,11 +76,11 @@ class ProverClientFactory( return createClient( proverAConfig = config.proverA.proofAggregation, proverBConfig = config.proverB?.proofAggregation, - switchBlockNumberInclusive = config.switchBlockNumberInclusive + switchBlockNumberInclusive = config.switchBlockNumberInclusive, ) { proverConfig -> FileBasedProofAggregationClientV2( config = proverConfig, - vertx = vertx + vertx = vertx, ).also { aggregationWaitingResponsesMetric.addReporter(it) } } } @@ -89,7 +89,7 @@ class ProverClientFactory( proverAConfig: FileBasedProverConfig, proverBConfig: FileBasedProverConfig?, switchBlockNumberInclusive: ULong?, - clientBuilder: (FileBasedProverConfig) -> ProverClient + clientBuilder: (FileBasedProverConfig) -> ProverClient, ): ProverClient where ProofRequest : BlockInterval { return if (switchBlockNumberInclusive != null) { @@ -97,7 +97,7 @@ class ProverClientFactory( ABProverClientRouter( proverA = clientBuilder(proverAConfig), proverB = clientBuilder(proverBConfig!!), - switchToProverBPredicate = switchPredicate::invoke + switchToProverBPredicate = switchPredicate::invoke, ) } else { clientBuilder(proverAConfig) diff --git a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvider.kt b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvider.kt index 55c95db1..fe349043 100644 --- a/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvider.kt +++ b/coordinator/clients/prover-client/file-based-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvider.kt @@ -9,7 +9,7 @@ open class ProverFileNameProvider(protected val fileNameSuffix: String) { startBlockNumber: ULong, endBlockNumber: ULong, fileNameSuffix: String, - hash: ByteArray? + hash: ByteArray?, ) = if (hash == null || hash.isEmpty()) { "$startBlockNumber-$endBlockNumber-$fileNameSuffix" @@ -22,7 +22,7 @@ open class ProverFileNameProvider(protected val fileNameSuffix: String) { startBlockNumber = proofIndex.startBlockNumber, endBlockNumber = proofIndex.endBlockNumber, hash = proofIndex.hash, - fileNameSuffix = fileNameSuffix + fileNameSuffix = fileNameSuffix, ) } } @@ -35,7 +35,7 @@ object FileNameSuffixes { class ExecutionProofRequestFileNameProvider( private val tracesVersion: String, - private val stateManagerVersion: String + private val stateManagerVersion: String, ) : ProverFileNameProvider(FileNameSuffixes.EXECUTION_PROOF_SUFFIX) { override fun getFileName(proofIndex: ProofIndex): String { return "${proofIndex.startBlockNumber}-${proofIndex.endBlockNumber}" + diff --git a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ExecutionProofRequestDtoMapperTest.kt b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ExecutionProofRequestDtoMapperTest.kt index 3f0a9a20..24abf6df 100644 --- a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ExecutionProofRequestDtoMapperTest.kt +++ b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ExecutionProofRequestDtoMapperTest.kt @@ -51,8 +51,8 @@ class ExecutionProofRequestDtoMapperTest { data = "0xdeadbeef".decodeHex(), topics = listOf( "0xa000000000000000000000000000000000000000000000000000000000000001".decodeHex(), - "0xa000000000000000000000000000000000000000000000000000000000000002".decodeHex() - ) + "0xa000000000000000000000000000000000000000000000000000000000000002".decodeHex(), + ), ) assertThat(BridgeLogsDto.fromDomainObject(logEvent)) .isEqualTo( @@ -67,9 +67,9 @@ class ExecutionProofRequestDtoMapperTest { data = "0xdeadbeef", topics = listOf( "0xa000000000000000000000000000000000000000000000000000000000000001", - "0xa000000000000000000000000000000000000000000000000000000000000002" - ) - ) + "0xa000000000000000000000000000000000000000000000000000000000000002", + ), + ), ) } @@ -82,19 +82,19 @@ class ExecutionProofRequestDtoMapperTest { zkStateMerkleProof = ArrayNode(null), zkParentStateRootHash = ByteArrayExt.random32(), zkEndStateRootHash = ByteArrayExt.random32(), - zkStateManagerVersion = "2.0.0" + zkStateManagerVersion = "2.0.0", ) val block1Logs = listOf( createMessageSentEthLogV1(blockNumber = 747066UL), - createL2RollingHashUpdatedEthLogV1(blockNumber = 747066UL) + createL2RollingHashUpdatedEthLogV1(blockNumber = 747066UL), ) val block3Logs = listOf( createMessageSentEthLogV1(blockNumber = 747068UL), - createL2RollingHashUpdatedEthLogV1(blockNumber = 747068UL) + createL2RollingHashUpdatedEthLogV1(blockNumber = 747068UL), ) val generateTracesResponse = GenerateTracesResponse( tracesFileName = "747066-747068-conflated-traces.json", - tracesEngineVersion = "1.0.0" + tracesEngineVersion = "1.0.0", ) val stateRoot = Random.nextBytes(32) val request = BatchExecutionProofRequestV1( @@ -102,7 +102,7 @@ class ExecutionProofRequestDtoMapperTest { bridgeLogs = block1Logs + block3Logs, tracesResponse = generateTracesResponse, type2StateData = type2StateResponse, - keccakParentStateRootHash = stateRoot + keccakParentStateRootHash = stateRoot, ) val requestDto = requestDtoMapper.invoke(request).get() @@ -117,20 +117,20 @@ class ExecutionProofRequestDtoMapperTest { assertThat(requestDto.blocksData[0]).isEqualTo( RlpBridgeLogsDto( rlp = "747066".toByteArray().encodeHex(), - bridgeLogs = block1Logs.map(BridgeLogsDto::fromDomainObject) - ) + bridgeLogs = block1Logs.map(BridgeLogsDto::fromDomainObject), + ), ) assertThat(requestDto.blocksData[1]).isEqualTo( RlpBridgeLogsDto( rlp = "747067".toByteArray().encodeHex(), - bridgeLogs = emptyList() - ) + bridgeLogs = emptyList(), + ), ) assertThat(requestDto.blocksData[2]).isEqualTo( RlpBridgeLogsDto( rlp = "747068".toByteArray().encodeHex(), - bridgeLogs = block3Logs.map(BridgeLogsDto::fromDomainObject) - ) + bridgeLogs = block3Logs.map(BridgeLogsDto::fromDomainObject), + ), ) } } diff --git a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClientTest.kt b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClientTest.kt index c7a73b7a..06beae7c 100644 --- a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClientTest.kt +++ b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/GenericFileBasedProverClientTest.kt @@ -49,17 +49,19 @@ class GenericFileBasedProverClientTest { ProofRequest, ProofResponse, ProofRequestDto, - ProofResponseDto + ProofResponseDto, > private lateinit var proverConfig: FileBasedProverConfig private fun createProverClient( config: FileBasedProverConfig, - vertx: Vertx - ): GenericFileBasedProverClient { + ProofResponseDto, + > { return GenericFileBasedProverClient( config = config, vertx = vertx, @@ -67,20 +69,20 @@ class GenericFileBasedProverClientTest { fileReader = FileReader( vertx, JsonSerialization.proofResponseMapperV1, - ProofResponseDto::class.java + ProofResponseDto::class.java, ), requestFileNameProvider = requestFileNameProvider, responseFileNameProvider = responseFileNameProvider, requestMapper = { SafeFuture.completedFuture(ProofRequestDto.fromDomain(it)) }, proofTypeLabel = "batch", - responseMapper = ProofResponseDto::toDomain + responseMapper = ProofResponseDto::toDomain, ) } @BeforeEach fun beforeEach( vertx: Vertx, - @TempDir tempDir: Path + @TempDir tempDir: Path, ) { proverConfig = FileBasedProverConfig( requestsDirectory = tempDir.resolve("requests"), @@ -88,7 +90,7 @@ class GenericFileBasedProverClientTest { inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", inprogressRequestWritingSuffix = "coordinator_writing_inprogress", pollingInterval = 100.milliseconds, - pollingTimeout = 2.seconds + pollingTimeout = 2.seconds, ) proverClient = createProverClient(proverConfig, vertx) @@ -114,12 +116,12 @@ class GenericFileBasedProverClientTest { @Test fun `when it cannot create request and response directories shall fail`( - vertx: Vertx + vertx: Vertx, ) { val dirWithoutWritePermissions = Path.of("/invalid/path") val invalidConfig = proverConfig.copy( requestsDirectory = dirWithoutWritePermissions.resolve("requests"), - responsesDirectory = dirWithoutWritePermissions.resolve("responses") + responsesDirectory = dirWithoutWritePermissions.resolve("responses"), ) assertThrows { createProverClient(invalidConfig, vertx) @@ -197,7 +199,7 @@ class GenericFileBasedProverClientTest { // 8930088-8930101-etv0.2.0-stv2.2.0-getZkProof.json.inprogress.prover-aggregation-97695c877-vgsfg val requestProvingInprogressFilePath = proverConfig.requestsDirectory.resolve( requestFileNameProvider.getFileName(proofIndex) + - "some-midle-str.inprogress.prover-aggregation-97695c877-vgsfg" + "some-midle-str.inprogress.prover-aggregation-97695c877-vgsfg", ) // write request with a different block number content to check tha it was not overwritten saveToFile(requestProvingInprogressFilePath, ProofRequestDto(blockNumberStart = 4u, blockNumberEnd = 44444u)) diff --git a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactoryTest.kt b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactoryTest.kt index dde9c0ae..e9fbc22d 100644 --- a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactoryTest.kt +++ b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverClientFactoryTest.kt @@ -27,7 +27,7 @@ import kotlin.time.toJavaDuration class ProverClientFactoryTest { private fun buildProversConfig( tmpDir: Path, - switchBlockNumber: Int? = null + switchBlockNumber: Int? = null, ): ProversConfig { fun buildProverConfig(proverDir: Path): ProverConfig { return ProverConfig( @@ -37,7 +37,7 @@ class ProverClientFactoryTest { pollingInterval = 100.milliseconds, pollingTimeout = 500.milliseconds, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", ), blobCompression = FileBasedProverConfig( requestsDirectory = proverDir.resolve("compression/requests"), @@ -45,7 +45,7 @@ class ProverClientFactoryTest { pollingInterval = 100.milliseconds, pollingTimeout = 500.milliseconds, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", ), proofAggregation = FileBasedProverConfig( requestsDirectory = proverDir.resolve("aggregation/requests"), @@ -53,8 +53,8 @@ class ProverClientFactoryTest { pollingInterval = 100.milliseconds, pollingTimeout = 500.milliseconds, inprogressProvingSuffixPattern = ".*\\.inprogress\\.prover.*", - inprogressRequestWritingSuffix = ".inprogress_coordinator_writing" - ) + inprogressRequestWritingSuffix = ".inprogress_coordinator_writing", + ), ) } @@ -63,7 +63,7 @@ class ProverClientFactoryTest { switchBlockNumberInclusive = switchBlockNumber?.toULong(), proverB = switchBlockNumber?.let { buildProverConfig(tmpDir.resolve("prover/v3")) - } + }, ) } @@ -78,27 +78,27 @@ class ProverClientFactoryTest { executionProofs = BlockIntervals(startingBlockNumber = 1uL, listOf(9uL)), parentAggregationLastBlockTimestamp = Clock.System.now(), parentAggregationLastL1RollingHashMessageNumber = 0uL, - parentAggregationLastL1RollingHash = ByteArrayExt.random32() + parentAggregationLastL1RollingHash = ByteArrayExt.random32(), ) private val request2 = ProofsToAggregate( compressionProofIndexes = listOf(ProofIndex(startBlockNumber = 10uL, endBlockNumber = 19uL)), executionProofs = BlockIntervals(startingBlockNumber = 10uL, listOf(19uL)), parentAggregationLastBlockTimestamp = Clock.System.now(), parentAggregationLastL1RollingHashMessageNumber = 9uL, - parentAggregationLastL1RollingHash = ByteArrayExt.random32() + parentAggregationLastL1RollingHash = ByteArrayExt.random32(), ) private val request3 = ProofsToAggregate( compressionProofIndexes = listOf(ProofIndex(startBlockNumber = 300uL, endBlockNumber = 319uL)), executionProofs = BlockIntervals(startingBlockNumber = 300uL, listOf(319uL)), parentAggregationLastBlockTimestamp = Clock.System.now(), parentAggregationLastL1RollingHashMessageNumber = 299uL, - parentAggregationLastL1RollingHash = ByteArrayExt.random32() + parentAggregationLastL1RollingHash = ByteArrayExt.random32(), ) @BeforeEach fun beforeEach( vertx: Vertx, - @TempDir tmpDir: Path + @TempDir tmpDir: Path, ) { this.vertx = vertx this.testTmpDir = tmpDir diff --git a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvidersTest.kt b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvidersTest.kt index c8fdbc6b..fc71d562 100644 --- a/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvidersTest.kt +++ b/coordinator/clients/prover-client/file-based-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/ProverFileNameProvidersTest.kt @@ -11,16 +11,16 @@ class ProverFileNameProvidersTest { fun test_getExecutionProof_requestFileName() { val executionProofRequestFileNameProvider = ExecutionProofRequestFileNameProvider( tracesVersion = "0.1", - stateManagerVersion = "0.2" + stateManagerVersion = "0.2", ) Assertions.assertEquals( "11-17-etv0.1-stv0.2-getZkProof.json", executionProofRequestFileNameProvider.getFileName( ProofIndex( startBlockNumber = 11u, - endBlockNumber = 17u - ) - ) + endBlockNumber = 17u, + ), + ), ) } @@ -31,9 +31,9 @@ class ProverFileNameProvidersTest { ExecutionProofResponseFileNameProvider.getFileName( ProofIndex( startBlockNumber = 11u, - endBlockNumber = 17u - ) - ) + endBlockNumber = 17u, + ), + ), ) } @@ -47,9 +47,9 @@ class ProverFileNameProvidersTest { ProofIndex( startBlockNumber = 11u, endBlockNumber = 17u, - hash = hash - ) - ) + hash = hash, + ), + ), ) } @@ -60,13 +60,13 @@ class ProverFileNameProvidersTest { ProofIndex( startBlockNumber = 1uL, endBlockNumber = 11uL, - hash = requestHash - ) + hash = requestHash, + ), ) Assertions.assertEquals( "1-11-bcv0.0-ccv0.0-0abcd123-getZkBlobCompressionProof.json", - requestFileName + requestFileName, ) } @@ -79,9 +79,9 @@ class ProverFileNameProvidersTest { ProofIndex( startBlockNumber = 11u, endBlockNumber = 27u, - hash = hash - ) - ) + hash = hash, + ), + ), ) } } diff --git a/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobJsonFileRequestResponse.kt b/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobJsonFileRequestResponse.kt index a541675a..493e2911 100644 --- a/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobJsonFileRequestResponse.kt +++ b/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobJsonFileRequestResponse.kt @@ -66,17 +66,17 @@ data class BlobCompressionProofJsonRequest( val kzgProofContract: ByteArray, @JsonProperty("kzgProofSidecar") @JsonSerialize(using = ByteArraySerializer::class) - val kzgProofSidecar: ByteArray + val kzgProofSidecar: ByteArray, ) { companion object { fun fromDomainObject( - request: BlobCompressionProofRequest + request: BlobCompressionProofRequest, ): BlobCompressionProofJsonRequest { return BlobCompressionProofJsonRequest( compressedData = request.compressedData, conflationOrder = BlockIntervals( startingBlockNumber = request.conflations.first().startBlockNumber, - upperBoundaries = request.conflations.map { it.endBlockNumber } + upperBoundaries = request.conflations.map { it.endBlockNumber }, ), prevShnarf = request.prevShnarf, parentStateRootHash = request.parentStateRootHash, @@ -89,7 +89,7 @@ data class BlobCompressionProofJsonRequest( expectedShnarf = request.expectedShnarfResult.expectedShnarf, commitment = request.commitment, kzgProofContract = request.kzgProofContract, - kzgProofSidecar = request.kzgProofSideCar + kzgProofSidecar = request.kzgProofSideCar, ) } } @@ -152,7 +152,7 @@ data class BlobCompressionProofJsonResponse( @JsonProperty("kzgProofSidecar") @JsonDeserialize(using = ByteArrayDeserializer::class) @JsonSerialize(using = ByteArraySerializer::class) - val kzgProofSidecar: ByteArray = ByteArray(0) + val kzgProofSidecar: ByteArray = ByteArray(0), ) { fun toDomainObject(): BlobCompressionProof { @@ -173,7 +173,7 @@ data class BlobCompressionProofJsonResponse( verifierID = verifierID, commitment = commitment, kzgProofContract = kzgProofContract, - kzgProofSidecar = kzgProofSidecar + kzgProofSidecar = kzgProofSidecar, ) } @@ -235,7 +235,7 @@ data class BlobCompressionProofJsonResponse( fun fromJsonString(jsonString: String): BlobCompressionProofJsonResponse { return JsonSerialization.proofResponseMapperV1.readValue( jsonString, - BlobCompressionProofJsonResponse::class.java + BlobCompressionProofJsonResponse::class.java, ) } @@ -257,7 +257,7 @@ data class BlobCompressionProofJsonResponse( verifierID = compressionProof.verifierID, commitment = compressionProof.commitment, kzgProofContract = compressionProof.kzgProofContract, - kzgProofSidecar = compressionProof.kzgProofSidecar + kzgProofSidecar = compressionProof.kzgProofSidecar, ) } } diff --git a/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponse.kt b/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponse.kt index a3fd9340..9fad24d5 100644 --- a/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponse.kt +++ b/coordinator/clients/prover-client/serialization/src/main/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponse.kt @@ -36,7 +36,7 @@ data class ProofToFinalizeJsonResponse( val l2MerkleTreesDepth: Int, @JsonSerialize(using = ByteArraySerializer::class) @JsonDeserialize(using = ByteArrayDeserializer::class) - val l2MessagingBlocksOffsets: ByteArray + val l2MessagingBlocksOffsets: ByteArray, ) { fun toDomainObject(): ProofToFinalize { @@ -55,7 +55,7 @@ data class ProofToFinalizeJsonResponse( l1RollingHashMessageNumber = l1RollingHashMessageNumber, l2MerkleRoots = l2MerkleRoots, l2MerkleTreesDepth = l2MerkleTreesDepth, - l2MessagingBlocksOffsets = l2MessagingBlocksOffsets + l2MessagingBlocksOffsets = l2MessagingBlocksOffsets, ) } @@ -118,7 +118,7 @@ data class ProofToFinalizeJsonResponse( fun fromJsonString(jsonString: String): ProofToFinalizeJsonResponse { return JsonSerialization.proofResponseMapperV1.readValue( jsonString, - ProofToFinalizeJsonResponse::class.java + ProofToFinalizeJsonResponse::class.java, ) } @@ -138,7 +138,7 @@ data class ProofToFinalizeJsonResponse( l1RollingHashMessageNumber = proofToFinalize.l1RollingHashMessageNumber, l2MerkleRoots = proofToFinalize.l2MerkleRoots, l2MerkleTreesDepth = proofToFinalize.l2MerkleTreesDepth, - l2MessagingBlocksOffsets = proofToFinalize.l2MessagingBlocksOffsets + l2MessagingBlocksOffsets = proofToFinalize.l2MessagingBlocksOffsets, ) } } diff --git a/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobCompressionProofJsonResponseTest.kt b/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobCompressionProofJsonResponseTest.kt index 50565d05..197b3812 100644 --- a/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobCompressionProofJsonResponseTest.kt +++ b/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/BlobCompressionProofJsonResponseTest.kt @@ -35,7 +35,7 @@ class BlobCompressionProofJsonResponseTest { eip4844Enabled = false, commitment = ByteArray(0), kzgProofSidecar = ByteArray(0), - kzgProofContract = ByteArray(0) + kzgProofContract = ByteArray(0), ) val proofResponseJsonString = proofResponse.toJsonString() diff --git a/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponseTest.kt b/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponseTest.kt index cacdc760..4f1e461f 100644 --- a/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponseTest.kt +++ b/coordinator/clients/prover-client/serialization/src/test/kotlin/net/consensys/zkevm/coordinator/clients/prover/serialization/ProofToFinalizeJsonResponseTest.kt @@ -26,7 +26,7 @@ class ProofToFinalizeJsonResponseTest { @ParameterizedTest(name = "when_deserialize_{0}_properties_match_proof_to_finalize_json_response") @MethodSource("aggregationProofResponseFiles") fun when_deserialize_test_data_json_properties_match_proof_to_finalize_json_response( - filePath: Path + filePath: Path, ) { val proofToFinalizeJsonResponseProperties = ProofToFinalizeJsonResponse::class .declaredMemberProperties @@ -37,7 +37,7 @@ class ProofToFinalizeJsonResponseTest { val propertiesInTestDataFile = getKeysInJsonUsingJsonParser( filePath.toFile(), - JsonSerialization.proofResponseMapperV1 + JsonSerialization.proofResponseMapperV1, ) assertThat(propertiesInTestDataFile).isEqualTo(proofToFinalizeJsonResponseProperties) } diff --git a/coordinator/clients/shomei-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClient.kt b/coordinator/clients/shomei-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClient.kt index 6d5035bc..cd177490 100644 --- a/coordinator/clients/shomei-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClient.kt +++ b/coordinator/clients/shomei-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClient.kt @@ -21,23 +21,23 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture import java.util.concurrent.atomic.AtomicInteger class ShomeiClient( - private val rpcClient: JsonRpcClient + private val rpcClient: JsonRpcClient, ) : RollupForkChoiceUpdatedClient { constructor( vertx: Vertx, rpcClient: JsonRpcClient, retryConfig: RequestRetryConfig, - log: Logger = LogManager.getLogger(ShomeiClient::class.java) + log: Logger = LogManager.getLogger(ShomeiClient::class.java), ) : this( JsonRpcRequestRetryer( vertx, rpcClient, config = JsonRpcRequestRetryer.Config( methodsToRetry = retryableMethods, - requestRetry = retryConfig + requestRetry = retryConfig, ), - log = log - ) + log = log, + ), ) private var id = AtomicInteger(0) @@ -52,9 +52,9 @@ class ShomeiClient( listOf( mapOf( "finalizedBlockNumber" to finalizedBlockNumberAndHash.number.toString(), - "finalizedBlockHash" to finalizedBlockNumberAndHash.hash.encodeHex() - ) - ) + "finalizedBlockHash" to finalizedBlockNumberAndHash.hash.encodeHex(), + ), + ), ) return rpcClient.makeRequest(jsonRequest).toSafeFuture() .thenApply { responseResult -> @@ -64,8 +64,7 @@ class ShomeiClient( companion object { internal val retryableMethods = setOf("rollup_forkChoiceUpdated") - fun mapErrorResponse(jsonRpcErrorResponse: JsonRpcErrorResponse): - ErrorResponse { + fun mapErrorResponse(jsonRpcErrorResponse: JsonRpcErrorResponse): ErrorResponse { val errorType: RollupForkChoiceUpdatedError = runCatching { RollupForkChoiceUpdatedError.valueOf(jsonRpcErrorResponse.error.message.substringBefore(':')) }.getOrElse { RollupForkChoiceUpdatedError.UNKNOWN } @@ -73,8 +72,7 @@ class ShomeiClient( return ErrorResponse(errorType, jsonRpcErrorResponse.error.message) } - fun mapRollupForkChoiceUpdatedResponse(jsonRpcResponse: JsonRpcSuccessResponse): - RollupForkChoiceUpdatedResponse { + fun mapRollupForkChoiceUpdatedResponse(jsonRpcResponse: JsonRpcSuccessResponse): RollupForkChoiceUpdatedResponse { return RollupForkChoiceUpdatedResponse(result = jsonRpcResponse.result.toString()) } } diff --git a/coordinator/clients/shomei-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClientTest.kt b/coordinator/clients/shomei-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClientTest.kt index 9dea1b2f..561a760b 100644 --- a/coordinator/clients/shomei-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClientTest.kt +++ b/coordinator/clients/shomei-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/ShomeiClientTest.kt @@ -59,14 +59,14 @@ class ShomeiClientTest { "id", "1", "result", - "success" + "success", ) wiremock.stubFor( WireMock.post("/") .withHeader("Content-Type", WireMock.containing("application/json")) .willReturn( - WireMock.ok().withHeader("Content-type", "application/json").withBody(successResponse.toString()) - ) + WireMock.ok().withHeader("Content-type", "application/json").withBody(successResponse.toString()), + ), ) val blockNumberAndHash = BlockNumberAndHash(1U, ByteArrayExt.random32()) val resultFuture = shomeiClient.rollupForkChoiceUpdated(blockNumberAndHash) @@ -86,14 +86,14 @@ class ShomeiClientTest { listOf( mapOf( "finalizedBlockNumber" to blockNumberAndHash.number.toString(), - "finalizedBlockHash" to blockNumberAndHash.hash.encodeHex() - ) - ) + "finalizedBlockHash" to blockNumberAndHash.hash.encodeHex(), + ), + ), ) wiremock.verify( WireMock.postRequestedFor(WireMock.urlEqualTo("/")) .withHeader("Content-Type", WireMock.equalTo("application/json")) - .withRequestBody(WireMock.equalToJson(expectedJsonRequest.toString(), false, true)) + .withRequestBody(WireMock.equalToJson(expectedJsonRequest.toString(), false, true)), ) } @@ -106,7 +106,7 @@ class ShomeiClientTest { "id", "1", "error", - mapOf("code" to "1", "message" to "Internal Error") + mapOf("code" to "1", "message" to "Internal Error"), ) wiremock.stubFor( @@ -115,8 +115,8 @@ class ShomeiClientTest { .willReturn( WireMock.aResponse() .withStatus(200) - .withBody(jsonRpcErrorResponse.toString()) - ) + .withBody(jsonRpcErrorResponse.toString()), + ), ) val blockNumberAndHash = BlockNumberAndHash(1U, ByteArrayExt.random32()) val resultFuture = shomeiClient.rollupForkChoiceUpdated(blockNumberAndHash) @@ -136,14 +136,14 @@ class ShomeiClientTest { listOf( mapOf( "finalizedBlockNumber" to blockNumberAndHash.number.toString(), - "finalizedBlockHash" to blockNumberAndHash.hash.encodeHex() - ) - ) + "finalizedBlockHash" to blockNumberAndHash.hash.encodeHex(), + ), + ), ) wiremock.verify( WireMock.postRequestedFor(WireMock.urlEqualTo("/")) .withHeader("Content-Type", WireMock.equalTo("application/json")) - .withRequestBody(WireMock.equalToJson(expectedJsonRequest.toString(), false, true)) + .withRequestBody(WireMock.equalToJson(expectedJsonRequest.toString(), false, true)), ) } } diff --git a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/GenesisStateProvider.kt b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/GenesisStateProvider.kt index c53820fc..c2d2695e 100644 --- a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/GenesisStateProvider.kt +++ b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/GenesisStateProvider.kt @@ -5,7 +5,7 @@ import net.consensys.zkevm.coordinator.clients.smartcontract.LineaGenesisStatePr data class GenesisStateProvider( override val stateRootHash: ByteArray, - override val shnarf: ByteArray + override val shnarf: ByteArray, ) : LineaGenesisStateProvider { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/LineaRollupEnhancedWrapper.kt b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/LineaRollupEnhancedWrapper.kt index 98c62cf4..9b07c822 100644 --- a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/LineaRollupEnhancedWrapper.kt +++ b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/LineaRollupEnhancedWrapper.kt @@ -15,25 +15,24 @@ internal class LineaRollupEnhancedWrapper( web3j: Web3j, transactionManager: AsyncFriendlyTransactionManager, contractGasProvider: ContractGasProvider, - private val web3jContractHelper: Web3JContractAsyncHelper + private val web3jContractHelper: Web3JContractAsyncHelper, ) : LineaRollupV6( contractAddress, web3j, transactionManager, - contractGasProvider + contractGasProvider, ) { @Synchronized - override fun executeRemoteCallTransaction( function: Function, - weiValue: BigInteger + weiValue: BigInteger, ): RemoteFunctionCall = web3jContractHelper.executeRemoteCallTransaction(function, weiValue) @Synchronized override fun executeRemoteCallTransaction( - function: Function + function: Function, ): RemoteFunctionCall = web3jContractHelper.executeRemoteCallTransaction( function, - BigInteger.ZERO + BigInteger.ZERO, ) } diff --git a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JFunctionBuildersV6.kt b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JFunctionBuildersV6.kt index 4e57c82b..0b774987 100644 --- a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JFunctionBuildersV6.kt +++ b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JFunctionBuildersV6.kt @@ -17,7 +17,7 @@ import java.util.Arrays internal fun buildSubmitBlobsFunction( version: LineaContractVersion, - blobs: List + blobs: List, ): Function { return when (version) { LineaContractVersion.V6 -> buildSubmitBlobsFunctionV6(blobs) @@ -25,18 +25,23 @@ internal fun buildSubmitBlobsFunction( } internal fun buildSubmitBlobsFunctionV6( - blobs: List + blobs: List, ): Function { val blobsSubmissionData = blobs.map { blob -> val blobCompressionProof = blob.blobCompressionProof!! // BlobSubmission(BigInteger dataEvaluationClaim, byte[] kzgCommitment, byte[] kzgProof, // byte[] finalStateRootHash, byte[] snarkHash) LineaRollupV6.BlobSubmission( - /*dataEvaluationClaim*/ BigInteger(blobCompressionProof.expectedY), - /*kzgCommitment*/ blobCompressionProof.commitment, - /*kzgProof*/ blobCompressionProof.kzgProofContract, - /*finalStateRootHash*/ blobCompressionProof.finalStateRootHash, - /*snarkHash*/ blobCompressionProof.snarkHash + /*dataEvaluationClaim*/ + BigInteger(blobCompressionProof.expectedY), + /*kzgCommitment*/ + blobCompressionProof.commitment, + /*kzgProof*/ + blobCompressionProof.kzgProofContract, + /*finalStateRootHash*/ + blobCompressionProof.finalStateRootHash, + /*snarkHash*/ + blobCompressionProof.snarkHash, ) } @@ -52,9 +57,9 @@ internal fun buildSubmitBlobsFunctionV6( Arrays.asList>( DynamicArray(LineaRollupV6.BlobSubmission::class.java, blobsSubmissionData), Bytes32(blobs.first().blobCompressionProof!!.prevShnarf), - Bytes32(blobs.last().blobCompressionProof!!.expectedShnarf) + Bytes32(blobs.last().blobCompressionProof!!.expectedShnarf), ), - emptyList>() + emptyList>(), ) } @@ -63,7 +68,7 @@ fun buildFinalizeBlocksFunction( aggregationProof: ProofToFinalize, aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): Function { when (version) { LineaContractVersion.V6 -> { @@ -71,7 +76,7 @@ fun buildFinalizeBlocksFunction( aggregationProof, aggregationLastBlob, parentL1RollingHash, - parentL1RollingHashMessageNumber + parentL1RollingHashMessageNumber, ) } } @@ -81,14 +86,19 @@ internal fun buildFinalizeBlockFunctionV6( aggregationProof: ProofToFinalize, aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): Function { val aggregationEndBlobInfo = LineaRollupV6.ShnarfData( - /*parentShnarf*/ aggregationLastBlob.blobCompressionProof!!.prevShnarf, - /*snarkHash*/ aggregationLastBlob.blobCompressionProof!!.snarkHash, - /*finalStateRootHash*/ aggregationLastBlob.blobCompressionProof!!.finalStateRootHash, - /*dataEvaluationPoint*/ aggregationLastBlob.blobCompressionProof!!.expectedX, - /*dataEvaluationClaim*/ aggregationLastBlob.blobCompressionProof!!.expectedY + /*parentShnarf*/ + aggregationLastBlob.blobCompressionProof!!.prevShnarf, + /*snarkHash*/ + aggregationLastBlob.blobCompressionProof!!.snarkHash, + /*finalStateRootHash*/ + aggregationLastBlob.blobCompressionProof!!.finalStateRootHash, + /*dataEvaluationPoint*/ + aggregationLastBlob.blobCompressionProof!!.expectedX, + /*dataEvaluationClaim*/ + aggregationLastBlob.blobCompressionProof!!.expectedY, ) // FinalizationDataV3( @@ -107,18 +117,30 @@ internal fun buildFinalizeBlockFunctionV6( // ) val finalizationData = LineaRollupV6.FinalizationDataV3( - /*parentStateRootHash*/ aggregationProof.parentStateRootHash, - /*endBlockNumber*/ aggregationProof.endBlockNumber.toBigInteger(), - /*shnarfData*/ aggregationEndBlobInfo, - /*lastFinalizedTimestamp*/ aggregationProof.parentAggregationLastBlockTimestamp.epochSeconds.toBigInteger(), - /*finalTimestamp*/ aggregationProof.finalTimestamp.epochSeconds.toBigInteger(), - /*lastFinalizedL1RollingHash*/ parentL1RollingHash, - /*l1RollingHash*/ aggregationProof.l1RollingHash, - /*lastFinalizedL1RollingHashMessageNumber*/ parentL1RollingHashMessageNumber.toBigInteger(), - /*l1RollingHashMessageNumber*/ aggregationProof.l1RollingHashMessageNumber.toBigInteger(), - /*l2MerkleTreesDepth*/ aggregationProof.l2MerkleTreesDepth.toBigInteger(), - /*l2MerkleRoots*/ aggregationProof.l2MerkleRoots, - /*l2MessagingBlocksOffsets*/ aggregationProof.l2MessagingBlocksOffsets + /*parentStateRootHash*/ + aggregationProof.parentStateRootHash, + /*endBlockNumber*/ + aggregationProof.endBlockNumber.toBigInteger(), + /*shnarfData*/ + aggregationEndBlobInfo, + /*lastFinalizedTimestamp*/ + aggregationProof.parentAggregationLastBlockTimestamp.epochSeconds.toBigInteger(), + /*finalTimestamp*/ + aggregationProof.finalTimestamp.epochSeconds.toBigInteger(), + /*lastFinalizedL1RollingHash*/ + parentL1RollingHash, + /*l1RollingHash*/ + aggregationProof.l1RollingHash, + /*lastFinalizedL1RollingHashMessageNumber*/ + parentL1RollingHashMessageNumber.toBigInteger(), + /*l1RollingHashMessageNumber*/ + aggregationProof.l1RollingHashMessageNumber.toBigInteger(), + /*l2MerkleTreesDepth*/ + aggregationProof.l2MerkleTreesDepth.toBigInteger(), + /*l2MerkleRoots*/ + aggregationProof.l2MerkleRoots, + /*l2MessagingBlocksOffsets*/ + aggregationProof.l2MessagingBlocksOffsets, ) /** @@ -133,9 +155,9 @@ internal fun buildFinalizeBlockFunctionV6( Arrays.asList>( DynamicBytes(aggregationProof.aggregatedProof), Uint256(aggregationProof.aggregatedVerifierIndex.toLong()), - finalizationData + finalizationData, ), - emptyList>() + emptyList>(), ) return function } diff --git a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JLineaRollupSmartContractClient.kt b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JLineaRollupSmartContractClient.kt index bfacafe2..59582a96 100644 --- a/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JLineaRollupSmartContractClient.kt +++ b/coordinator/clients/smart-contract-client/src/main/kotlin/net/consensys/linea/contract/l1/Web3JLineaRollupSmartContractClient.kt @@ -26,11 +26,11 @@ class Web3JLineaRollupSmartContractClient internal constructor( private val transactionManager: AsyncFriendlyTransactionManager, private val web3jContractHelper: Web3JContractAsyncHelper, private val web3jLineaClient: LineaRollupV6, - private val log: Logger = LogManager.getLogger(Web3JLineaRollupSmartContractClient::class.java) + private val log: Logger = LogManager.getLogger(Web3JLineaRollupSmartContractClient::class.java), ) : Web3JLineaRollupSmartContractClientReadOnly( contractAddress = contractAddress, web3j = web3j, - log = log + log = log, ), LineaRollupSmartContractClient { @@ -41,7 +41,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( transactionManager: AsyncFriendlyTransactionManager, contractGasProvider: ContractGasProvider, smartContractErrors: SmartContractErrors, - useEthEstimateGas: Boolean = false + useEthEstimateGas: Boolean = false, ): Web3JLineaRollupSmartContractClient { val web3JContractAsyncHelper = Web3JContractAsyncHelper( contractAddress = contractAddress, @@ -49,21 +49,21 @@ class Web3JLineaRollupSmartContractClient internal constructor( transactionManager = transactionManager, contractGasProvider = contractGasProvider, smartContractErrors = smartContractErrors, - useEthEstimateGas = useEthEstimateGas + useEthEstimateGas = useEthEstimateGas, ) val lineaRollupEnhancedWrapper = LineaRollupEnhancedWrapper( contractAddress = contractAddress, web3j = web3j, transactionManager = transactionManager, contractGasProvider = contractGasProvider, - web3jContractHelper = web3JContractAsyncHelper + web3jContractHelper = web3JContractAsyncHelper, ) return Web3JLineaRollupSmartContractClient( contractAddress = contractAddress, web3j = web3j, transactionManager = transactionManager, web3jContractHelper = web3JContractAsyncHelper, - web3jLineaClient = lineaRollupEnhancedWrapper + web3jLineaClient = lineaRollupEnhancedWrapper, ) } @@ -73,7 +73,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( credentials: Credentials, contractGasProvider: ContractGasProvider, smartContractErrors: SmartContractErrors, - useEthEstimateGas: Boolean + useEthEstimateGas: Boolean, ): Web3JLineaRollupSmartContractClient { return load( contractAddress, @@ -82,7 +82,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( AsyncFriendlyTransactionManager(web3j, credentials), contractGasProvider, smartContractErrors, - useEthEstimateGas + useEthEstimateGas, ) } } @@ -112,7 +112,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( */ override fun submitBlobs( blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { return getVersion() .thenCompose { version -> @@ -120,14 +120,14 @@ class Web3JLineaRollupSmartContractClient internal constructor( web3jContractHelper.sendBlobCarryingTransactionAndGetTxHash( function = function, blobs = blobs.map { it.blobCompressionProof!!.compressedData }, - gasPriceCaps = gasPriceCaps + gasPriceCaps = gasPriceCaps, ) } } override fun submitBlobsEthCall( blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { return getVersion() .thenCompose { version -> @@ -135,7 +135,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( web3jContractHelper.executeBlobEthCall( function = function, blobs = blobs.map { it.blobCompressionProof!!.compressedData }, - gasPriceCaps = gasPriceCaps + gasPriceCaps = gasPriceCaps, ) } } @@ -145,7 +145,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, parentL1RollingHashMessageNumber: Long, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { return getVersion() .thenCompose { version -> @@ -154,7 +154,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregation, aggregationLastBlob, parentL1RollingHash, - parentL1RollingHashMessageNumber + parentL1RollingHashMessageNumber, ) web3jContractHelper .sendTransactionAsync(function, BigInteger.ZERO, gasPriceCaps) @@ -166,7 +166,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregation: ProofToFinalize, aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): SafeFuture { return getVersion() .thenCompose { version -> @@ -175,7 +175,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregation, aggregationLastBlob, parentL1RollingHash, - parentL1RollingHashMessageNumber + parentL1RollingHashMessageNumber, ) web3jContractHelper.executeEthCall(function) } @@ -186,7 +186,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, parentL1RollingHashMessageNumber: Long, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { return getVersion() .thenCompose { version -> @@ -195,7 +195,7 @@ class Web3JLineaRollupSmartContractClient internal constructor( aggregation, aggregationLastBlob, parentL1RollingHash, - parentL1RollingHashMessageNumber + parentL1RollingHashMessageNumber, ) web3jContractHelper.sendTransactionAfterEthCallAsync(function, BigInteger.ZERO, gasPriceCaps) .thenApply { result -> result.transactionHash } diff --git a/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesClientResponsesParser.kt b/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesClientResponsesParser.kt index e8b83594..a5748feb 100644 --- a/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesClientResponsesParser.kt +++ b/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesClientResponsesParser.kt @@ -17,7 +17,7 @@ object TracesClientResponsesParser { private val log: Logger = LogManager.getLogger(this::class.java) internal fun mapErrorResponseV2( - jsonRpcErrorResponse: JsonRpcErrorResponse + jsonRpcErrorResponse: JsonRpcErrorResponse, ): ErrorResponse { val errorType: TracesServiceErrorType = runCatching { TracesServiceErrorType.valueOf(jsonRpcErrorResponse.error.data.toString().substringBefore(':')) @@ -27,13 +27,13 @@ object TracesClientResponsesParser { } internal fun parseTracesCounterResponseV2( - jsonRpcResponse: JsonRpcSuccessResponse + jsonRpcResponse: JsonRpcSuccessResponse, ): GetTracesCountersResponse { val result = jsonRpcResponse.result as JsonObject return GetTracesCountersResponse( result.getJsonObject("tracesCounters").let { parseTracesCountersV2(it) }, - result.getString("tracesEngineVersion") + result.getString("tracesEngineVersion"), ) } @@ -62,7 +62,7 @@ object TracesClientResponsesParser { log.error( "Failed to parse Evm module ${traceModule.name}='$counterValue' to UInt. errorMessage={}", it.message, - it + it, ) } .getOrThrow() @@ -71,12 +71,12 @@ object TracesClientResponsesParser { } internal fun parseConflatedTracesToFileResponse( - jsonRpcResponse: JsonRpcSuccessResponse + jsonRpcResponse: JsonRpcSuccessResponse, ): GenerateTracesResponse { val result = jsonRpcResponse.result as JsonObject return GenerateTracesResponse( result.getString("conflatedTracesFileName"), - result.getString("tracesEngineVersion") + result.getString("tracesEngineVersion"), ) } } diff --git a/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2.kt b/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2.kt index 0dc4da07..60797cfc 100644 --- a/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2.kt +++ b/coordinator/clients/traces-generator-api-client/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2.kt @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicInteger class TracesGeneratorJsonRpcClientV2( private val rpcClient: JsonRpcClient, - private val config: Config + private val config: Config, ) : TracesCountersClientV2, TracesConflationClientV2 { constructor( @@ -25,28 +25,28 @@ class TracesGeneratorJsonRpcClientV2( rpcClient: JsonRpcClient, config: Config, retryConfig: RequestRetryConfig, - log: Logger = LogManager.getLogger(TracesGeneratorJsonRpcClientV2::class.java) + log: Logger = LogManager.getLogger(TracesGeneratorJsonRpcClientV2::class.java), ) : this( JsonRpcRequestRetryer( vertx, rpcClient, config = JsonRpcRequestRetryer.Config( methodsToRetry = retryableMethods, - requestRetry = retryConfig + requestRetry = retryConfig, ), - log = log + log = log, ), - config + config, ) data class Config( - val expectedTracesApiVersion: String + val expectedTracesApiVersion: String, ) private var id = AtomicInteger(0) override fun getTracesCounters( - blockNumber: ULong + blockNumber: ULong, ): SafeFuture>> { val jsonRequest = JsonRpcRequestListParams( @@ -58,23 +58,23 @@ class TracesGeneratorJsonRpcClientV2( "blockNumber", blockNumber, "expectedTracesEngineVersion", - config.expectedTracesApiVersion - ) - ) + config.expectedTracesApiVersion, + ), + ), ) return rpcClient.makeRequest(jsonRequest).toSafeFuture() .thenApply { responseResult -> responseResult.mapEither( TracesClientResponsesParser::parseTracesCounterResponseV2, - TracesClientResponsesParser::mapErrorResponseV2 + TracesClientResponsesParser::mapErrorResponseV2, ) } } override fun generateConflatedTracesToFile( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): SafeFuture>> { val jsonRequest = JsonRpcRequestListParams( @@ -88,16 +88,16 @@ class TracesGeneratorJsonRpcClientV2( "endBlockNumber", endBlockNumber, "expectedTracesEngineVersion", - config.expectedTracesApiVersion - ) - ) + config.expectedTracesApiVersion, + ), + ), ) return rpcClient.makeRequest(jsonRequest).toSafeFuture() .thenApply { responseResult -> responseResult.mapEither( TracesClientResponsesParser::parseConflatedTracesToFileResponse, - TracesClientResponsesParser::mapErrorResponseV2 + TracesClientResponsesParser::mapErrorResponseV2, ) } } diff --git a/coordinator/clients/traces-generator-api-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2Test.kt b/coordinator/clients/traces-generator-api-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2Test.kt index fe0a49e8..ad7d2871 100644 --- a/coordinator/clients/traces-generator-api-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2Test.kt +++ b/coordinator/clients/traces-generator-api-client/src/test/kotlin/net/consensys/zkevm/coordinator/clients/TracesGeneratorJsonRpcClientV2Test.kt @@ -49,7 +49,8 @@ class TracesGeneratorJsonRpcClientV2Test { private val tracesCountersValid: Map = TracingModuleV2.values() .fold(mutableMapOf()) { acc: MutableMap, - evmModule: TracingModuleV2 -> + evmModule: TracingModuleV2, + -> acc[evmModule.name] = Random.nextUInt(0u, UInt.MAX_VALUE).toLong() acc } @@ -77,15 +78,15 @@ class TracesGeneratorJsonRpcClientV2Test { maxRetries = 2u, timeout = 10.seconds, backoffDelay = 10.milliseconds, - failuresWarningThreshold = 1u - ) + failuresWarningThreshold = 1u, + ), ) tracesGeneratorClient = TracesGeneratorJsonRpcClientV2( vertxHttpJsonRpcClient, TracesGeneratorJsonRpcClientV2.Config( - expectedTracesApiVersion = expectedTracesApiVersion - ) + expectedTracesApiVersion = expectedTracesApiVersion, + ), ) } @@ -105,8 +106,8 @@ class TracesGeneratorJsonRpcClientV2Test { "result", mapOf( "tracesEngineVersion" to tracesEngineVersion, - "tracesCounters" to tracesCountersValid - ) + "tracesCounters" to tracesCountersValid, + ), ) } @@ -117,7 +118,7 @@ class TracesGeneratorJsonRpcClientV2Test { "id", 1, "error", - mapOf("code" to "1", "message" to errorMessage, "data" to data) + mapOf("code" to "1", "message" to errorMessage, "data" to data), ) } @@ -130,8 +131,8 @@ class TracesGeneratorJsonRpcClientV2Test { post("/") .withHeader("Content-Type", containing("application/json")) .willReturn( - ok().withHeader("Content-type", "application/json").withBody(response.toString()) - ) + ok().withHeader("Content-type", "application/json").withBody(response.toString()), + ), ) val blockNumber = 1UL @@ -145,11 +146,11 @@ class TracesGeneratorJsonRpcClientV2Test { TracesCountersV2( tracesCountersValid .mapKeys { TracingModuleV2.valueOf(it.key) } - .mapValues { it.value.toUInt() } + .mapValues { it.value.toUInt() }, ), - tracesEngineVersion - ) - ) + tracesEngineVersion, + ), + ), ) val expectedJsonRequest = JsonObject.of( @@ -165,14 +166,14 @@ class TracesGeneratorJsonRpcClientV2Test { "blockNumber", 1, "expectedTracesEngineVersion", - expectedTracesApiVersion - ) - ) + expectedTracesApiVersion, + ), + ), ) wiremock.verify( postRequestedFor(urlEqualTo("/")) .withHeader("Content-Type", equalTo("application/json")) - .withRequestBody(equalToJson(expectedJsonRequest.toString(), false, true)) + .withRequestBody(equalToJson(expectedJsonRequest.toString(), false, true)), ) } @@ -191,16 +192,16 @@ class TracesGeneratorJsonRpcClientV2Test { "result", mapOf( "tracesEngineVersion" to tracesEngineVersion, - "tracesCounters" to tracesCountersMissingModule - ) + "tracesCounters" to tracesCountersMissingModule, + ), ) wiremock.stubFor( post("/") .withHeader("Content-Type", containing("application/json")) .willReturn( - ok().withHeader("Content-type", "application/json").withBody(response.toString()) - ) + ok().withHeader("Content-type", "application/json").withBody(response.toString()), + ), ) val blockNumber = 1UL @@ -224,16 +225,16 @@ class TracesGeneratorJsonRpcClientV2Test { "result", mapOf( "tracesEngineVersion" to tracesEngineVersion, - "tracesCounters" to tracesCountersMissingModule - ) + "tracesCounters" to tracesCountersMissingModule, + ), ) wiremock.stubFor( post("/") .withHeader("Content-Type", containing("application/json")) .willReturn( - ok().withHeader("Content-type", "application/json").withBody(response.toString()) - ) + ok().withHeader("Content-type", "application/json").withBody(response.toString()), + ), ) val blockNumber = 1UL @@ -260,8 +261,8 @@ class TracesGeneratorJsonRpcClientV2Test { "result", mapOf( "tracesEngineVersion" to tracesEngineVersion, - "conflatedTracesFileName" to conflatedTracesFileName - ) + "conflatedTracesFileName" to conflatedTracesFileName, + ), ) wiremock.stubFor( @@ -270,8 +271,8 @@ class TracesGeneratorJsonRpcClientV2Test { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(response.toString().toByteArray()) - ) + .withBody(response.toString().toByteArray()), + ), ) val queryStartBlockNumber = 1UL @@ -280,13 +281,13 @@ class TracesGeneratorJsonRpcClientV2Test { val resultFuture = tracesGeneratorClient.generateConflatedTracesToFile( queryStartBlockNumber, - queryEndBlockNumber + queryEndBlockNumber, ) resultFuture.get() assertThat(resultFuture) .isCompletedWithValue( - Ok(GenerateTracesResponse(conflatedTracesFileName, tracesEngineVersion)) + Ok(GenerateTracesResponse(conflatedTracesFileName, tracesEngineVersion)), ) val expectedJsonRequest = JsonObject.of( @@ -304,14 +305,14 @@ class TracesGeneratorJsonRpcClientV2Test { "endBlockNumber", queryEndBlockNumber.toLong(), "expectedTracesEngineVersion", - expectedTracesApiVersion - ) - ) + expectedTracesApiVersion, + ), + ), ) wiremock.verify( postRequestedFor(urlEqualTo("/")) .withHeader("Content-Type", equalTo("application/json")) - .withRequestBody(equalToJson(expectedJsonRequest.toString(), false, true)) + .withRequestBody(equalToJson(expectedJsonRequest.toString(), false, true)), ) } @@ -327,8 +328,8 @@ class TracesGeneratorJsonRpcClientV2Test { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(response.toString().toByteArray()) - ) + .withBody(response.toString().toByteArray()), + ), ) val blockNumber = 1UL @@ -337,7 +338,7 @@ class TracesGeneratorJsonRpcClientV2Test { assertThat(resultFuture) .isCompletedWithValue( - Err(ErrorResponse(TracesServiceErrorType.BLOCK_MISSING_IN_CHAIN, errorMessage)) + Err(ErrorResponse(TracesServiceErrorType.BLOCK_MISSING_IN_CHAIN, errorMessage)), ) } @@ -353,8 +354,8 @@ class TracesGeneratorJsonRpcClientV2Test { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(response.toString().toByteArray()) - ) + .withBody(response.toString().toByteArray()), + ), ) val startBlockNumber = 1UL @@ -363,13 +364,13 @@ class TracesGeneratorJsonRpcClientV2Test { val resultFuture = tracesGeneratorClient.generateConflatedTracesToFile( startBlockNumber, - endBlockNumber + endBlockNumber, ) resultFuture.get() assertThat(resultFuture) .isCompletedWithValue( - Err(ErrorResponse(TracesServiceErrorType.BLOCK_RANGE_TOO_LARGE, errorMessage)) + Err(ErrorResponse(TracesServiceErrorType.BLOCK_RANGE_TOO_LARGE, errorMessage)), ) } @@ -388,8 +389,8 @@ class TracesGeneratorJsonRpcClientV2Test { .willReturn( aResponse() .withStatus(500) - .withBody("Internal Server Error") - ) + .withBody("Internal Server Error"), + ), ) wiremock.stubFor( post("/") @@ -400,8 +401,8 @@ class TracesGeneratorJsonRpcClientV2Test { .willReturn( aResponse() .withStatus(200) - .withBody(jsonRpcErrorResponse.toString()) - ) + .withBody(jsonRpcErrorResponse.toString()), + ), ) wiremock.stubFor( post("/") @@ -421,24 +422,24 @@ class TracesGeneratorJsonRpcClientV2Test { "result", mapOf( "tracesEngineVersion" to tracesEngineVersion, - "conflatedTracesFileName" to "conflated-traces-1-3.json" - ) - ).toString() - ) - ) + "conflatedTracesFileName" to "conflated-traces-1-3.json", + ), + ).toString(), + ), + ), ) tracesGeneratorClient = TracesGeneratorJsonRpcClientV2( vertxHttpJsonRpcClient, TracesGeneratorJsonRpcClientV2.Config( - expectedTracesApiVersion = expectedTracesApiVersion - ) + expectedTracesApiVersion = expectedTracesApiVersion, + ), ) val blockNumber = 1UL val resultFuture = tracesGeneratorClient.generateConflatedTracesToFile( startBlockNumber = blockNumber, - endBlockNumber = blockNumber + endBlockNumber = blockNumber, ) assertThat(resultFuture.get()).isInstanceOf(Ok::class.java) diff --git a/coordinator/clients/web3signer-client/src/test/kotlin/Web3SignerRestClientTest.kt b/coordinator/clients/web3signer-client/src/test/kotlin/Web3SignerRestClientTest.kt index c17eb9ba..bf624c56 100644 --- a/coordinator/clients/web3signer-client/src/test/kotlin/Web3SignerRestClientTest.kt +++ b/coordinator/clients/web3signer-client/src/test/kotlin/Web3SignerRestClientTest.kt @@ -68,8 +68,8 @@ class Web3SignerRestClientTest { .willReturn( WireMock.ok() .withHeader("Content-type", "text/plain; charset=utf-8\n") - .withBody(returnSignature) - ) + .withBody(returnSignature), + ), ) val (r, s) = web3SignerClient.sign(Bytes.wrap(msg.toByteArray())) @@ -89,8 +89,8 @@ class Web3SignerRestClientTest { .willReturn( WireMock.notFound() .withHeader("Content-type", "text/plain; charset=utf-8\n") - .withStatusMessage("Public Key not found") - ) + .withStatusMessage("Public Key not found"), + ), ) assertThrows { web3SignerClient.sign(Bytes.wrap("Message".toByteArray())) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BatchExecutionProverRequestResponse.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BatchExecutionProverRequestResponse.kt index 81699d64..016067c1 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BatchExecutionProverRequestResponse.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BatchExecutionProverRequestResponse.kt @@ -10,7 +10,7 @@ data class BatchExecutionProofRequestV1( val bridgeLogs: List, val tracesResponse: GenerateTracesResponse, val type2StateData: GetZkEVMStateMerkleProofResponse, - val keccakParentStateRootHash: ByteArray + val keccakParentStateRootHash: ByteArray, ) : BlockInterval { override val startBlockNumber: ULong get() = blocks.first().number @@ -44,5 +44,5 @@ data class BatchExecutionProofRequestV1( data class BatchExecutionProofResponse( override val startBlockNumber: ULong, - override val endBlockNumber: ULong + override val endBlockNumber: ULong, ) : BlockInterval diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BlobCompressionProverRequestResponse.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BlobCompressionProverRequestResponse.kt index aecc4977..88521d5c 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BlobCompressionProverRequestResponse.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/BlobCompressionProverRequestResponse.kt @@ -15,7 +15,7 @@ data class BlobCompressionProofRequest( val expectedShnarfResult: ShnarfResult, val commitment: ByteArray, val kzgProofContract: ByteArray, - val kzgProofSideCar: ByteArray + val kzgProofSideCar: ByteArray, ) : BlockInterval { override val startBlockNumber: ULong get() = conflations.first().startBlockNumber @@ -75,7 +75,7 @@ data class BlobCompressionProof( val verifierID: Long, val commitment: ByteArray, val kzgProofContract: ByteArray, - val kzgProofSidecar: ByteArray + val kzgProofSidecar: ByteArray, ) { override fun equals(other: Any?): Boolean { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/RollupForkChoiceUpdatedClient.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/RollupForkChoiceUpdatedClient.kt index 081dab6d..ae4d632f 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/RollupForkChoiceUpdatedClient.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/RollupForkChoiceUpdatedClient.kt @@ -6,7 +6,7 @@ import net.consensys.linea.errors.ErrorResponse import tech.pegasys.teku.infrastructure.async.SafeFuture enum class RollupForkChoiceUpdatedError { - UNKNOWN + UNKNOWN, } data class RollupForkChoiceUpdatedResponse(val result: String) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesServiceClient.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesServiceClient.kt index 9f6c4c21..5b8389e0 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesServiceClient.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/TracesServiceClient.kt @@ -9,7 +9,7 @@ enum class TracesServiceErrorType { BLOCK_MISSING_IN_CHAIN, BLOCK_RANGE_TOO_LARGE, INVALID_TRACES_VERSION, - UNKNOWN_ERROR + UNKNOWN_ERROR, } data class GetTracesCountersResponse(val tracesCounters: TracesCounters, val tracesEngineVersion: String) @@ -18,13 +18,13 @@ data class GenerateTracesResponse(val tracesFileName: String, val tracesEngineVe interface TracesCountersClientV2 { fun getTracesCounters( - blockNumber: ULong + blockNumber: ULong, ): SafeFuture>> } interface TracesConflationClientV2 { fun generateConflatedTracesToFile( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): SafeFuture>> } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/smartcontract/LineaRollupSmartContractClient.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/smartcontract/LineaRollupSmartContractClient.kt index ff595b6f..4118ffae 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/smartcontract/LineaRollupSmartContractClient.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/coordinator/clients/smartcontract/LineaRollupSmartContractClient.kt @@ -8,7 +8,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class BlockAndNonce( val blockNumber: ULong, - val nonce: ULong + val nonce: ULong, ) interface LineaRollupSmartContractClient : LineaRollupSmartContractClientReadOnly { @@ -26,14 +26,14 @@ interface LineaRollupSmartContractClient : LineaRollupSmartContractClientReadOnl */ fun submitBlobsEthCall( blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture fun finalizeBlocksEthCall( aggregation: ProofToFinalize, aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): SafeFuture /** @@ -41,7 +41,7 @@ interface LineaRollupSmartContractClient : LineaRollupSmartContractClientReadOnl */ fun submitBlobs( blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture fun finalizeBlocks( @@ -49,7 +49,7 @@ interface LineaRollupSmartContractClient : LineaRollupSmartContractClientReadOnl aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, parentL1RollingHashMessageNumber: Long, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture fun finalizeBlocksAfterEthCall( @@ -57,7 +57,7 @@ interface LineaRollupSmartContractClient : LineaRollupSmartContractClientReadOnl aggregationLastBlob: BlobRecord, parentL1RollingHash: ByteArray, parentL1RollingHashMessageNumber: Long, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Aggregation.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Aggregation.kt index 8f96a066..eb05dab6 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Aggregation.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Aggregation.kt @@ -15,7 +15,7 @@ data class ProofsToAggregate( val executionProofs: BlockIntervals, val parentAggregationLastBlockTimestamp: Instant, val parentAggregationLastL1RollingHashMessageNumber: ULong, - val parentAggregationLastL1RollingHash: ByteArray + val parentAggregationLastL1RollingHash: ByteArray, ) : BlockInterval { override val startBlockNumber = compressionProofIndexes.first().startBlockNumber override val endBlockNumber = compressionProofIndexes.last().endBlockNumber @@ -68,7 +68,7 @@ data class ProofToFinalize( val l1RollingHashMessageNumber: Long, val l2MerkleRoots: List, val l2MerkleTreesDepth: Int, - val l2MessagingBlocksOffsets: ByteArray + val l2MessagingBlocksOffsets: ByteArray, ) : BlockInterval { override val startBlockNumber: ULong = firstBlockNumber.toULong() override val endBlockNumber: ULong = finalBlockNumber.toULong() @@ -126,11 +126,11 @@ data class Aggregation( override val startBlockNumber: ULong, override val endBlockNumber: ULong, val batchCount: ULong, - val aggregationProof: ProofToFinalize? + val aggregationProof: ProofToFinalize?, ) : BlockInterval { enum class Status { Proven, - Proving + Proving, } } @@ -140,7 +140,7 @@ data class FinalizationSubmittedEvent( val parentL1RollingHash: ByteArray, val parentL1RollingHashMessageNumber: Long, val submissionTimestamp: Instant, - val transactionHash: ByteArray + val transactionHash: ByteArray, ) : BlockInterval by aggregationProof { override fun equals(other: Any?): Boolean { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Blob.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Blob.kt index 2c2c36d5..05985023 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Blob.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Blob.kt @@ -10,7 +10,7 @@ data class Blob( val conflations: List, val compressedData: ByteArray, val startBlockTime: Instant, - val endBlockTime: Instant + val endBlockTime: Instant, ) : BlockInterval { override val startBlockNumber: ULong @@ -70,7 +70,7 @@ data class Blob( data class BlobAndBatchCounters( val blobCounters: BlobCounters, - val executionProofs: BlockIntervals + val executionProofs: BlockIntervals, ) data class BlobCounters( val numberOfBatches: UInt, @@ -78,7 +78,7 @@ data class BlobCounters( override val endBlockNumber: ULong, val startBlockTimestamp: Instant, val endBlockTimestamp: Instant, - val expectedShnarf: ByteArray + val expectedShnarf: ByteArray, ) : BlockInterval { companion object { fun areAllConsecutive(blobs: List): Boolean { @@ -124,7 +124,7 @@ data class BlobRecord( val batchesCount: UInt, val expectedShnarf: ByteArray, // Unproven records will have null here - val blobCompressionProof: BlobCompressionProof? = null + val blobCompressionProof: BlobCompressionProof? = null, ) : BlockInterval { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -160,7 +160,7 @@ data class BlobRecord( enum class BlobStatus { COMPRESSION_PROVING, - COMPRESSION_PROVEN + COMPRESSION_PROVEN, } data class BlobSubmittedEvent( @@ -168,7 +168,7 @@ data class BlobSubmittedEvent( val endBlockTime: Instant, val lastShnarf: ByteArray, val submissionTimestamp: Instant, - val transactionHash: ByteArray + val transactionHash: ByteArray, ) { fun getSubmissionDelay(): Long { return submissionTimestamp.minus(endBlockTime).inWholeSeconds diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Conflation.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Conflation.kt index 8ef681cf..d01177dc 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Conflation.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/Conflation.kt @@ -9,7 +9,7 @@ import net.consensys.linea.traces.TracesCounters data class BlocksConflation( val blocks: List, - val conflationResult: ConflationCalculationResult + val conflationResult: ConflationCalculationResult, ) : BlockInterval { init { require(blocks.isSortedBy { it.number }) { "Blocks list must be sorted by blockNumber" } @@ -23,7 +23,7 @@ data class BlocksConflation( data class Batch( val startBlockNumber: ULong, - val endBlockNumber: ULong + val endBlockNumber: ULong, ) { init { require(startBlockNumber <= endBlockNumber) { @@ -33,7 +33,7 @@ data class Batch( enum class Status { Finalized, // Batch is finalized on L1 - Proven // Batch is ready to be sent to L1 to be finalized + Proven, // Batch is ready to be sent to L1 to be finalized } fun intervalString(): String = @@ -52,14 +52,14 @@ enum class ConflationTrigger(val triggerPriority: Int) { TRACES_LIMIT(3), TIME_LIMIT(4), BLOCKS_LIMIT(5), - SWITCH_CUTOFF(6) + SWITCH_CUTOFF(6), } data class ConflationCalculationResult( override val startBlockNumber: ULong, override val endBlockNumber: ULong, val conflationTrigger: ConflationTrigger, - val tracesCounters: TracesCounters + val tracesCounters: TracesCounters, ) : BlockInterval { init { require(startBlockNumber <= endBlockNumber) { @@ -74,7 +74,7 @@ data class BlockCounters( val tracesCounters: TracesCounters, val blockRLPEncoded: ByteArray, val numOfTransactions: UInt = 0u, - val gasUsed: ULong = 0uL + val gasUsed: ULong = 0uL, ) { override fun toString(): String { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/ProofIndex.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/ProofIndex.kt index 9ff75a35..dcd77b6c 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/ProofIndex.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/domain/ProofIndex.kt @@ -5,7 +5,7 @@ import linea.domain.BlockInterval data class ProofIndex( override val startBlockNumber: ULong, override val endBlockNumber: ULong, - val hash: ByteArray? = null + val hash: ByteArray? = null, ) : BlockInterval { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcher.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcher.kt index 83cfe255..9d3d3aea 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcher.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcher.kt @@ -6,7 +6,7 @@ import java.util.function.Consumer class EventDispatcher( private val consumers: Map, String>, - private val log: Logger = LogManager.getLogger(EventDispatcher::class.java) + private val log: Logger = LogManager.getLogger(EventDispatcher::class.java), ) : Consumer { override fun accept(event: T) { @@ -19,7 +19,7 @@ class EventDispatcher( name, event, e.message, - e + e, ) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationCalculator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationCalculator.kt index b42a6cdb..141b8cde 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationCalculator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationCalculator.kt @@ -17,12 +17,12 @@ enum class AggregationTriggerType { * Aggregation trigger by target block numbers specified in the configuration. * This is meant for either Development, Testing or Match specific blobs sent to L1. */ - TARGET_BLOCK_NUMBER + TARGET_BLOCK_NUMBER, } data class AggregationTrigger( val aggregationTriggerType: AggregationTriggerType, - val aggregation: BlobsToAggregate + val aggregation: BlobsToAggregate, ) fun interface AggregationTriggerHandler { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2State.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2State.kt index 649fd242..43648514 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2State.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2State.kt @@ -5,7 +5,7 @@ import kotlinx.datetime.Instant data class AggregationL2State( val parentAggregationLastBlockTimestamp: Instant, val parentAggregationLastL1RollingHashMessageNumber: ULong, - val parentAggregationLastL1RollingHash: ByteArray + val parentAggregationLastL1RollingHash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2StateProvider.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2StateProvider.kt index 5e34af00..e3c56300 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2StateProvider.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationL2StateProvider.kt @@ -12,12 +12,12 @@ interface AggregationL2StateProvider { class AggregationL2StateProviderImpl( private val ethApiClient: EthApiClient, - private val messageService: L2MessageServiceSmartContractClientReadOnly + private val messageService: L2MessageServiceSmartContractClientReadOnly, ) : AggregationL2StateProvider { private data class AnchoredMessage( val messageNumber: ULong, - val rollingHash: ByteArray + val rollingHash: ByteArray, ) private fun getLastAnchoredMessage(blockNumber: ULong): SafeFuture { @@ -34,7 +34,7 @@ class AggregationL2StateProviderImpl( .thenCompose { lastAnchoredMessageNumber -> messageService.getRollingHashByL1MessageNumber( block = blockNumber.toBlockParameter(), - l1MessageNumber = lastAnchoredMessageNumber + l1MessageNumber = lastAnchoredMessageNumber, ) .thenApply { rollingHash -> AnchoredMessage(lastAnchoredMessageNumber, rollingHash) } } @@ -46,12 +46,12 @@ class AggregationL2StateProviderImpl( val blockParameter = blockNumber.toBlockParameter() return getLastAnchoredMessage(blockNumber.toULong()) .thenCombine( - ethApiClient.getBlockByNumberWithoutTransactionsData(blockParameter) + ethApiClient.getBlockByNumberWithoutTransactionsData(blockParameter), ) { (messageNumber, rollingHash), block -> AggregationL2State( parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(block.timestamp.toLong()), parentAggregationLastL1RollingHashMessageNumber = messageNumber, - parentAggregationLastL1RollingHash = rollingHash + parentAggregationLastL1RollingHash = rollingHash, ) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadline.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadline.kt index 9284499e..88e9b717 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadline.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadline.kt @@ -18,13 +18,13 @@ import kotlin.time.Duration.Companion.seconds class AggregationTriggerCalculatorByDeadline( private val config: Config, private val clock: Clock = Clock.System, - private val latestBlockProvider: SafeBlockProvider + private val latestBlockProvider: SafeBlockProvider, ) : DeferredAggregationTriggerCalculator { data class Config(val aggregationDeadline: Duration, val aggregationDeadlineDelay: Duration) data class InFlightAggregation( val aggregationStartTimeStamp: Instant, - val blobsToAggregate: BlobsToAggregate + val blobsToAggregate: BlobsToAggregate, ) private var inFlightAggregation: InFlightAggregation? = null @@ -36,7 +36,7 @@ class AggregationTriggerCalculatorByDeadline( log.warn( "SafeBlock request failed. Will retry aggregation deadline on next tick errorMessage={}", th.message, - th + th, ) }.thenApply { val noActivityOnL2 = clock.now().minus(config.aggregationDeadlineDelay) > it.timestamp @@ -44,15 +44,15 @@ class AggregationTriggerCalculatorByDeadline( "Aggregation deadline checking trigger criteria lastBlockNumber={} latestL2SafeBlock={} noActivityOnL2={}", blobsToAggregate.endBlockNumber, it.number, - noActivityOnL2 + noActivityOnL2, ) if (it.number == blobsToAggregate.endBlockNumber && noActivityOnL2) { log.info("Aggregation Deadline reached at block {}", blobsToAggregate.endBlockNumber) aggregationTriggerHandler.onAggregationTrigger( AggregationTrigger( aggregationTriggerType = AggregationTriggerType.TIME_LIMIT, - aggregation = blobsToAggregate - ) + aggregation = blobsToAggregate, + ), ) } } @@ -65,12 +65,12 @@ class AggregationTriggerCalculatorByDeadline( "Checking deadline: inflightAggregation={} timeElapsed={} deadline={}", inFlightAggregation, inFlightAggregation?.aggregationStartTimeStamp?.let { now.minus(it) } ?: 0.seconds, - config.aggregationDeadline + config.aggregationDeadline, ) val deadlineReached = inFlightAggregation != null && now > inFlightAggregation!!.aggregationStartTimeStamp.plus( - config.aggregationDeadline + config.aggregationDeadline, ) if (!deadlineReached) { @@ -84,15 +84,15 @@ class AggregationTriggerCalculatorByDeadline( if (inFlightAggregation == null) { inFlightAggregation = InFlightAggregation( aggregationStartTimeStamp = blobCounters.startBlockTimestamp, - blobsToAggregate = BlobsToAggregate(blobCounters.startBlockNumber, blobCounters.endBlockNumber) + blobsToAggregate = BlobsToAggregate(blobCounters.startBlockNumber, blobCounters.endBlockNumber), ) } else { inFlightAggregation = InFlightAggregation( aggregationStartTimeStamp = inFlightAggregation!!.aggregationStartTimeStamp, blobsToAggregate = BlobsToAggregate( inFlightAggregation!!.blobsToAggregate.startBlockNumber, - blobCounters.endBlockNumber - ) + blobCounters.endBlockNumber, + ), ) } } @@ -111,7 +111,7 @@ class AggregationTriggerCalculatorByDeadline( class AggregationTriggerCalculatorByDeadlineRunner( private val vertx: Vertx, private val config: Config, - private val aggregationTriggerByDeadline: AggregationTriggerCalculatorByDeadline + private val aggregationTriggerByDeadline: AggregationTriggerCalculatorByDeadline, ) : DeferredAggregationTriggerCalculator by aggregationTriggerByDeadline, LongRunningService { data class Config(val deadlineCheckInterval: Duration) @@ -129,7 +129,7 @@ class AggregationTriggerCalculatorByDeadlineRunner( } deadlineCheckerTimerId = vertx.setTimer( config.deadlineCheckInterval.inWholeMilliseconds, - deadlineCheckerAction + deadlineCheckerAction, ) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimit.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimit.kt index 925d8d6f..88494ef3 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimit.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimit.kt @@ -8,7 +8,7 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati data class InFlightAggregation( val proofsCount: UInt, - val blobsToAggregate: BlobsToAggregate + val blobsToAggregate: BlobsToAggregate, ) private var inFlightAggregation: InFlightAggregation? = null @@ -23,7 +23,7 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati if (blobProofCount > maxProofsPerAggregation) { throw IllegalArgumentException( "Number of proofs in one blob exceed the aggregation proof limit. " + - "blob = $blobCounters" + "blob = $blobCounters", ) } @@ -32,15 +32,15 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati if (newProofsCount > maxProofsPerAggregation) { AggregationTrigger( aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, - aggregation = inFlightAggregation!!.blobsToAggregate + aggregation = inFlightAggregation!!.blobsToAggregate, ) } else if (newProofsCount == maxProofsPerAggregation) { AggregationTrigger( aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, aggregation = BlobsToAggregate( inFlightAggregation!!.blobsToAggregate.startBlockNumber, - blobCounters.endBlockNumber - ) + blobCounters.endBlockNumber, + ), ) } else { null @@ -51,8 +51,8 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, aggregation = BlobsToAggregate( blobCounters.startBlockNumber, - blobCounters.endBlockNumber - ) + blobCounters.endBlockNumber, + ), ) } else { null @@ -66,7 +66,7 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati if (blobProofCount > maxProofsPerAggregation) { throw IllegalArgumentException( "Number of proofs in one blob exceed the aggregation proof limit. " + - "blob = $blobCounters" + "blob = $blobCounters", ) } val newProofsCount = (inFlightAggregation?.proofsCount ?: 0u) + blobProofCount @@ -77,8 +77,8 @@ class AggregationTriggerCalculatorByProofLimit(private val maxProofsPerAggregati proofsCount = newProofsCount, blobsToAggregate = BlobsToAggregate( inFlightAggregation?.blobsToAggregate?.startBlockNumber ?: blobCounters.startBlockNumber, - blobCounters.endBlockNumber - ) + blobCounters.endBlockNumber, + ), ) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbers.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbers.kt index 477671c4..0689151a 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbers.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbers.kt @@ -8,7 +8,7 @@ import org.apache.logging.log4j.Logger class AggregationTriggerCalculatorByTargetBlockNumbers( targetEndBlockNumbers: List, - private val log: Logger = LogManager.getLogger(SyncAggregationTriggerCalculator::class.java) + private val log: Logger = LogManager.getLogger(SyncAggregationTriggerCalculator::class.java), ) : SyncAggregationTriggerCalculator { private val endBlockNumbers = targetEndBlockNumbers.sorted() private var firstBlobWasConsumed: Boolean = false @@ -27,7 +27,7 @@ class AggregationTriggerCalculatorByTargetBlockNumbers( "first blob={} is already beyond last target aggregation endBlockNumber={} " + "please check configuration", blob, - endBlockNumbers.last() + endBlockNumbers.last(), ) } @@ -42,7 +42,7 @@ class AggregationTriggerCalculatorByTargetBlockNumbers( log.warn( "blob={} overlaps target aggregation with endBlockNumber={}", blob.intervalString(), - overlapedTargetAggregation + overlapedTargetAggregation, ) null } @@ -52,8 +52,8 @@ class AggregationTriggerCalculatorByTargetBlockNumbers( aggregationTriggerType = AggregationTriggerType.TARGET_BLOCK_NUMBER, aggregation = BlobsToAggregate( startBlockNumber = inFlightAggregation?.startBlockNumber ?: blob.startBlockNumber, - endBlockNumber = blob.endBlockNumber - ) + endBlockNumber = blob.endBlockNumber, + ), ) } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProvider.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProvider.kt index 78561b04..561ff6a6 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProvider.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ConsecutiveProvenBlobsProvider.kt @@ -5,6 +5,6 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture fun interface ConsecutiveProvenBlobsProvider { fun findConsecutiveProvenBlobs( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture> } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculator.kt index 4bd180bc..d99916a1 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculator.kt @@ -14,7 +14,7 @@ class GlobalAggregationCalculator( private val syncAggregationTrigger: List, private val deferredAggregationTrigger: List, metricsFacade: MetricsFacade, - private val aggregationSizeMultipleOf: UInt + private val aggregationSizeMultipleOf: UInt, ) : AggregationCalculator { private var aggregationHandler: AggregationHandler = AggregationHandler.NOOP_HANDLER @@ -26,12 +26,12 @@ class GlobalAggregationCalculator( private val blobsCounter: Counter = metricsFacade.createCounter( category = LineaMetricsCategory.AGGREGATION, name = "calculator.blobs.accepted", - description = "Number of blobs accepted by aggregation calculator" + description = "Number of blobs accepted by aggregation calculator", ) private val batchesCounter: Counter = metricsFacade.createCounter( category = LineaMetricsCategory.AGGREGATION, name = "calculator.batches.accepted", - description = "Number of batches accepted by aggregation calculator" + description = "Number of batches accepted by aggregation calculator", ) init { @@ -43,7 +43,7 @@ class GlobalAggregationCalculator( description = "Number of proofs pending for aggregation", measurementSupplier = { pendingBlobs.size + pendingBlobs.sumOf { it.numberOfBatches }.toLong() - } + }, ) metricsFacade.createGauge( category = LineaMetricsCategory.AGGREGATION, @@ -51,7 +51,7 @@ class GlobalAggregationCalculator( description = "Number of batches pending for aggregation", measurementSupplier = { pendingBlobs.sumOf { it.numberOfBatches }.toLong() - } + }, ) metricsFacade.createGauge( category = LineaMetricsCategory.AGGREGATION, @@ -59,7 +59,7 @@ class GlobalAggregationCalculator( description = "Number of blobs pending for aggregation", measurementSupplier = { pendingBlobs.size - } + }, ) } @@ -109,7 +109,7 @@ class GlobalAggregationCalculator( val exception = IllegalStateException( "Aggregation triggered when pending blobs do not contain blobs within aggregation interval. " + "aggregationTrigger=$aggregationTrigger " + - "pendingBlobs=${pendingBlobs.map { it.intervalString() }}" + "pendingBlobs=${pendingBlobs.map { it.intervalString() }}", ) log.error(exception.message, exception) throw exception @@ -130,18 +130,18 @@ class GlobalAggregationCalculator( val updatedAggregationSize = getUpdatedAggregationSize( blobsInAggregation.size.toUInt(), - aggregationSizeMultipleOf + aggregationSizeMultipleOf, ) val blobsInUpdatedAggregation = blobsInAggregation.subList(0, updatedAggregationSize.toInt()) val blobsNotInUpdatedAggregation = blobsInAggregation.subList( updatedAggregationSize.toInt(), - blobsInAggregation.size + blobsInAggregation.size, ) val updatedAggregation = BlobsToAggregate( startBlockNumber = blobsInUpdatedAggregation.first().startBlockNumber, - endBlockNumber = blobsInUpdatedAggregation.last().endBlockNumber + endBlockNumber = blobsInUpdatedAggregation.last().endBlockNumber, ) log.info( @@ -153,7 +153,7 @@ class GlobalAggregationCalculator( blobsInUpdatedAggregation.size, blobsInUpdatedAggregation.sumOf { it.numberOfBatches }, blobsInUpdatedAggregation.map { it.intervalString() }, - aggregationSizeMultipleOf + aggregationSizeMultipleOf, ) // Reset the trigger calculators now that we have a valid aggregation to handle @@ -181,7 +181,7 @@ class GlobalAggregationCalculator( if (blockNumber != (lastBlockNumber + 1u)) { val error = IllegalArgumentException( "Blobs to aggregate must be sequential: lastBlockNumber=$lastBlockNumber, startBlockNumber=$blockNumber for " + - "new blob" + "new blob", ) log.error(error.message) throw error diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorService.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorService.kt index a69953b8..11d45e0a 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorService.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorService.kt @@ -36,32 +36,32 @@ class ProofAggregationCoordinatorService( private val proofAggregationClient: ProofAggregationProverClientV2, private val aggregationL2StateProvider: AggregationL2StateProvider, private val log: Logger = LogManager.getLogger(ProofAggregationCoordinatorService::class.java), - private val provenAggregationEndBlockNumberConsumer: Consumer = Consumer { } + private val provenAggregationEndBlockNumberConsumer: Consumer = Consumer { }, ) : AggregationHandler, PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { data class Config( val pollingInterval: Duration, - val proofsLimit: UInt + val proofsLimit: UInt, ) private val pendingBlobs = ConcurrentLinkedQueue() private val aggregationSizeInBlocksHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.AGGREGATION, name = "blocks.size", - description = "Number of blocks in each aggregation" + description = "Number of blocks in each aggregation", ) private val aggregationSizeInBatchesHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.AGGREGATION, name = "batches.size", - description = "Number of batches in each aggregation" + description = "Number of batches in each aggregation", ) private val aggregationSizeInBlobsHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.AGGREGATION, name = "blobs.size", - description = "Number of blobs in each aggregation" + description = "Number of blobs in each aggregation", ) init { @@ -123,7 +123,7 @@ class ProofAggregationCoordinatorService( blobs.size, numberOfBatches, blobs.size + numberOfBatches.toInt(), - blobs.map(BlobAndBatchCounters::blobCounters).toBlockIntervalsString() + blobs.map(BlobAndBatchCounters::blobCounters).toBlockIntervalsString(), ) } else { log.debug("Found no new blobs for aggregation. nextBlockToPoll={}", nextBlockNumberToPoll) @@ -157,7 +157,7 @@ class ProofAggregationCoordinatorService( ProofIndex( startBlockNumber = it.blobCounters.startBlockNumber, endBlockNumber = it.blobCounters.endBlockNumber, - hash = it.blobCounters.expectedShnarf + hash = it.blobCounters.expectedShnarf, ) } @@ -174,7 +174,7 @@ class ProofAggregationCoordinatorService( "failed to get parent aggregation l2 message rolling hash: aggregation={} errorMessage={}", blobsToAggregate.intervalString(), it.message, - it + it, ) } .thenApply { rollingInfo -> @@ -183,7 +183,7 @@ class ProofAggregationCoordinatorService( executionProofs = blockIntervals, parentAggregationLastBlockTimestamp = rollingInfo.parentAggregationLastBlockTimestamp, parentAggregationLastL1RollingHashMessageNumber = rollingInfo.parentAggregationLastL1RollingHashMessageNumber, - parentAggregationLastL1RollingHash = rollingInfo.parentAggregationLastL1RollingHash + parentAggregationLastL1RollingHash = rollingInfo.parentAggregationLastL1RollingHash, ) } .thenCompose(proofAggregationClient::requestProof) @@ -192,7 +192,7 @@ class ProofAggregationCoordinatorService( "Error getting aggregation proof: aggregation={} errorMessage={}", blobsToAggregate.intervalString(), it.message, - it + it, ) } .thenCompose { aggregationProof -> @@ -200,7 +200,7 @@ class ProofAggregationCoordinatorService( startBlockNumber = blobsToAggregate.startBlockNumber, endBlockNumber = blobsToAggregate.endBlockNumber, batchCount = batchCount.toULong(), - aggregationProof = aggregationProof + aggregationProof = aggregationProof, ) aggregationsRepository .saveNewAggregation(aggregation = aggregation) @@ -212,7 +212,7 @@ class ProofAggregationCoordinatorService( "Error saving proven aggregation to DB: aggregation={} errorMessage={}", blobsToAggregate.intervalString(), it.message, - it + it, ) } } @@ -236,16 +236,16 @@ class ProofAggregationCoordinatorService( targetEndBlockNumbers: List, metricsFacade: MetricsFacade, provenAggregationEndBlockNumberConsumer: Consumer, - aggregationSizeMultipleOf: UInt + aggregationSizeMultipleOf: UInt, ): LongRunningService { val aggregationCalculatorByDeadline = AggregationTriggerCalculatorByDeadline( config = AggregationTriggerCalculatorByDeadline.Config( aggregationDeadline = aggregationDeadline, - aggregationDeadlineDelay = aggregationDeadlineDelay + aggregationDeadlineDelay = aggregationDeadlineDelay, ), clock = Clock.System, - latestBlockProvider = latestBlockProvider + latestBlockProvider = latestBlockProvider, ) val syncAggregationTriggerCalculators = mutableListOf() syncAggregationTriggerCalculators @@ -259,22 +259,22 @@ class ProofAggregationCoordinatorService( syncAggregationTrigger = syncAggregationTriggerCalculators, deferredAggregationTrigger = listOf(aggregationCalculatorByDeadline), metricsFacade = metricsFacade, - aggregationSizeMultipleOf = aggregationSizeMultipleOf + aggregationSizeMultipleOf = aggregationSizeMultipleOf, ) val deadlineCheckRunner = AggregationTriggerCalculatorByDeadlineRunner( vertx = vertx, config = AggregationTriggerCalculatorByDeadlineRunner.Config( - deadlineCheckInterval = deadlineCheckInterval + deadlineCheckInterval = deadlineCheckInterval, ), - aggregationTriggerByDeadline = aggregationCalculatorByDeadline + aggregationTriggerByDeadline = aggregationCalculatorByDeadline, ) val proofAggregationService = ProofAggregationCoordinatorService( vertx = vertx, config = Config( pollingInterval = aggregationCoordinatorPollingInterval, - proofsLimit = maxProofsPerAggregation + proofsLimit = maxProofsPerAggregation, ), metricsFacade = metricsFacade, nextBlockNumberToPoll = startBlockNumberInclusive.toLong(), @@ -284,9 +284,9 @@ class ProofAggregationCoordinatorService( proofAggregationClient = proofAggregationClient, aggregationL2StateProvider = AggregationL2StateProviderImpl( ethApiClient = l2EthApiClient, - messageService = l2MessageService + messageService = l2MessageService, ), - provenAggregationEndBlockNumberConsumer = provenAggregationEndBlockNumberConsumer + provenAggregationEndBlockNumberConsumer = provenAggregationEndBlockNumberConsumer, ) return LongRunningService.compose(deadlineCheckRunner, proofAggregationService) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinator.kt index cc86e7da..1dfe5d02 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinator.kt @@ -31,7 +31,7 @@ class BlobCompressionProofCoordinator( private val blobZkStateProvider: BlobZkStateProvider, private val config: Config, private val blobCompressionProofHandler: BlobCompressionProofHandler, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ) : BlobCreationHandler, LongRunningService { private val log: Logger = LogManager.getLogger(this::class.java) private val defaultQueueCapacity = 1000 // Should be more than blob submission limit @@ -42,17 +42,17 @@ class BlobCompressionProofCoordinator( private val blobsCounter = metricsFacade.createCounter( category = LineaMetricsCategory.BLOB, name = "counter", - description = "New blobs arriving to blob compression proof coordinator" + description = "New blobs arriving to blob compression proof coordinator", ) private val blobSizeInBlocksHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "blocks.size", - description = "Number of blocks in each blob" + description = "Number of blocks in each blob", ) private val blobSizeInBatchesHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "batches.size", - description = "Number of batches in each blob" + description = "Number of batches in each blob", ) init { @@ -60,12 +60,12 @@ class BlobCompressionProofCoordinator( category = LineaMetricsCategory.BLOB, name = "compression.queue.size", description = "Size of blob compression proving queue", - measurementSupplier = { blobsToHandle.size } + measurementSupplier = { blobsToHandle.size }, ) } data class Config( - val pollingInterval: Duration + val pollingInterval: Duration, ) @Synchronized @@ -81,8 +81,8 @@ class BlobCompressionProofCoordinator( finalStateRootHash = blobZkState.finalStateRootHash, conflationOrder = BlockIntervals( startingBlockNumber = blob.conflations.first().startBlockNumber, - upperBoundaries = blob.conflations.map { it.endBlockNumber } - ) + upperBoundaries = blob.conflations.map { it.endBlockNumber }, + ), ).thenApply { rollingBlobShnarfResult -> Pair(blobZkState, rollingBlobShnarfResult) } @@ -101,13 +101,13 @@ class BlobCompressionProofCoordinator( kzgProofContract = rollingBlobShnarfResult.shnarfResult.kzgProofContract, kzgProofSideCar = rollingBlobShnarfResult.shnarfResult.kzgProofSideCar, blobStartBlockTime = blob.startBlockTime, - blobEndBlockTime = blob.endBlockTime + blobEndBlockTime = blob.endBlockTime, ).whenException { exception -> log.error( "Error in requesting blob compression proof: blob={} errorMessage={} ", blob.intervalString(), exception.message, - exception + exception, ) } } @@ -128,7 +128,7 @@ class BlobCompressionProofCoordinator( kzgProofContract: ByteArray, kzgProofSideCar: ByteArray, blobStartBlockTime: Instant, - blobEndBlockTime: Instant + blobEndBlockTime: Instant, ): SafeFuture { val proofRequest = BlobCompressionProofRequest( compressedData = compressedData, @@ -140,7 +140,7 @@ class BlobCompressionProofCoordinator( expectedShnarfResult = expectedShnarfResult, commitment = commitment, kzgProofContract = kzgProofContract, - kzgProofSideCar = kzgProofSideCar + kzgProofSideCar = kzgProofSideCar, ) return blobCompressionProverClient.requestProof(proofRequest) .thenCompose { blobCompressionProof -> @@ -152,7 +152,7 @@ class BlobCompressionProofCoordinator( endBlockTime = blobEndBlockTime, batchesCount = conflations.size.toUInt(), expectedShnarf = expectedShnarfResult.expectedShnarf, - blobCompressionProof = blobCompressionProof + blobCompressionProof = blobCompressionProof, ) SafeFuture.allOf( blobsRepository.saveNewBlob(blobRecord), @@ -160,11 +160,11 @@ class BlobCompressionProofCoordinator( BlobCompressionProofUpdate( blockInterval = BlockInterval.between( startBlockNumber = blobRecord.startBlockNumber, - endBlockNumber = blobRecord.endBlockNumber + endBlockNumber = blobRecord.endBlockNumber, ), - blobCompressionProof = blobCompressionProof - ) - ) + blobCompressionProof = blobCompressionProof, + ), + ), ).thenApply {} } } @@ -176,7 +176,7 @@ class BlobCompressionProofCoordinator( "new blob: blob={} queuedBlobsToProve={} blobBatches={}", blob.intervalString(), blobsToHandle.size, - blob.conflations.toBlockIntervalsString() + blob.conflations.toBlockIntervalsString(), ) blobSizeInBlocksHistogram.record(blob.blocksRange.count().toDouble()) blobSizeInBatchesHistogram.record(blob.conflations.size.toDouble()) @@ -207,7 +207,7 @@ class BlobCompressionProofCoordinator( "Error handling blob from BlobCompressionProofCoordinator queue: blob={} errorMessage={}", blobToHandle.intervalString(), exception.message, - exception + exception, ) } } else { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofHandler.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofHandler.kt index 827c92fc..f2ffcf1c 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofHandler.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofHandler.kt @@ -6,7 +6,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class BlobCompressionProofUpdate( val blockInterval: BlockInterval, - val blobCompressionProof: BlobCompressionProof + val blobCompressionProof: BlobCompressionProof, ) fun interface BlobCompressionProofHandler { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressor.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressor.kt index 7f792b3a..802826cc 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressor.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressor.kt @@ -33,14 +33,14 @@ interface BlobCompressor { val blockAppended: Boolean, val compressedSizeBefore: Int, // even when block is not appended, compressedSizeAfter should as if it was appended - val compressedSizeAfter: Int + val compressedSizeAfter: Int, ) } class GoBackedBlobCompressor private constructor( internal val goNativeBlobCompressor: GoNativeBlobCompressor, private val dataLimit: UInt, - private val metricsFacade: MetricsFacade + private val metricsFacade: MetricsFacade, ) : BlobCompressor { companion object { @@ -50,7 +50,7 @@ class GoBackedBlobCompressor private constructor( fun getInstance( compressorVersion: BlobCompressorVersion, dataLimit: UInt, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ): GoBackedBlobCompressor { if (instance == null) { synchronized(this) { @@ -58,7 +58,7 @@ class GoBackedBlobCompressor private constructor( val goNativeBlobCompressor = GoNativeBlobCompressorFactory.getInstance(compressorVersion) val initialized = goNativeBlobCompressor.Init( dataLimit.toInt(), - GoNativeBlobCompressorFactory.dictionaryPath.toString() + GoNativeBlobCompressorFactory.dictionaryPath.toString(), ) if (!initialized) { throw InstantiationException(goNativeBlobCompressor.Error()) @@ -78,24 +78,24 @@ class GoBackedBlobCompressor private constructor( private val canAppendBlockTimer: TimerCapture = metricsFacade.createSimpleTimer( category = LineaMetricsCategory.BLOB, name = "compressor.canappendblock", - description = "Time taken to check if block fits in current blob" + description = "Time taken to check if block fits in current blob", ) private val appendBlockTimer: TimerCapture = metricsFacade.createSimpleTimer( category = LineaMetricsCategory.BLOB, name = "compressor.appendblock", - description = "Time taken to compress block into current blob" + description = "Time taken to compress block into current blob", ) private val compressionRatioHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "block.compression.ratio", description = "Block compression ratio measured in [0.0,1.0]", - isRatio = true + isRatio = true, ) private val utilizationRatioHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "data.utilization.ratio", description = "Data utilization ratio of a blob measured in [0.0,1.0]", - isRatio = true + isRatio = true, ) private val log = LogManager.getLogger(GoBackedBlobCompressor::class.java) @@ -120,7 +120,7 @@ class GoBackedBlobCompressor private constructor( blockRLPEncoded.size, compressionSizeBefore, compressedSizeAfter, - compressionRatio + compressionRatio, ) val error = goNativeBlobCompressor.Error() if (error != null) { @@ -151,7 +151,7 @@ class FakeBlobCompressor( // 1 means no compression // 0.5 means compressed data is 50% smaller than original // 1.1 means compressed data is 10% bigger than original - private val fakeCompressionRatio: Double = 1.0 + private val fakeCompressionRatio: Double = 1.0, ) : BlobCompressor { val log = LogManager.getLogger(FakeBlobCompressor::class.java) @@ -178,7 +178,7 @@ class FakeBlobCompressor( BlobCompressor.AppendResult( false, compressedSizeBefore, - compressedSizeAfter + compressedSizeAfter, ) } else { compressedData += compressedBlock diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobShnarfCalulator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobShnarfCalulator.kt index 8d02e61c..e21655cd 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobShnarfCalulator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobShnarfCalulator.kt @@ -26,7 +26,7 @@ data class ShnarfResult( val expectedShnarf: ByteArray, val commitment: ByteArray, val kzgProofContract: ByteArray, - val kzgProofSideCar: ByteArray + val kzgProofSideCar: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -65,13 +65,13 @@ interface BlobShnarfCalculator { parentStateRootHash: ByteArray, finalStateRootHash: ByteArray, prevShnarf: ByteArray, - conflationOrder: BlockIntervals + conflationOrder: BlockIntervals, ): ShnarfResult } class GoBackedBlobShnarfCalculator( private val delegate: GoNativeBlobShnarfCalculator, - private val metricsFacade: MetricsFacade + private val metricsFacade: MetricsFacade, ) : BlobShnarfCalculator { constructor(version: ShnarfCalculatorVersion, metricsFacade: MetricsFacade) : this(GoNativeShnarfCalculatorFactory.getInstance(version), metricsFacade) @@ -79,7 +79,7 @@ class GoBackedBlobShnarfCalculator( private val calculateShnarfTimer: TimerCapture = metricsFacade.createSimpleTimer( category = LineaMetricsCategory.BLOB, name = "shnarf.calculation", - description = "Time taken to calculate the shnarf hash of the given blob" + description = "Time taken to calculate the shnarf hash of the given blob", ) private val log: Logger = LogManager.getLogger(GoBackedBlobShnarfCalculator::class.java) @@ -90,7 +90,7 @@ class GoBackedBlobShnarfCalculator( parentStateRootHash: ByteArray, finalStateRootHash: ByteArray, prevShnarf: ByteArray, - conflationOrder: BlockIntervals + conflationOrder: BlockIntervals, ): ShnarfResult { val compressedDataB64 = Base64.getEncoder().encodeToString(compressedData) log.trace( @@ -106,7 +106,7 @@ class GoBackedBlobShnarfCalculator( parentStateRootHash.encodeHex(), finalStateRootHash.encodeHex(), prevShnarf.encodeHex(), - conflationOrder + conflationOrder, ) val result = calculateShnarfTimer.captureTime { @@ -118,7 +118,7 @@ class GoBackedBlobShnarfCalculator( prevShnarf = prevShnarf.encodeHex(), conflationOrderStartingBlockNumber = conflationOrder.startingBlockNumber.toLong(), conflationOrderUpperBoundariesLen = conflationOrder.upperBoundaries.size, - conflationOrderUpperBoundaries = conflationOrder.upperBoundaries.map { it.toLong() }.toLongArray() + conflationOrderUpperBoundaries = conflationOrder.upperBoundaries.map { it.toLong() }.toLongArray(), ) } @@ -136,7 +136,7 @@ class GoBackedBlobShnarfCalculator( expectedShnarf = result.expectedShnarf.decodeHex(), commitment = result.commitment.decodeHex(), kzgProofContract = result.kzgProofContract.decodeHex(), - kzgProofSideCar = result.kzgProofSideCar.decodeHex() + kzgProofSideCar = result.kzgProofSideCar.decodeHex(), ) } catch (it: Exception) { throw RuntimeException("Error while decoding Shnarf calculation response from Go: ${it.message}") @@ -156,7 +156,7 @@ class FakeBlobShnarfCalculator : BlobShnarfCalculator { parentStateRootHash: ByteArray, finalStateRootHash: ByteArray, prevShnarf: ByteArray, - conflationOrder: BlockIntervals + conflationOrder: BlockIntervals, ): ShnarfResult { return ShnarfResult( dataHash = Random.nextBytes(32), @@ -166,7 +166,7 @@ class FakeBlobShnarfCalculator : BlobShnarfCalculator { expectedShnarf = Random.nextBytes(32), commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSideCar = Random.nextBytes(48) + kzgProofSideCar = Random.nextBytes(48), ) } } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProvider.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProvider.kt index e600f3d8..531a079e 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProvider.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobZkStateProvider.kt @@ -4,7 +4,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class BlobZkState( val parentStateRootHash: ByteArray, - val finalStateRootHash: ByteArray + val finalStateRootHash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/ParentBlobDataProvider.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/ParentBlobDataProvider.kt index b2c2fd47..b43a9493 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/ParentBlobDataProvider.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/ParentBlobDataProvider.kt @@ -6,7 +6,7 @@ data class ParentBlobAndZkStateData( val parentBlobHash: ByteArray, val parentBlobShnarf: ByteArray, val parentStateRootHash: ByteArray, - val finalStateRootHash: ByteArray + val finalStateRootHash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculator.kt index 11dea61c..2f917bfc 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculator.kt @@ -18,7 +18,7 @@ import java.util.concurrent.atomic.AtomicReference data class RollingBlobShnarfResult( val shnarfResult: ShnarfResult, val parentBlobHash: ByteArray, - val parentBlobShnarf: ByteArray + val parentBlobShnarf: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -44,14 +44,14 @@ data class RollingBlobShnarfResult( class RollingBlobShnarfCalculator( private val blobShnarfCalculator: BlobShnarfCalculator, private val blobsRepository: BlobsRepository, - private val genesisShnarf: ByteArray + private val genesisShnarf: ByteArray, ) { private val log: Logger = LogManager.getLogger(this::class.java) private data class ParentBlobData( val endBlockNumber: ULong, val blobHash: ByteArray, - val blobShnarf: ByteArray + val blobShnarf: ByteArray, ) private var parentBlobDataReference: AtomicReference = AtomicReference(null) @@ -61,14 +61,14 @@ class RollingBlobShnarfCalculator( return if (parentBlobEndBlockNumber == 0UL) { log.info( "Requested parent shnarf for the genesis block, returning genesisShnarf={}", - genesisShnarf.encodeHex() + genesisShnarf.encodeHex(), ) SafeFuture.completedFuture( ParentBlobData( endBlockNumber = 0UL, blobHash = ByteArray(32), - blobShnarf = genesisShnarf - ) + blobShnarf = genesisShnarf, + ), ) } else if (parentBlobDataReference.get() != null) { val parentBlobData = parentBlobDataReference.get()!! @@ -76,8 +76,8 @@ class RollingBlobShnarfCalculator( SafeFuture.failedFuture( IllegalStateException( "Blob block range start block number=${blobBlockRange.startBlockNumber} " + - "is not equal to parent blob end block number=${parentBlobData.endBlockNumber} + 1" - ) + "is not equal to parent blob end block number=${parentBlobData.endBlockNumber} + 1", + ), ) } else { SafeFuture.completedFuture(parentBlobData) @@ -91,12 +91,12 @@ class RollingBlobShnarfCalculator( ParentBlobData( endBlockNumber = blobRecord.endBlockNumber, blobHash = blobRecord.blobHash, - blobShnarf = blobRecord.expectedShnarf - ) + blobShnarf = blobRecord.expectedShnarf, + ), ) } else { SafeFuture.failedFuture( - IllegalStateException("Failed to find the parent blob in db with end block=$parentBlobEndBlockNumber") + IllegalStateException("Failed to find the parent blob in db with end block=$parentBlobEndBlockNumber"), ) } } @@ -107,11 +107,11 @@ class RollingBlobShnarfCalculator( compressedData: ByteArray, parentStateRootHash: ByteArray, finalStateRootHash: ByteArray, - conflationOrder: BlockIntervals + conflationOrder: BlockIntervals, ): SafeFuture { val blobBlockRange = BlockInterval.between( conflationOrder.startingBlockNumber, - conflationOrder.upperBoundaries.last() + conflationOrder.upperBoundaries.last(), ) return getParentBlobData(blobBlockRange).thenCompose { parentBlobData -> runCatching { @@ -120,23 +120,23 @@ class RollingBlobShnarfCalculator( parentStateRootHash = parentStateRootHash, finalStateRootHash = finalStateRootHash, prevShnarf = parentBlobData.blobShnarf, - conflationOrder = conflationOrder + conflationOrder = conflationOrder, ) }.onSuccess { shnarfResult -> parentBlobDataReference.set( ParentBlobData( endBlockNumber = blobBlockRange.endBlockNumber, blobHash = shnarfResult.dataHash, - blobShnarf = shnarfResult.expectedShnarf - ) + blobShnarf = shnarfResult.expectedShnarf, + ), ) }.map { SafeFuture.completedFuture( RollingBlobShnarfResult( shnarfResult = it, parentBlobHash = parentBlobData.blobHash, - parentBlobShnarf = parentBlobData.blobShnarf - ) + parentBlobShnarf = parentBlobData.blobShnarf, + ), ) }.recover { error -> SafeFuture.failedFuture(error) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/BlockCreationCoordinator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/BlockCreationCoordinator.kt index 6482a815..8cde323a 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/BlockCreationCoordinator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/blockcreation/BlockCreationCoordinator.kt @@ -4,7 +4,7 @@ import linea.domain.Block import tech.pegasys.teku.infrastructure.async.SafeFuture data class BlockCreated( - val block: Block + val block: Block, ) fun interface BlockCreationListener { diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinator.kt index 7b6f359e..b5faf123 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinator.kt @@ -24,10 +24,10 @@ class BlockToBatchSubmissionCoordinator( private val tracesCountersClient: TracesCountersClientV2, private val vertx: Vertx, private val encoder: BlockEncoder, - private val log: Logger = LogManager.getLogger(BlockToBatchSubmissionCoordinator::class.java) + private val log: Logger = LogManager.getLogger(BlockToBatchSubmissionCoordinator::class.java), ) : BlockCreationListener { private fun getTracesCounters( - block: Block + block: Block, ): SafeFuture { return tracesCountersClient .getTracesCounters(block.number) @@ -56,15 +56,15 @@ class BlockToBatchSubmissionCoordinator( tracesCounters = traces.tracesCounters, blockRLPEncoded = blockRLPEncoded, numOfTransactions = blockEvent.block.transactions.size.toUInt(), - gasUsed = blockEvent.block.gasUsed - ) + gasUsed = blockEvent.block.gasUsed, + ), ) }.whenException { th -> log.error( "Failed to conflate block={} errorMessage={}", blockEvent.block.number, th.message, - th + th, ) } @@ -76,7 +76,7 @@ class BlockToBatchSubmissionCoordinator( return vertx.executeBlocking( Callable { encoder.encode(block) - } + }, ) .toSafeFuture() } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimit.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimit.kt index 4b3d7d8a..2271d3c2 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimit.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimit.kt @@ -4,7 +4,7 @@ import net.consensys.zkevm.domain.BlockCounters import net.consensys.zkevm.domain.ConflationTrigger class ConflationCalculatorByBlockLimit( - private val blockLimit: UInt + private val blockLimit: UInt, ) : ConflationCalculator { override val id: String = ConflationTrigger.BLOCKS_LIMIT.name private var blockCount: UInt = 0u @@ -29,7 +29,7 @@ class ConflationCalculatorByBlockLimit( } override fun copyCountersTo( - counters: ConflationCounters + counters: ConflationCounters, ) { counters.blockCount = blockCount } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressed.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressed.kt index 0c61dda9..8867515d 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressed.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressed.kt @@ -8,7 +8,7 @@ import org.apache.logging.log4j.Logger class ConflationCalculatorByDataCompressed( private val blobCompressor: BlobCompressor, - private val log: Logger = LogManager.getLogger(ConflationCalculatorByDataCompressed::class.java) + private val log: Logger = LogManager.getLogger(ConflationCalculatorByDataCompressed::class.java), ) : ConflationCalculator { override val id: String = ConflationTrigger.DATA_LIMIT.name internal var dataSizeUpToLastBatch: UInt = 0u @@ -30,7 +30,7 @@ class ConflationCalculatorByDataCompressed( blockCounters.blockNumber, dataSize, dataSizeUpToLastBatch, - overflowResult + overflowResult, ) return overflowResult } @@ -51,7 +51,7 @@ class ConflationCalculatorByDataCompressed( blockCounters.blockRLPEncoded.size, appendResult.compressedSizeBefore, appendResult.compressedSizeAfter, - compressionRatio + compressionRatio, ) if (!appendResult.blockAppended) { @@ -70,7 +70,7 @@ class ConflationCalculatorByDataCompressed( } override fun copyCountersTo( - counters: ConflationCounters + counters: ConflationCounters, ) { counters.dataSize = dataSize - dataSizeUpToLastBatch } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTraces.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTraces.kt index 5614f57f..75d16f05 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTraces.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTraces.kt @@ -18,7 +18,7 @@ class ConflationCalculatorByExecutionTraces( val tracesCountersLimit: TracesCounters, private val emptyTracesCounters: TracesCounters, metricsFacade: MetricsFacade, - private val log: Logger = LogManager.getLogger(ConflationCalculatorByExecutionTraces::class.java) + private val log: Logger = LogManager.getLogger(ConflationCalculatorByExecutionTraces::class.java), ) : ConflationCalculator { private val overflownTracesMetricsCounters = HashMap().also { tracesCountersLimit.entries() @@ -30,9 +30,9 @@ class ConflationCalculatorByExecutionTraces( tags = listOf( Tag( key = "module", - value = module.name - ) - ) + value = module.name, + ), + ), ) } } @@ -67,7 +67,7 @@ class ConflationCalculatorByExecutionTraces( } private fun isOversizedBlockOnTopOfNonEmptyConflation( - countersAfterConflation: TracesCounters + countersAfterConflation: TracesCounters, ): Boolean { return !countersAfterConflation.allTracesWithinLimits(tracesCountersLimit) && inprogressTracesCounters != emptyTracesCounters @@ -82,7 +82,7 @@ class ConflationCalculatorByExecutionTraces( } override fun copyCountersTo( - counters: ConflationCounters + counters: ConflationCounters, ) { counters.tracesCounters = inprogressTracesCounters } @@ -93,7 +93,7 @@ class ConflationCalculatorByExecutionTraces( val errorMessage = overSizeTraces.joinToString( separator = ", ", prefix = "oversized block: block=$blockNumber, oversize traces TRACE(count, limit, overflow): [", - postfix = "]" + postfix = "]", ) { (moduleName, count, limit) -> "$moduleName($count, $limit, ${count - limit})" } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbers.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbers.kt index 058c6357..0b94a36f 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbers.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbers.kt @@ -4,7 +4,7 @@ import net.consensys.zkevm.domain.BlockCounters import net.consensys.zkevm.domain.ConflationTrigger class ConflationCalculatorByTargetBlockNumbers( - private val targetEndBlockNumbers: Set + private val targetEndBlockNumbers: Set, ) : ConflationCalculator { override val id: String = ConflationTrigger.TARGET_BLOCK_NUMBER.name diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadline.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadline.kt index 3101b2dc..01d0ee0d 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadline.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadline.kt @@ -17,7 +17,7 @@ import kotlin.time.Duration.Companion.seconds class DeadlineConflationCalculatorRunner( private val conflationDeadlineCheckInterval: Duration, - private val delegate: ConflationCalculatorByTimeDeadline + private val delegate: ConflationCalculatorByTimeDeadline, ) : DeferredTriggerConflationCalculator by delegate, LongRunningService { private lateinit var timerInstance: Timer @@ -27,7 +27,7 @@ class DeadlineConflationCalculatorRunner( timerInstance = timer( name = "conflation-deadline-checker", initialDelay = conflationDeadlineCheckInterval.inWholeMilliseconds, - period = conflationDeadlineCheckInterval.inWholeMilliseconds + period = conflationDeadlineCheckInterval.inWholeMilliseconds, ) { delegate.checkConflationDeadline() } @@ -49,14 +49,14 @@ class ConflationCalculatorByTimeDeadline( private var lastBlockNumber: ULong, private val clock: Clock = Clock.System, private val latestBlockProvider: SafeBlockProvider, - val log: Logger = LogManager.getLogger(ConflationCalculatorByTimeDeadline::class.java) + val log: Logger = LogManager.getLogger(ConflationCalculatorByTimeDeadline::class.java), ) : DeferredTriggerConflationCalculator { data class Config( val conflationDeadline: Duration, // this is to avoid triggering conflation on the last block while new is being created // which is a false positive, network has activity. // it should be 2*blocktime - val conflationDeadlineLastBlockConfirmationDelay: Duration + val conflationDeadlineLastBlockConfirmationDelay: Duration, ) override val id: String = ConflationTrigger.TIME_LIMIT.name @@ -70,7 +70,7 @@ class ConflationCalculatorByTimeDeadline( "Checking conflation deadline: startBlockTime={} timeElapsed={} deadline={}", startBlockTimestamp, startBlockTimestamp?.let { now.minus(it) } ?: 0.seconds, - config.conflationDeadline + config.conflationDeadline, ) val deadlineReachedForFirstBlockInProgress = @@ -99,7 +99,7 @@ class ConflationCalculatorByTimeDeadline( log.warn( "SafeBlock request failed. Will Retry conflation deadline on next tick errorMessage={}", th.message, - th + th, ) } } @@ -120,7 +120,7 @@ class ConflationCalculatorByTimeDeadline( } override fun copyCountersTo( - counters: ConflationCounters + counters: ConflationCounters, ) { // nothing to do here } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorInterfaces.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorInterfaces.kt index b4c7ad75..7d0eddda 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorInterfaces.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorInterfaces.kt @@ -7,7 +7,7 @@ import net.consensys.zkevm.domain.ConflationTrigger data class ConflationCounters( var dataSize: UInt = 0u, var blockCount: UInt = 0u, - var tracesCounters: TracesCounters + var tracesCounters: TracesCounters, ) { companion object { internal fun empty(emptyTracesCounters: TracesCounters): ConflationCounters { @@ -20,7 +20,7 @@ interface ConflationCalculator { val id: String data class OverflowTrigger( val trigger: ConflationTrigger, - val singleBlockOverSized: Boolean + val singleBlockOverSized: Boolean, ) /** diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImpl.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImpl.kt index ed70033d..b1bab193 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImpl.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImpl.kt @@ -14,7 +14,7 @@ import java.util.concurrent.TimeUnit class ConflationServiceImpl( private val calculator: TracesConflationCalculator, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ) : ConflationService { private val log: Logger = LogManager.getLogger(this::class.java) @@ -23,7 +23,7 @@ class ConflationServiceImpl( data class PayloadAndBlockCounters( val block: Block, - val blockCounters: BlockCounters + val blockCounters: BlockCounters, ) : Comparable { override fun compareTo(other: PayloadAndBlockCounters): Int { return this.block.number.compareTo(other.block.number) @@ -35,12 +35,12 @@ class ConflationServiceImpl( private val blocksCounter = metricsFacade.createCounter( category = LineaMetricsCategory.CONFLATION, name = "blocks.imported", - description = "New blocks arriving to conflation service counter" + description = "New blocks arriving to conflation service counter", ) private val batchSizeInBlocksHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.CONFLATION, name = "blocks.size", - description = "Number of blocks in each conflated batch" + description = "Number of blocks in each conflated batch", ) init { @@ -48,13 +48,13 @@ class ConflationServiceImpl( category = LineaMetricsCategory.CONFLATION, name = "inprogress.blocks", description = "Number of blocks in progress of conflation", - measurementSupplier = { blocksInProgress.size } + measurementSupplier = { blocksInProgress.size }, ) metricsFacade.createGauge( category = LineaMetricsCategory.CONFLATION, name = "queue.size", description = "Number of blocks in conflation queue", - measurementSupplier = { blocksToConflate.size } + measurementSupplier = { blocksToConflate.size }, ) calculator.onConflatedBatch(this::handleConflation) } @@ -66,7 +66,7 @@ class ConflationServiceImpl( conflation.intervalString(), conflation.conflationTrigger, conflation.tracesCounters, - conflation.blocksRange.joinToString(",", "[", "]") { it.toString() } + conflation.blocksRange.joinToString(",", "[", "]") { it.toString() }, ) batchSizeInBlocksHistogram.record(conflation.blocksRange.count().toDouble()) @@ -82,7 +82,7 @@ class ConflationServiceImpl( "Conflation listener failed: batch={} errorMessage={}", conflation.intervalString(), th.message, - th + th, ) } } @@ -98,7 +98,7 @@ class ConflationServiceImpl( block.number, calculator.lastBlockNumber, blocksToConflate.size, - blocksInProgress.size + blocksInProgress.size, ) blocksToConflate.add(PayloadAndBlockCounters(block, blockCounters)) blocksInProgress.add(block) @@ -114,7 +114,7 @@ class ConflationServiceImpl( nextAvailableBlock = blocksToConflate.poll(100, TimeUnit.MILLISECONDS) log.trace( "block {} removed from conflation queue and sent to calculator", - nextAvailableBlock?.block?.number + nextAvailableBlock?.block?.number, ) calculator.newBlock(nextAvailableBlock.blockCounters) nextBlockNumberToConflate = nextAvailableBlock.block.number + 1u diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculator.kt index 192c09bd..478445d2 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculator.kt @@ -25,7 +25,7 @@ class GlobalBlobAwareConflationCalculator( private val blobCalculator: ConflationCalculatorByDataCompressed, private val batchesLimit: UInt, private val metricsFacade: MetricsFacade, - private val log: Logger = LogManager.getLogger(GlobalBlobAwareConflationCalculator::class.java) + private val log: Logger = LogManager.getLogger(GlobalBlobAwareConflationCalculator::class.java), ) : TracesConflationCalculator { private var conflationHandler: (ConflationCalculationResult) -> SafeFuture<*> = NOOP_CONSUMER private var blobHandler: BlobCreationHandler = NOOP_BLOB_HANDLER @@ -38,42 +38,42 @@ class GlobalBlobAwareConflationCalculator( private val gasUsedInBlobHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "gas", - description = "Total gas in each blob" + description = "Total gas in each blob", ) private val compressedDataSizeInBlobHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "compressed.data.size", - description = "Compressed L2 data size in bytes of each blob" + description = "Compressed L2 data size in bytes of each blob", ) private val uncompressedDataSizeInBlobHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BLOB, name = "uncompressed.data.size", - description = "Uncompressed L2 data size in bytes of each blob" + description = "Uncompressed L2 data size in bytes of each blob", ) private val gasUsedInBatchHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BATCH, name = "gas", - description = "Total gas in each batch" + description = "Total gas in each batch", ) private val compressedDataSizeInBatchHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BATCH, name = "compressed.data.size", - description = "Compressed L2 data size in bytes of each batch" + description = "Compressed L2 data size in bytes of each batch", ) private val uncompressedDataSizeInBatchHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BATCH, name = "uncompressed.data.size", - description = "Uncompressed L2 data size in bytes of each batch" + description = "Uncompressed L2 data size in bytes of each batch", ) private val avgCompressedTxDataSizeInBatchHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BATCH, name = "avg.compressed.tx.data.size", - description = "Average compressed transaction data size in bytes of each batch" + description = "Average compressed transaction data size in bytes of each batch", ) private val avgUncompressedTxDataSizeInBatchHistogram = metricsFacade.createHistogram( category = LineaMetricsCategory.BATCH, name = "avg.uncompressed.tx.data.size", - description = "Average uncompressed transaction data size in bytes of each batch" + description = "Average uncompressed transaction data size in bytes of each batch", ) init { @@ -96,14 +96,14 @@ class GlobalBlobAwareConflationCalculator( uncompressedDataSizeInBatch.div(numOfTransactionsInBatch.toInt()).toDouble() } else { 0.0 - } + }, ) avgCompressedTxDataSizeInBatchHistogram.record( if (numOfTransactionsInBatch > 0U) { compressedDataSizeInBatch.toInt().div(numOfTransactionsInBatch.toInt()).toDouble() } else { 0.0 - } + }, ) }.onFailure { log.error("Error when recording batch metrics: errorMessage={}", it.message) @@ -115,10 +115,10 @@ class GlobalBlobAwareConflationCalculator( val filteredBlockCounters = blobBlockCounters .filter { blobInterval.blocksRange.contains(it.blockNumber) } gasUsedInBlobHistogram.record( - filteredBlockCounters.sumOf { it.gasUsed }.toDouble() + filteredBlockCounters.sumOf { it.gasUsed }.toDouble(), ) uncompressedDataSizeInBlobHistogram.record( - filteredBlockCounters.sumOf { it.blockRLPEncoded.size }.toDouble() + filteredBlockCounters.sumOf { it.blockRLPEncoded.size }.toDouble(), ) compressedDataSizeInBlobHistogram.record(blobCompressedDataSize.toDouble()) }.onFailure { @@ -162,7 +162,7 @@ class GlobalBlobAwareConflationCalculator( val compressedData = blobCalculator.getCompressedData() val blobInterval = BlockInterval( blobBatches.first().startBlockNumber, - blobBatches.last().endBlockNumber + blobBatches.last().endBlockNumber, ) val blob = Blob( conflations = blobBatches, @@ -170,7 +170,7 @@ class GlobalBlobAwareConflationCalculator( startBlockTime = blobBlockCounters .find { it.blockNumber == blobInterval.startBlockNumber }!!.blockTimestamp, endBlockTime = blobBlockCounters - .find { it.blockNumber == blobInterval.endBlockNumber }!!.blockTimestamp + .find { it.blockNumber == blobInterval.endBlockNumber }!!.blockTimestamp, ) log.info( "new blob: blob={} trigger={} blobSizeBytes={} blobBatchesCount={} blobBatchesLimit={} blobBatchesList={}", @@ -179,7 +179,7 @@ class GlobalBlobAwareConflationCalculator( compressedData.size, blobBatches.size, batchesLimit, - blobBatches.toBlockIntervalsString() + blobBatches.toBlockIntervalsString(), ) blobHandler.handleBlob(blob) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculator.kt index 42b0467a..409b685e 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculator.kt @@ -15,7 +15,7 @@ internal val NOOP_CONSUMER: (ConflationCalculationResult) -> SafeFuture<*> = internal data class InflightConflation( var startBlockNumber: ULong?, - var counters: ConflationCounters + var counters: ConflationCounters, ) { fun toConflationResult(endBlockNumber: ULong, trigger: ConflationTrigger): ConflationCalculationResult { @@ -23,7 +23,7 @@ internal data class InflightConflation( startBlockNumber = startBlockNumber!!, endBlockNumber = endBlockNumber, conflationTrigger = trigger, - tracesCounters = counters.tracesCounters + tracesCounters = counters.tracesCounters, ) } @@ -31,7 +31,7 @@ internal data class InflightConflation( fun empty(emptyTracesCounters: TracesCounters): InflightConflation { return InflightConflation( startBlockNumber = null, - counters = ConflationCounters.empty(emptyTracesCounters) + counters = ConflationCounters.empty(emptyTracesCounters), ) } } @@ -42,7 +42,7 @@ class GlobalBlockConflationCalculator( syncCalculators: List, deferredTriggerConflationCalculators: List, private val emptyTracesCounters: TracesCounters, - private val log: Logger = LogManager.getLogger(GlobalBlockConflationCalculator::class.java) + private val log: Logger = LogManager.getLogger(GlobalBlockConflationCalculator::class.java), ) : TracesConflationCalculator, ConflationTriggerConsumer { private var conflationConsumer: (ConflationCalculationResult) -> SafeFuture<*> = NOOP_CONSUMER private var inflightConflation: InflightConflation = InflightConflation.empty(emptyTracesCounters) @@ -71,7 +71,7 @@ class GlobalBlockConflationCalculator( "conflatingBlock: blockNumber={} startBlockNumber={} accCounters={}", blockCounters.blockNumber, inflightConflation.startBlockNumber, - inflightConflation.counters + inflightConflation.counters, ) val triggers = calculators.mapNotNull { val overflowTrigger = it.checkOverflow(blockCounters) @@ -104,7 +104,7 @@ class GlobalBlockConflationCalculator( "conflatingBlock FINISH: blockNumber={} startBlockNumber={} accCounters={}", blockCounters.blockNumber, inflightConflation.startBlockNumber, - inflightConflation.counters + inflightConflation.counters, ) } @@ -112,7 +112,7 @@ class GlobalBlockConflationCalculator( calculators.forEach { it.copyCountersTo(inflightConflation.counters) } val conflationResult = inflightConflation.toConflationResult( endBlockNumber = endBlockNumber, - trigger = conflationTrigger + trigger = conflationTrigger, ) log.trace("conflationTrigger: trigger=$conflationTrigger, result=$conflationResult") conflationConsumer.invoke(conflationResult) @@ -149,7 +149,7 @@ class GlobalBlockConflationCalculator( private fun ensureBlockIsInOrder(blockNumber: ULong) { if (blockNumber != (lastBlockNumber + 1u)) { val error = IllegalArgumentException( - "Blocks to conflate must be sequential: lastBlockNumber=$lastBlockNumber, new blockNumber=$blockNumber" + "Blocks to conflate must be sequential: lastBlockNumber=$lastBlockNumber, new blockNumber=$blockNumber", ) log.error(error.message) throw error diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImpl.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImpl.kt index a82b2821..0f4fc5a6 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImpl.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImpl.kt @@ -22,12 +22,12 @@ class ProofGeneratingConflationHandlerImpl( private val zkProofProductionCoordinator: ZkProofCreationCoordinator, private val batchProofHandler: BatchProofHandler, private val vertx: Vertx, - private val config: Config + private val config: Config, ) : ConflationHandler { private val log: Logger = LogManager.getLogger(this::class.java) data class Config( - val conflationAndProofGenerationRetryInterval: Duration + val conflationAndProofGenerationRetryInterval: Duration, ) override fun handleConflatedBatch(conflation: BlocksConflation): SafeFuture<*> { @@ -37,7 +37,7 @@ class ProofGeneratingConflationHandlerImpl( "new batch: batch={} trigger={} tracesCounters={}", blockIntervalString, conflation.conflationResult.conflationTrigger, - conflation.conflationResult.tracesCounters + conflation.conflationResult.tracesCounters, ) AsyncRetryer.retry( vertx = vertx, @@ -47,9 +47,9 @@ class ProofGeneratingConflationHandlerImpl( log.warn( "conflation and proof creation flow failed batch={} errorMessage={}", blockIntervalString, - it.message + it.message, ) - } + }, ) { conflationToProofCreation(conflation) } @@ -59,7 +59,7 @@ class ProofGeneratingConflationHandlerImpl( "traces conflation or proof request failed: batch={} errorMessage={}", blockIntervalString, th.message, - th + th, ) } } @@ -75,14 +75,14 @@ class ProofGeneratingConflationHandlerImpl( "traces conflation failed: batch={} errorMessage={}", conflation.conflationResult.intervalString(), th.message, - th + th, ) } .thenCompose { blocksTracesConflated: BlocksTracesConflated -> log.debug( "requesting execution proof: batch={} tracesFile={}", blockIntervalString, - blocksTracesConflated.tracesResponse.tracesFileName + blocksTracesConflated.tracesResponse.tracesFileName, ) zkProofProductionCoordinator .createZkProof(conflation, blocksTracesConflated) @@ -94,7 +94,7 @@ class ProofGeneratingConflationHandlerImpl( "execution proof failure: batch={} errorMessage={}", blockIntervalString, th.message, - th + th, ) } } @@ -104,7 +104,7 @@ class ProofGeneratingConflationHandlerImpl( } internal fun assertConsecutiveBlocksRange( - blocks: List + blocks: List, ): Result { if (blocks.isEmpty()) { return Err(IllegalArgumentException("Empty list of blocks")) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinator.kt index f4971a04..a59418d0 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinator.kt @@ -6,11 +6,11 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture data class BlocksTracesConflated( val tracesResponse: GenerateTracesResponse, - val zkStateTraces: GetZkEVMStateMerkleProofResponse + val zkStateTraces: GetZkEVMStateMerkleProofResponse, ) interface TracesConflationCoordinator { fun conflateExecutionTraces( - blockRange: ULongRange + blockRange: ULongRange, ): SafeFuture } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinatorImpl.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinatorImpl.kt index b3e085c3..a6f9a8cd 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinatorImpl.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/TracesConflationCoordinatorImpl.kt @@ -16,39 +16,39 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class TracesConflationCoordinatorImpl( private val tracesConflationClient: TracesConflationClientV2, - private val zkStateClient: StateManagerClientV1 + private val zkStateClient: StateManagerClientV1, ) : TracesConflationCoordinator { private val log: Logger = LogManager.getLogger(this::class.java) private fun requestConflatedTraces( - blockRange: ULongRange + blockRange: ULongRange, ): SafeFuture { return tracesConflationClient .generateConflatedTracesToFile( startBlockNumber = blockRange.first(), - endBlockNumber = blockRange.last() + endBlockNumber = blockRange.last(), ) - .thenCompose { result: Result> + .thenCompose { result: Result>, -> result.mapBoth( { SafeFuture.completedFuture(it) }, { log.error("Conflation service returned error: errorMessage={}", it.message, it) SafeFuture.failedFuture(it.asException("Conflation service error")) - } + }, ) } } private fun requestStateMerkleProof( - blockRange: ULongRange + blockRange: ULongRange, ): SafeFuture { return zkStateClient.makeRequest( - GetStateMerkleProofRequest(BlockInterval(blockRange.first(), blockRange.last())) + GetStateMerkleProofRequest(BlockInterval(blockRange.first(), blockRange.last())), ) } override fun conflateExecutionTraces( - blockRange: ULongRange + blockRange: ULongRange, ): SafeFuture { return requestConflatedTraces(blockRange).thenCompose { tracesConflationResult: GenerateTracesResponse -> // these 2 requests can be done in parallel, but traces-api is much slower to respond so diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinator.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinator.kt index f4ca215e..f68ee697 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinator.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinator.kt @@ -8,6 +8,6 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface ZkProofCreationCoordinator { fun createZkProof( blocksConflation: BlocksConflation, - traces: BlocksTracesConflated + traces: BlocksTracesConflated, ): SafeFuture } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImpl.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImpl.kt index aa86fc96..0588c5fb 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImpl.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImpl.kt @@ -18,13 +18,13 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class ZkProofCreationCoordinatorImpl( private val executionProverClient: ExecutionProverClientV2, private val messageServiceAddress: String, - private val l2EthApiClient: EthApiClient + private val l2EthApiClient: EthApiClient, ) : ZkProofCreationCoordinator { private val log: Logger = LogManager.getLogger(this::class.java) private val messageEventsTopics: List = listOf( MessageSentEvent.topic, L1L2MessageHashesAddedToInboxEvent.topic, - L2RollingHashUpdatedEvent.topic + L2RollingHashUpdatedEvent.topic, ) private fun getBlockStateRootHash(blockNumber: ULong): SafeFuture { @@ -40,7 +40,7 @@ class ZkProofCreationCoordinatorImpl( fromBlock = blockNumber.toBlockParameter(), toBlock = blockNumber.toBlockParameter(), address = messageServiceAddress, - topics = listOf(messageEventTopic) + topics = listOf(messageEventTopic), ) }.let { SafeFuture.collectAll(it.stream()).thenApply { it.flatten() } @@ -49,7 +49,7 @@ class ZkProofCreationCoordinatorImpl( override fun createZkProof( blocksConflation: BlocksConflation, - traces: BlocksTracesConflated + traces: BlocksTracesConflated, ): SafeFuture { val startBlockNumber = blocksConflation.blocks.first().number val endBlockNumber = blocksConflation.blocks.last().number @@ -68,12 +68,12 @@ class ZkProofCreationCoordinatorImpl( bridgeLogs = bridgeLogsList.flatten(), tracesResponse = traces.tracesResponse, type2StateData = traces.zkStateTraces, - keccakParentStateRootHash = previousKeccakStateRootHash - ) + keccakParentStateRootHash = previousKeccakStateRootHash, + ), ).thenApply { Batch( startBlockNumber = startBlockNumber, - endBlockNumber = endBlockNumber + endBlockNumber = endBlockNumber, ) }.whenException { log.error("Prover returned for batch={} errorMessage={}", blocksConflationInterval, it.message, it) diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitor.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitor.kt index 608be272..bfc9b0f9 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitor.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitor.kt @@ -7,7 +7,7 @@ interface FinalizationMonitor { data class FinalizationUpdate( val blockNumber: ULong, val zkStateRootHash: Bytes32, - val blockHash: Bytes32 + val blockHash: Bytes32, ) fun getLastFinalizationUpdate(): FinalizationUpdate diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/AggregationsRepository.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/AggregationsRepository.kt index 4bd37f34..a21e7db1 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/AggregationsRepository.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/AggregationsRepository.kt @@ -23,7 +23,7 @@ interface AggregationsRepository { * * Not sure yet about blockMetaData, we'll revisit it later */ fun findConsecutiveProvenBlobs( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture> fun saveNewAggregation(aggregation: Aggregation): SafeFuture @@ -31,15 +31,15 @@ interface AggregationsRepository { fun getProofsToFinalize( fromBlockNumber: Long, finalEndBlockCreatedBefore: Instant, - maximumNumberOfProofs: Int + maximumNumberOfProofs: Int, ): SafeFuture> fun findHighestConsecutiveEndBlockNumber( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findAggregationProofByEndBlockNumber( - endBlockNumber: Long + endBlockNumber: Long, ): SafeFuture fun deleteAggregationsUpToEndBlockNumber(endBlockNumberInclusive: Long): SafeFuture diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BatchesRepository.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BatchesRepository.kt index 223da0f7..12f14a52 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BatchesRepository.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BatchesRepository.kt @@ -7,14 +7,14 @@ interface BatchesRepository { fun saveNewBatch(batch: Batch): SafeFuture fun findHighestConsecutiveEndBlockNumberFromBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture fun deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive: Long + endBlockNumberInclusive: Long, ): SafeFuture fun deleteBatchesAfterBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture } diff --git a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BlobsRepository.kt b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BlobsRepository.kt index 7f18f6e6..65cd4313 100644 --- a/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BlobsRepository.kt +++ b/coordinator/core/src/main/kotlin/net/consensys/zkevm/persistence/BlobsRepository.kt @@ -9,19 +9,19 @@ interface BlobsRepository { fun getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive: Long, - endBlockCreatedBefore: Instant + endBlockCreatedBefore: Instant, ): SafeFuture> fun findBlobByStartBlockNumber( - startBlockNumber: Long + startBlockNumber: Long, ): SafeFuture fun findBlobByEndBlockNumber( - endBlockNumber: Long + endBlockNumber: Long, ): SafeFuture fun deleteBlobsUpToEndBlockNumber( - endBlockNumberInclusive: ULong + endBlockNumberInclusive: ULong, ): SafeFuture fun deleteBlobsAfterBlockNumber(startingBlockNumberInclusive: ULong): SafeFuture diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/FakeBlobCompressorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/FakeBlobCompressorTest.kt index fcc3d527..2c0d2298 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/FakeBlobCompressorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/FakeBlobCompressorTest.kt @@ -57,24 +57,24 @@ class FakeBlobCompressorTest { BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 0, - compressedSizeAfter = 33 - ) + compressedSizeAfter = 33, + ), ) assertThat(compressor.appendBlock(block2)).isEqualTo( BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 33, - compressedSizeAfter = 77 - ) + compressedSizeAfter = 77, + ), ) val block3 = ByteArray(31) assertThat(compressor.appendBlock(block3)).isEqualTo( BlobCompressor.AppendResult( blockAppended = false, compressedSizeBefore = 77, - compressedSizeAfter = 111 - ) + compressedSizeAfter = 111, + ), ) } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedBlobCompressorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedBlobCompressorTest.kt index 41e9418c..8a9c0d64 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedBlobCompressorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedBlobCompressorTest.kt @@ -25,7 +25,7 @@ class GoBackedBlobCompressorTest { private val compressor = GoBackedBlobCompressor.getInstance( BlobCompressorVersion.V1_2, DATA_LIMIT.toUInt(), - metricsFacade + metricsFacade, ) private fun loadTestData(): Array { val data = GoBackedBlobCompressorTest::class.java.getResourceAsStream("rlp_blocks.bin")!!.readAllBytes() diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedCalculateShnarfCalculatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedCalculateShnarfCalculatorTest.kt index ab80d1cd..74ea92af 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedCalculateShnarfCalculatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/coordination/blob/GoBackedCalculateShnarfCalculatorTest.kt @@ -41,7 +41,7 @@ class GoBackedCalculateShnarfCalculatorTest { expectedX = Bytes32.random().toArray().encodeHex(), expectedY = Bytes32.random().toArray().encodeHex(), expectedShnarf = Bytes32.random().toArray().encodeHex(), - errorMessage = "" + errorMessage = "", ) private val expectedShnarfParsedResult = ShnarfResult( dataHash = fakeCalculationResult.dataHash.decodeHex(), @@ -51,7 +51,7 @@ class GoBackedCalculateShnarfCalculatorTest { expectedShnarf = fakeCalculationResult.expectedShnarf.decodeHex(), commitment = fakeCalculationResult.commitment.decodeHex(), kzgProofSideCar = fakeCalculationResult.kzgProofSideCar.decodeHex(), - kzgProofContract = fakeCalculationResult.kzgProofContract.decodeHex() + kzgProofContract = fakeCalculationResult.kzgProofContract.decodeHex(), ) @BeforeEach @@ -70,7 +70,7 @@ class GoBackedCalculateShnarfCalculatorTest { parentStateRootHash = parentStateRootHash, finalStateRootHash = finalStateRootHash, prevShnarf = prevShnarf, - conflationOrder = BlockIntervals(1UL, listOf(5UL, 10UL)) + conflationOrder = BlockIntervals(1UL, listOf(5UL, 10UL)), ) verify(delegate).CalculateShnarf( @@ -81,7 +81,7 @@ class GoBackedCalculateShnarfCalculatorTest { eq(prevShnarf.encodeHex()), eq(1L), eq(2), - eq(longArrayOf(5L, 10L)) + eq(longArrayOf(5L, 10L)), ) assertThat(result).isEqualTo(expectedShnarfParsedResult) } @@ -96,7 +96,7 @@ class GoBackedCalculateShnarfCalculatorTest { parentStateRootHash = parentStateRootHash, finalStateRootHash = finalStateRootHash, prevShnarf = prevShnarf, - conflationOrder = BlockIntervals(Long.MAX_VALUE.toULong(), listOf(5UL, Long.MAX_VALUE.toULong())) + conflationOrder = BlockIntervals(Long.MAX_VALUE.toULong(), listOf(5UL, Long.MAX_VALUE.toULong())), ) verify(delegate).CalculateShnarf( @@ -107,7 +107,7 @@ class GoBackedCalculateShnarfCalculatorTest { eq(prevShnarf.encodeHex()), eq(Long.MAX_VALUE), eq(2), - eq(longArrayOf(5L, Long.MAX_VALUE)) + eq(longArrayOf(5L, Long.MAX_VALUE)), ) assertThat(result).isEqualTo(expectedShnarfParsedResult) @@ -125,7 +125,7 @@ class GoBackedCalculateShnarfCalculatorTest { parentStateRootHash = ByteArray(0), finalStateRootHash = ByteArray(0), prevShnarf = ByteArray(0), - conflationOrder = BlockIntervals(0UL, listOf(0UL)) + conflationOrder = BlockIntervals(0UL, listOf(0UL)), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcherTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcherTest.kt index 431303ad..b3f55692 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcherTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/EventDispatcherTest.kt @@ -28,7 +28,7 @@ class EventDispatcherTest { } to "Consumer error", Consumer { atomicInteger -> atomicInteger.incrementAndGet() - } to "Consumer counter 2" + } to "Consumer counter 2", ) val eventDispatcher = EventDispatcher(mappedConsumers) @@ -50,7 +50,7 @@ class EventDispatcherTest { val mappedConsumers: Map, String> = mapOf( Consumer { throw RuntimeException(exceptionMessage) - } to consumerName + } to consumerName, ) val log = Mockito.spy(LogManager.getLogger(EventDispatcher::class.java)) @@ -66,7 +66,7 @@ class EventDispatcherTest { eq(consumerName), eq(event), eq(exceptionMessage), - any() + any(), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadlineTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadlineTest.kt index 0fc632ef..c2d408ec 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadlineTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByDeadlineTest.kt @@ -37,9 +37,9 @@ class AggregationTriggerCalculatorByDeadlineTest { BlockHeaderSummary( number = latestBlockNumber, hash = ByteArrayExt.random32(), - timestamp = latestBlockTimestamp - ) - ) + timestamp = latestBlockTimestamp, + ), + ), ) val deadlineTriggered = SafeFuture() @@ -55,7 +55,7 @@ class AggregationTriggerCalculatorByDeadlineTest { val aggregationTriggerByDeadline = AggregationTriggerCalculatorByDeadline( AggregationTriggerCalculatorByDeadline.Config(aggregationDeadline, aggregationDeadlineDelay), mockClock, - mockLatestSafeBlockProvider + mockLatestSafeBlockProvider, ) aggregationTriggerByDeadline.onAggregationTrigger(aggregationTriggerTypeHandler) @@ -71,8 +71,8 @@ class AggregationTriggerCalculatorByDeadlineTest { endBlockNumber = blobEndBlockNumber, startBlockTimestamp = blobStartBlockTimeStamp, endBlockTimestamp = blobEndBlockTimeStamp, - expectedShnarf = Random.nextBytes(32) - ) + expectedShnarf = Random.nextBytes(32), + ), ) val time1 = blobEndBlockTimeStamp.plus(1.milliseconds) // 491 @@ -126,7 +126,7 @@ class AggregationTriggerCalculatorByDeadlineTest { val aggregationTriggerByDeadline = AggregationTriggerCalculatorByDeadline( AggregationTriggerCalculatorByDeadline.Config(deadline, aggregationDeadlineDelay), mockClock, - mockLatestSafeBlockProvider + mockLatestSafeBlockProvider, ) aggregationTriggerByDeadline.onAggregationTrigger(aggregationTriggerTypeHandler) @@ -144,13 +144,13 @@ class AggregationTriggerCalculatorByDeadlineTest { endBlockNumber = 15u, startBlockTimestamp = firstBloblStartBlockTimeStamp, endBlockTimestamp = firstBlobEndBlockTimeStamp, - expectedShnarf = Random.nextBytes(32) - ) + expectedShnarf = Random.nextBytes(32), + ), ) whenever(mockClock.now()).thenReturn( firstBlobEndBlockTimeStamp - .plus(1.milliseconds) + .plus(1.milliseconds), ) aggregationTriggerByDeadline.checkAggregation().get() assertThat(deadlineTriggered).isNotCompleted @@ -176,8 +176,8 @@ class AggregationTriggerCalculatorByDeadlineTest { endBlockNumber = blobEndBlockNumber, startBlockTimestamp = secondBlobStartBlockTimestamp, endBlockTimestamp = secondBlobEndBlockTimestamp, - expectedShnarf = Random.nextBytes(32) - ) + expectedShnarf = Random.nextBytes(32), + ), ) whenever(mockLatestSafeBlockProvider.getLatestSafeBlockHeader()) .thenReturn( @@ -185,9 +185,9 @@ class AggregationTriggerCalculatorByDeadlineTest { BlockHeaderSummary( number = 15u, hash = ByteArrayExt.random32(), - timestamp = firstBlobEndBlockTimeStamp - ) - ) + timestamp = firstBlobEndBlockTimeStamp, + ), + ), ) whenever(mockClock.now()).thenReturn(secondBlobStartBlockTimestamp.plus(deadline).plus(1.milliseconds)) aggregationTriggerByDeadline.checkAggregation().get() @@ -218,9 +218,9 @@ class AggregationTriggerCalculatorByDeadlineTest { BlockHeaderSummary( number = latestBlockNumber, hash = ByteArrayExt.random32(), - timestamp = latestBlockTimestamp - ) - ) + timestamp = latestBlockTimestamp, + ), + ), ) val deadlineTriggered = SafeFuture() @@ -236,7 +236,7 @@ class AggregationTriggerCalculatorByDeadlineTest { val aggregationTriggerByDeadline = AggregationTriggerCalculatorByDeadline( AggregationTriggerCalculatorByDeadline.Config(aggregationDeadline, aggregationDeadlineDelay), mockClock, - mockLatestSafeBlockProvider + mockLatestSafeBlockProvider, ) aggregationTriggerByDeadline.onAggregationTrigger(aggregationTriggerTypeHandler) @@ -252,8 +252,8 @@ class AggregationTriggerCalculatorByDeadlineTest { endBlockNumber = blobEndBlockNumber, startBlockTimestamp = blobStartBlockTimeStamp, endBlockTimestamp = blobEndBlockTimeStamp, - expectedShnarf = Random.nextBytes(32) - ) + expectedShnarf = Random.nextBytes(32), + ), ) val time1 = blobEndBlockTimeStamp.plus(1.milliseconds) // 491 @@ -293,8 +293,8 @@ class AggregationTriggerCalculatorByDeadlineTest { endBlockNumber = latestBlockNumber, startBlockTimestamp = latestBlockTimestamp, endBlockTimestamp = latestBlockTimestamp, - expectedShnarf = Random.nextBytes(32) - ) + expectedShnarf = Random.nextBytes(32), + ), ) val time4 = time3.plus(10.milliseconds) // 611 whenever(mockClock.now()).thenReturn(time4) diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimitTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimitTest.kt index 5fe2953a..5248a919 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimitTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByProofLimitTest.kt @@ -19,7 +19,7 @@ class AggregationTriggerCalculatorByProofLimitTest { numberOfBatches = batchesCount, startBlockTimestamp = Instant.fromEpochMilliseconds((startBlockNumber * 100uL).toLong()), endBlockTimestamp = Instant.fromEpochMilliseconds((endBlockNumber * 100uL).toLong()), - expectedShnarf = Random.nextBytes(32) + expectedShnarf = Random.nextBytes(32), ) } @@ -49,8 +49,8 @@ class AggregationTriggerCalculatorByProofLimitTest { .isEqualTo( AggregationTrigger( aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, - aggregation = BlobsToAggregate(blobCounters.first().startBlockNumber, blobCounters.last().endBlockNumber) - ) + aggregation = BlobsToAggregate(blobCounters.first().startBlockNumber, blobCounters.last().endBlockNumber), + ), ) } @@ -82,9 +82,9 @@ class AggregationTriggerCalculatorByProofLimitTest { aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, aggregation = BlobsToAggregate( blobCounters.first().startBlockNumber, - blobCounters[blobCounters.size - 2].endBlockNumber // Last blob [size-1] should not be included - ) - ) + blobCounters[blobCounters.size - 2].endBlockNumber, // Last blob [size-1] should not be included + ), + ), ) } @@ -129,9 +129,9 @@ class AggregationTriggerCalculatorByProofLimitTest { aggregationTriggerType = AggregationTriggerType.PROOF_LIMIT, aggregation = BlobsToAggregate( blobCountersAfterReset.first().startBlockNumber, - blobCountersAfterReset.last().endBlockNumber - ) - ) + blobCountersAfterReset.last().endBlockNumber, + ), + ), ) } @@ -169,8 +169,8 @@ class AggregationTriggerCalculatorByProofLimitTest { assertThat(aggregationTrigger1.aggregation).isEqualTo( BlobsToAggregate( blobCounters.first().startBlockNumber, - blobCounters[blobCounters.size - 2].endBlockNumber - ) + blobCounters[blobCounters.size - 2].endBlockNumber, + ), ) // Calculator should be reset after aggregation trigger @@ -190,8 +190,8 @@ class AggregationTriggerCalculatorByProofLimitTest { assertThat(aggregationTrigger2.aggregation).isEqualTo( BlobsToAggregate( aggregationTrigger1.aggregation.endBlockNumber + 1u, - blobCounters[blobCounters.size - 2].endBlockNumber - ) + blobCounters[blobCounters.size - 2].endBlockNumber, + ), ) // Calculator should be reset after aggregation trigger diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbersTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbersTest.kt index 51ba1fa5..b2d6703e 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbersTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/AggregationTriggerCalculatorByTargetBlockNumbersTest.kt @@ -18,7 +18,7 @@ class AggregationTriggerCalculatorByTargetBlockNumbersTest { log = mock() calculator = AggregationTriggerCalculatorByTargetBlockNumbers( targetEndBlockNumbers = listOf(10uL, 20uL, 30uL), - log = log + log = log, ) } @@ -59,8 +59,8 @@ class AggregationTriggerCalculatorByTargetBlockNumbersTest { .isEqualTo( AggregationTrigger( aggregationTriggerType = AggregationTriggerType.TARGET_BLOCK_NUMBER, - aggregation = BlobsToAggregate(15uL, 20uL) - ) + aggregation = BlobsToAggregate(15uL, 20uL), + ), ) } @@ -70,8 +70,8 @@ class AggregationTriggerCalculatorByTargetBlockNumbersTest { .isEqualTo( AggregationTrigger( aggregationTriggerType = AggregationTriggerType.TARGET_BLOCK_NUMBER, - aggregation = BlobsToAggregate(20uL, 20uL) - ) + aggregation = BlobsToAggregate(20uL, 20uL), + ), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculatorTest.kt index b5daed3f..9545893c 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/GlobalAggregationCalculatorTest.kt @@ -56,7 +56,7 @@ class GlobalAggregationCalculatorTest { targetBlockNumbers: List? = null, aggregationSizeMultipleOf: Int = 1, metricsFacade: MetricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), - aggregationHandler: AggregationHandler = AggregationHandler.NOOP_HANDLER + aggregationHandler: AggregationHandler = AggregationHandler.NOOP_HANDLER, ): GlobalAggregationCalculator { val syncAggregationTriggers = mutableListOf() .apply { @@ -71,10 +71,10 @@ class GlobalAggregationCalculatorTest { aggregationTriggerCalculatorByDeadline = AggregationTriggerCalculatorByDeadline( AggregationTriggerCalculatorByDeadline.Config( aggregationDeadline = aggregationDeadline, - aggregationDeadlineDelay = aggregationDeadlineDelay!! + aggregationDeadlineDelay = aggregationDeadlineDelay!!, ), fixedClock, - safeBlockProvider + safeBlockProvider, ) add(aggregationTriggerCalculatorByDeadline) } @@ -85,7 +85,7 @@ class GlobalAggregationCalculatorTest { syncAggregationTrigger = syncAggregationTriggers, deferredAggregationTrigger = deferredAggregationTriggers, metricsFacade = metricsFacade, - aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt() + aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt(), ).apply { onAggregation(aggregationHandler) } } private fun blobCounters( @@ -93,7 +93,7 @@ class GlobalAggregationCalculatorTest { endBlockNumber: ULong, numberOfBatches: UInt = 1u, startBlockTimestamp: Instant = fixedClock.now(), - endBlockTimestamp: Instant = fixedClock.now().plus(2.seconds.times((endBlockNumber - startBlockNumber).toInt())) + endBlockTimestamp: Instant = fixedClock.now().plus(2.seconds.times((endBlockNumber - startBlockNumber).toInt())), ): BlobCounters { return BlobCounters( numberOfBatches = numberOfBatches, @@ -101,7 +101,7 @@ class GlobalAggregationCalculatorTest { endBlockNumber = endBlockNumber, startBlockTimestamp = startBlockTimestamp, endBlockTimestamp = endBlockTimestamp, - expectedShnarf = Random.nextBytes(32) + expectedShnarf = Random.nextBytes(32), ) } @@ -112,9 +112,9 @@ class GlobalAggregationCalculatorTest { BlockHeaderSummary( number = blockNumber, timestamp = timestamp, - hash = ByteArrayExt.random32() - ) - ) + hash = ByteArrayExt.random32(), + ), + ), ) } @@ -128,8 +128,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 5u, startBlockNumber = 2u, - endBlockNumber = 10u - ) + endBlockNumber = 10u, + ), ) } .message() @@ -146,9 +146,9 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = maxProofsPerAggregation, startBlockNumber = 1u, - endBlockNumber = 10u + endBlockNumber = 10u, - ) + ), ) } assertThat(exception.message).contains(expectedErrorMessage) @@ -170,8 +170,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 5u, startBlockNumber = 1u, - endBlockNumber = 10u - ) + endBlockNumber = 10u, + ), ) // This blob with #proofs = proofLimit (15) will trigger aggregation 2 times, first for the previous blob and @@ -180,8 +180,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = proofLimit - 1u, startBlockNumber = 11u, - endBlockNumber = 30u - ) + endBlockNumber = 30u, + ), ) expectedAggregations.add(BlobsToAggregate(1u, 10u)) expectedAggregations.add(BlobsToAggregate(11u, 30u)) @@ -191,8 +191,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = proofLimit - 1u, startBlockNumber = 31u, - endBlockNumber = 45u - ) + endBlockNumber = 45u, + ), ) expectedAggregations.add(BlobsToAggregate(31u, 45u)) @@ -201,8 +201,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 4u, startBlockNumber = 46u, - endBlockNumber = 61u - ) + endBlockNumber = 61u, + ), ) // This blob with #proofs = 10 will trigger aggregation and will be included in aggregation along with previous @@ -211,8 +211,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 9u, startBlockNumber = 62u, - endBlockNumber = 70u - ) + endBlockNumber = 70u, + ), ) expectedAggregations.add(BlobsToAggregate(46u, 70u)) @@ -221,8 +221,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = proofLimit - 1u, startBlockNumber = 71u, - endBlockNumber = 85u - ) + endBlockNumber = 85u, + ), ) expectedAggregations.add(BlobsToAggregate(71u, 85u)) assertThat(actualAggregations).containsExactlyElementsOf(expectedAggregations) @@ -243,8 +243,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 5u, startBlockNumber = 1u, - endBlockNumber = 10u - ) + endBlockNumber = 10u, + ), ) // This blob with proof count 13 will trigger aggregation, but will not be included in any aggregation. @@ -253,8 +253,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 12u, startBlockNumber = 11u, - endBlockNumber = 30u - ) + endBlockNumber = 30u, + ), ) expectedAggregations.add(BlobsToAggregate(1u, 10u)) @@ -264,8 +264,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 9u, startBlockNumber = 31u, - endBlockNumber = 45u - ) + endBlockNumber = 45u, + ), ) expectedAggregations.add(BlobsToAggregate(11u, 30u)) @@ -275,8 +275,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 4u, startBlockNumber = 46u, - endBlockNumber = 61u - ) + endBlockNumber = 61u, + ), ) expectedAggregations.add(BlobsToAggregate(31u, 61u)) assertThat(actualAggregations).containsExactlyElementsOf(expectedAggregations) @@ -292,7 +292,7 @@ class GlobalAggregationCalculatorTest { aggregationCalculator( proofLimit = 1500u, aggregationDeadline = aggregationDeadline, - aggregationDeadlineDelay = aggregationDeadlineDelay + aggregationDeadlineDelay = aggregationDeadlineDelay, ) { blobsToAggregate -> aggregation = blobsToAggregate SafeFuture.completedFuture(Unit) @@ -303,7 +303,7 @@ class GlobalAggregationCalculatorTest { startBlockNumber = 1u, endBlockNumber = 10u, startBlockTimestamp = Instant.fromEpochMilliseconds(100), - endBlockTimestamp = Instant.fromEpochMilliseconds(130) + endBlockTimestamp = Instant.fromEpochMilliseconds(130), ) val blob2 = blobCounters( @@ -311,7 +311,7 @@ class GlobalAggregationCalculatorTest { startBlockNumber = blob1.endBlockNumber + 1uL, endBlockNumber = 30u, startBlockTimestamp = Instant.fromEpochMilliseconds(140), - endBlockTimestamp = Instant.fromEpochMilliseconds(250) + endBlockTimestamp = Instant.fromEpochMilliseconds(250), ) whenever(safeBlockProvider.getLatestSafeBlockHeader()) @@ -320,9 +320,9 @@ class GlobalAggregationCalculatorTest { BlockHeaderSummary( number = blob2.endBlockNumber, hash = ByteArrayExt.random32(), - timestamp = blob2.endBlockTimestamp - ) - ) + timestamp = blob2.endBlockTimestamp, + ), + ), ) val time1 = blob1.startBlockTimestamp.plus(aggregationDeadline).minus(1.milliseconds) @@ -347,7 +347,7 @@ class GlobalAggregationCalculatorTest { val testMeterRegistry = SimpleMeterRegistry() val globalAggregationCalculator = aggregationCalculator( proofLimit = 15u, - metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test") + metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test"), ) val pendingProofsGauge = testMeterRegistry.get("test.aggregation.proofs.ready").gauge() assertThat(pendingProofsGauge.value()).isEqualTo(0.0) @@ -359,8 +359,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 5u, startBlockNumber = 1u, - endBlockNumber = 10u - ) + endBlockNumber = 10u, + ), ) assertThat(pendingProofsGauge.value()).isEqualTo(6.0) @@ -368,8 +368,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 7u, startBlockNumber = 11u, - endBlockNumber = 30u - ) + endBlockNumber = 30u, + ), ) assertThat(pendingProofsGauge.value()).isEqualTo(14.0) @@ -378,8 +378,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 9u, startBlockNumber = 31u, - endBlockNumber = 45u - ) + endBlockNumber = 45u, + ), ) assertThat(pendingProofsGauge.value()).isEqualTo(10.0) @@ -387,8 +387,8 @@ class GlobalAggregationCalculatorTest { blobCounters( numberOfBatches = 4u, startBlockNumber = 46u, - endBlockNumber = 61u - ) + endBlockNumber = 61u, + ), ) assertThat(pendingProofsGauge.value()).isEqualTo(0.0) } @@ -399,7 +399,7 @@ class GlobalAggregationCalculatorTest { val globalAggregationCalculator = aggregationCalculator( aggregationDeadline = 100.milliseconds, aggregationDeadlineDelay = 50.milliseconds, - metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test") + metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test"), ) val pendingProofsGauge = testMeterRegistry.get("test.aggregation.proofs.ready").gauge() @@ -411,8 +411,8 @@ class GlobalAggregationCalculatorTest { startBlockNumber = 1u, endBlockNumber = 10u, startBlockTimestamp = Instant.fromEpochMilliseconds(100), - endBlockTimestamp = Instant.fromEpochMilliseconds(130) - ) + endBlockTimestamp = Instant.fromEpochMilliseconds(130), + ), ) globalAggregationCalculator.newBlob( blobCounters( @@ -420,8 +420,8 @@ class GlobalAggregationCalculatorTest { startBlockNumber = 11u, endBlockNumber = 30u, startBlockTimestamp = Instant.fromEpochMilliseconds(140), - endBlockTimestamp = Instant.fromEpochMilliseconds(250) - ) + endBlockTimestamp = Instant.fromEpochMilliseconds(250), + ), ) whenever(safeBlockProvider.getLatestSafeBlockHeader()) @@ -430,9 +430,9 @@ class GlobalAggregationCalculatorTest { BlockHeaderSummary( number = 30u, hash = ByteArrayExt.random32(), - timestamp = Instant.fromEpochMilliseconds(250) - ) - ) + timestamp = Instant.fromEpochMilliseconds(250), + ), + ), ) fixedClock.setTimeTo(Instant.fromEpochMilliseconds(1755)) @@ -489,7 +489,7 @@ class GlobalAggregationCalculatorTest { lastBlockNumber = lastFinalizedBlockNumber, aggregationDeadline = aggregationDeadline, aggregationDeadlineDelay = aggregationDeadlineDelay, - aggregationHandler = aggregationHandler + aggregationHandler = aggregationHandler, ) whenever(safeBlockProvider.getLatestSafeBlockHeader()) @@ -498,9 +498,9 @@ class GlobalAggregationCalculatorTest { BlockHeaderSummary( number = firstBlobEndBlockNumber, hash = ByteArrayExt.random32(), - timestamp = firstBlobEndBlockTimeStamp - ) - ) + timestamp = firstBlobEndBlockTimeStamp, + ), + ), ) val time1 = firstBlobEndBlockTimeStamp.plus(aggregationDeadline).plus(aggregationDeadlineDelay).plus(2.milliseconds) @@ -511,8 +511,8 @@ class GlobalAggregationCalculatorTest { startBlockNumber = firstBlobStartBlockNumber, endBlockNumber = firstBlobEndBlockNumber, startBlockTimestamp = firstBlobStartBlockTimeStamp, - endBlockTimestamp = firstBlobEndBlockTimeStamp - ) + endBlockTimestamp = firstBlobEndBlockTimeStamp, + ), ) val check1 = aggregationTriggerCalculatorByDeadline.checkAggregation() @@ -522,9 +522,9 @@ class GlobalAggregationCalculatorTest { BlockHeaderSummary( number = secondBlobEndBlockNumber, hash = ByteArrayExt.random32(), - timestamp = secondBlobEndTimestamp - ) - ) + timestamp = secondBlobEndTimestamp, + ), + ), ) val time2 = secondBlobEndTimestamp.plus(aggregationDeadline).plus(aggregationDeadlineDelay).plus(2.milliseconds) @@ -536,8 +536,8 @@ class GlobalAggregationCalculatorTest { startBlockNumber = secondBlobStartBlockNumber, endBlockNumber = secondBlobEndBlockNumber, startBlockTimestamp = secondBlobStartTimestamp, - endBlockTimestamp = secondBlobEndTimestamp - ) + endBlockTimestamp = secondBlobEndTimestamp, + ), ) blockAggregation1ProcessingUntilComplete.complete(Unit) check1.get() @@ -550,7 +550,7 @@ class GlobalAggregationCalculatorTest { assertThat(aggregations.size).isEqualTo(2) assertThat(aggregations.toList().sortedBy { it.startBlockNumber }).containsExactly( BlobsToAggregate(startBlockNumber = firstBlobStartBlockNumber, endBlockNumber = firstBlobEndBlockNumber), - BlobsToAggregate(startBlockNumber = secondBlobStartBlockNumber, endBlockNumber = secondBlobEndBlockNumber) + BlobsToAggregate(startBlockNumber = secondBlobStartBlockNumber, endBlockNumber = secondBlobEndBlockNumber), ) } @@ -561,12 +561,12 @@ class GlobalAggregationCalculatorTest { aggregationSizeMultipleOf: Int, blobs: List, proofsLimit: Int, - expectedAggregations: List + expectedAggregations: List, ) { val actualAggregations = mutableListOf() val globalAggregationCalculator = aggregationCalculator( proofLimit = proofsLimit.toUInt(), - aggregationSizeMultipleOf = aggregationSizeMultipleOf + aggregationSizeMultipleOf = aggregationSizeMultipleOf, ) { blobsToAggregate -> actualAggregations.add(blobsToAggregate) SafeFuture.completedFuture(Unit) @@ -584,7 +584,7 @@ class GlobalAggregationCalculatorTest { return if (seenBlobsSet.contains(blobCounters.startBlockNumber)) { AggregationTrigger( AggregationTriggerType.TIME_LIMIT, - inFlightAggregation ?: BlobsToAggregate(blobCounters.startBlockNumber, blobCounters.endBlockNumber) + inFlightAggregation ?: BlobsToAggregate(blobCounters.startBlockNumber, blobCounters.endBlockNumber), ) } else { seenBlobsSet.add(blobCounters.startBlockNumber) @@ -594,7 +594,7 @@ class GlobalAggregationCalculatorTest { override fun newBlob(blobCounters: BlobCounters) { inFlightAggregation = BlobsToAggregate( inFlightAggregation?.startBlockNumber ?: blobCounters.startBlockNumber, - blobCounters.endBlockNumber + blobCounters.endBlockNumber, ) } override fun reset() { @@ -609,7 +609,7 @@ class GlobalAggregationCalculatorTest { BlobsToAggregate(5uL, 5uL), BlobsToAggregate(6uL, 6uL), BlobsToAggregate(7uL, 7uL), - BlobsToAggregate(8uL, 8uL) + BlobsToAggregate(8uL, 8uL), ) val aggregationTriggerCalculator = AggregationTriggerCalculatorByProofLimit(proofsLimit.toUInt()) val globalAggregationCalculator = GlobalAggregationCalculator( @@ -617,7 +617,7 @@ class GlobalAggregationCalculatorTest { syncAggregationTrigger = listOf(aggregationTriggerCalculator, aggregationTriggerOnReprocessCalculator), deferredAggregationTrigger = emptyList(), metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), - aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt() + aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt(), ) val actualAggregations = mutableListOf() val aggregationHandler = AggregationHandler { blobsToAggregate -> @@ -638,18 +638,18 @@ class GlobalAggregationCalculatorTest { aggregationTriggerType = AggregationTriggerType.TIME_LIMIT, aggregation = BlobsToAggregate( startBlockNumber = blobs[0].startBlockNumber, - endBlockNumber = blobs[2].endBlockNumber - ) + endBlockNumber = blobs[2].endBlockNumber, + ), ) val expectedAggregations = listOf( BlobsToAggregate( startBlockNumber = blobs[0].startBlockNumber, - endBlockNumber = blobs[1].endBlockNumber + endBlockNumber = blobs[1].endBlockNumber, ), BlobsToAggregate( startBlockNumber = blobs[2].startBlockNumber, - endBlockNumber = blobs[3].endBlockNumber - ) + endBlockNumber = blobs[3].endBlockNumber, + ), ) val syncAggregationTriggerCalculator = AggregationTriggerCalculatorByProofLimit(proofsLimit.toUInt()) val deferredAggregationTriggerCalculator = object : DeferredAggregationTriggerCalculator { @@ -668,7 +668,7 @@ class GlobalAggregationCalculatorTest { syncAggregationTrigger = listOf(syncAggregationTriggerCalculator), deferredAggregationTrigger = listOf(deferredAggregationTriggerCalculator), metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), - aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt() + aggregationSizeMultipleOf = aggregationSizeMultipleOf.toUInt(), ) val enableDeferredTrigger = AtomicBoolean(false) @@ -728,13 +728,13 @@ class GlobalAggregationCalculatorTest { val aggregationSizeMultipleOf: Int, val blobs: List, val proofsLimit: Int, - val expectedAggregations: List + val expectedAggregations: List, ) private fun checkAggregationSizesNotExceedingMaxAggregationSize(endSize: UInt, maxAggregationSize: UInt) { for (aggregationSize in 1u..endSize) { assertThat( - GlobalAggregationCalculator.getUpdatedAggregationSize(aggregationSize, maxAggregationSize) + GlobalAggregationCalculator.getUpdatedAggregationSize(aggregationSize, maxAggregationSize), ).isEqualTo(aggregationSize) } } @@ -750,7 +750,7 @@ class GlobalAggregationCalculatorTest { endBlockNumber = endBlockNumber.toULong(), startBlockTimestamp = Instant.fromEpochMilliseconds((startBlockNumber * 100).toLong()), endBlockTimestamp = Instant.fromEpochMilliseconds((endBlockNumber * 100).toLong()), - expectedShnarf = Random.nextBytes(32) + expectedShnarf = Random.nextBytes(32), ) } @@ -764,8 +764,8 @@ class GlobalAggregationCalculatorTest { BlobsToAggregate(1u, 7u), BlobsToAggregate(8u, 14u), BlobsToAggregate(15u, 15u), - BlobsToAggregate(16u, 20u) - ) + BlobsToAggregate(16u, 20u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs_with_customization", @@ -777,8 +777,8 @@ class GlobalAggregationCalculatorTest { BlobsToAggregate(7u, 12u), BlobsToAggregate(13u, 14u), BlobsToAggregate(15u, 20u), - BlobsToAggregate(21u, 25u) - ) + BlobsToAggregate(21u, 25u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -787,8 +787,8 @@ class GlobalAggregationCalculatorTest { proofsLimit = 15, expectedAggregations = listOf( BlobsToAggregate(1u, 6u), - BlobsToAggregate(7u, 12u) - ) + BlobsToAggregate(7u, 12u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -797,8 +797,8 @@ class GlobalAggregationCalculatorTest { proofsLimit = 15, expectedAggregations = listOf( BlobsToAggregate(1u, 4u), - BlobsToAggregate(5u, 8u) - ) + BlobsToAggregate(5u, 8u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -806,8 +806,8 @@ class GlobalAggregationCalculatorTest { blobs = regularBlobs(15), proofsLimit = 21, expectedAggregations = listOf( - BlobsToAggregate(1u, 10u) - ) + BlobsToAggregate(1u, 10u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -816,8 +816,8 @@ class GlobalAggregationCalculatorTest { proofsLimit = 26, expectedAggregations = listOf( BlobsToAggregate(1u, 12u), - BlobsToAggregate(13u, 24u) - ) + BlobsToAggregate(13u, 24u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -827,8 +827,8 @@ class GlobalAggregationCalculatorTest { expectedAggregations = listOf( BlobsToAggregate(1u, 7u), BlobsToAggregate(8u, 14u), - BlobsToAggregate(15u, 21u) - ) + BlobsToAggregate(15u, 21u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -838,8 +838,8 @@ class GlobalAggregationCalculatorTest { expectedAggregations = listOf( BlobsToAggregate(1u, 8u), BlobsToAggregate(9u, 16u), - BlobsToAggregate(17u, 24u) - ) + BlobsToAggregate(17u, 24u), + ), ), AggregationSizeConstraintTestCase( name = "regular_blobs", @@ -848,9 +848,9 @@ class GlobalAggregationCalculatorTest { proofsLimit = 26, expectedAggregations = listOf( BlobsToAggregate(1u, 9u), - BlobsToAggregate(10u, 18u) - ) - ) + BlobsToAggregate(10u, 18u), + ), + ), ) @JvmStatic @@ -861,7 +861,7 @@ class GlobalAggregationCalculatorTest { it.aggregationSizeMultipleOf, it.blobs, it.proofsLimit, - it.expectedAggregations + it.expectedAggregations, ) }.stream() } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorServiceTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorServiceTest.kt index 6aabb794..89eff65e 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorServiceTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/aggregation/ProofAggregationCoordinatorServiceTest.kt @@ -37,7 +37,7 @@ class ProofAggregationCoordinatorServiceTest { private fun createBlob(startBlockNumber: ULong, endBLockNumber: ULong): BlobAndBatchCounters { val batches = BlockIntervals( startBlockNumber, - listOf(startBlockNumber + 2UL, startBlockNumber + 6UL, endBLockNumber) + listOf(startBlockNumber + 2UL, startBlockNumber + 6UL, endBLockNumber), ) val blobCounters = BlobCounters( @@ -46,7 +46,7 @@ class ProofAggregationCoordinatorServiceTest { endBLockNumber, Instant.fromEpochMilliseconds(100), Instant.fromEpochMilliseconds(5000), - expectedShnarf = Random.nextBytes(32) + expectedShnarf = Random.nextBytes(32), ) return BlobAndBatchCounters(blobCounters = blobCounters, executionProofs = batches) } @@ -66,7 +66,7 @@ class ProofAggregationCoordinatorServiceTest { l1RollingHashMessageNumber = 4, l2MerkleRoots = listOf("mock_l2MerkleRoots".toByteArray()), l2MerkleTreesDepth = 5, - l2MessagingBlocksOffsets = "mock_l2MessagingBlocksOffsets".toByteArray() + l2MessagingBlocksOffsets = "mock_l2MessagingBlocksOffsets".toByteArray(), ) @Test @@ -81,7 +81,7 @@ class ProofAggregationCoordinatorServiceTest { val config = ProofAggregationCoordinatorService.Config( pollingInterval = 10.milliseconds, - proofsLimit = blobsToPoll + proofsLimit = blobsToPoll, ) var provenAggregation = 0UL @@ -97,7 +97,7 @@ class ProofAggregationCoordinatorServiceTest { proofAggregationClient = mockProofAggregationClient, aggregationL2StateProvider = mockAggregationL2StateProvider, metricsFacade = metricsFacade, - provenAggregationEndBlockNumberConsumer = provenAggregationEndBlockNumberConsumer + provenAggregationEndBlockNumberConsumer = provenAggregationEndBlockNumberConsumer, ) verify(mockAggregationCalculator).onAggregation(proofAggregationCoordinatorService) @@ -132,23 +132,23 @@ class ProofAggregationCoordinatorServiceTest { val executionProofs1 = BlockIntervals( blob1[0].executionProofs.startingBlockNumber, - blob1[0].executionProofs.upperBoundaries + blob1[1].executionProofs.upperBoundaries + blob1[0].executionProofs.upperBoundaries + blob1[1].executionProofs.upperBoundaries, ) val executionProofs2 = BlockIntervals( blob1[2].executionProofs.startingBlockNumber, - blob1[2].executionProofs.upperBoundaries + blob2[0].executionProofs.upperBoundaries + blob1[2].executionProofs.upperBoundaries + blob2[0].executionProofs.upperBoundaries, ) val rollingInfo1 = AggregationL2State( parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(123456), parentAggregationLastL1RollingHashMessageNumber = 12UL, - parentAggregationLastL1RollingHash = ByteArray(32) + parentAggregationLastL1RollingHash = ByteArray(32), ) val rollingInfo2 = AggregationL2State( parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(123458), parentAggregationLastL1RollingHashMessageNumber = 14UL, - parentAggregationLastL1RollingHash = ByteArray(32) + parentAggregationLastL1RollingHash = ByteArray(32), ) whenever(mockAggregationL2StateProvider.getAggregationL2State(anyLong())) @@ -160,13 +160,13 @@ class ProofAggregationCoordinatorServiceTest { ProofIndex( it.blobCounters.startBlockNumber, it.blobCounters.endBlockNumber, - it.blobCounters.expectedShnarf + it.blobCounters.expectedShnarf, ) }, executionProofs = executionProofs1, parentAggregationLastBlockTimestamp = rollingInfo1.parentAggregationLastBlockTimestamp, parentAggregationLastL1RollingHashMessageNumber = rollingInfo1.parentAggregationLastL1RollingHashMessageNumber, - parentAggregationLastL1RollingHash = rollingInfo1.parentAggregationLastL1RollingHash + parentAggregationLastL1RollingHash = rollingInfo1.parentAggregationLastL1RollingHash, ) val proofsToAggregate2 = ProofsToAggregate( @@ -174,13 +174,13 @@ class ProofAggregationCoordinatorServiceTest { ProofIndex( it.blobCounters.startBlockNumber, it.blobCounters.endBlockNumber, - it.blobCounters.expectedShnarf + it.blobCounters.expectedShnarf, ) }, executionProofs = executionProofs2, parentAggregationLastBlockTimestamp = rollingInfo2.parentAggregationLastBlockTimestamp, parentAggregationLastL1RollingHashMessageNumber = rollingInfo2.parentAggregationLastL1RollingHashMessageNumber, - parentAggregationLastL1RollingHash = rollingInfo2.parentAggregationLastL1RollingHash + parentAggregationLastL1RollingHash = rollingInfo2.parentAggregationLastL1RollingHash, ) val aggregationProof1 = aggregationProofResponse.copy(finalBlockNumber = 23) @@ -190,14 +190,14 @@ class ProofAggregationCoordinatorServiceTest { startBlockNumber = blobsToAggregate1.startBlockNumber, endBlockNumber = blobsToAggregate1.endBlockNumber, batchCount = compressionBlobs1.sumOf { it.blobCounters.numberOfBatches }.toULong(), - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) val aggregation2 = Aggregation( startBlockNumber = blobsToAggregate2.startBlockNumber, endBlockNumber = blobsToAggregate2.endBlockNumber, batchCount = compressionBlobs2.sumOf { it.blobCounters.numberOfBatches }.toULong(), - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) whenever(mockProofAggregationClient.requestProof(any())) @@ -215,8 +215,8 @@ class ProofAggregationCoordinatorServiceTest { mockAggregationsRepository.saveNewAggregation( argThat { this == aggregation1 || this == aggregation2 - } - ) + }, + ), ) .thenReturn(SafeFuture.completedFuture(Unit)) diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculatorTest.kt index 99ef046e..27af12ef 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/blob/RollingBlobShnarfCalculatorTest.kt @@ -54,14 +54,14 @@ class RollingBlobShnarfCalculatorTest { expectedShnarf = Random.nextBytes(32), commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSideCar = Random.nextBytes(48) - ) + kzgProofSideCar = Random.nextBytes(48), + ), ) rollingBlobShnarfCalculator = RollingBlobShnarfCalculator( blobShnarfCalculator = mockBlobShnarfCalculator, blobsRepository = mockBlobsRepository, - genesisShnarf = ByteArray(32) + genesisShnarf = ByteArray(32), ) } @@ -75,7 +75,7 @@ class RollingBlobShnarfCalculatorTest { compressedData = Random.nextBytes(100), parentStateRootHash = Random.nextBytes(32), finalStateRootHash = Random.nextBytes(32), - conflationOrder = BlockIntervals(previousBlobEndBlockNumber + 1UL, listOf(previousBlobEndBlockNumber + 100UL)) + conflationOrder = BlockIntervals(previousBlobEndBlockNumber + 1UL, listOf(previousBlobEndBlockNumber + 100UL)), ).get() assertThat(rollingBlobShnarfResult.parentBlobHash.contentEquals(previousBlobDataHash)).isTrue() @@ -97,7 +97,7 @@ class RollingBlobShnarfCalculatorTest { compressedData = Random.nextBytes(100), parentStateRootHash = Random.nextBytes(32), finalStateRootHash = Random.nextBytes(32), - conflationOrder = BlockIntervals(firstBlobEndBlockNumber + 2UL, listOf(firstBlobEndBlockNumber + 100UL)) + conflationOrder = BlockIntervals(firstBlobEndBlockNumber + 2UL, listOf(firstBlobEndBlockNumber + 100UL)), ).get() } assertThat(exception).hasCauseInstanceOf(IllegalStateException::class.java) @@ -113,7 +113,7 @@ class RollingBlobShnarfCalculatorTest { compressedData = Random.nextBytes(100), parentStateRootHash = Random.nextBytes(32), finalStateRootHash = Random.nextBytes(32), - conflationOrder = BlockIntervals(secondBlobStartBlockNumber, listOf(secondBlobEndBlockNumber)) + conflationOrder = BlockIntervals(secondBlobStartBlockNumber, listOf(secondBlobEndBlockNumber)), ).get() assertThat(rollingBlobShnarfResult.parentBlobHash.contentEquals(firstBlob.blobHash)).isTrue() @@ -129,14 +129,14 @@ class RollingBlobShnarfCalculatorTest { compressedData = Random.nextBytes(100), parentStateRootHash = Random.nextBytes(32), finalStateRootHash = Random.nextBytes(32), - conflationOrder = BlockIntervals(thirdBlobStartBlockNumber, listOf(thirdBlobEndBlockNumber)) + conflationOrder = BlockIntervals(thirdBlobStartBlockNumber, listOf(thirdBlobEndBlockNumber)), ).get() } assertThat(exception).hasCauseInstanceOf(IllegalStateException::class.java) assertThat(exception.cause) .hasMessage( "Blob block range start block number=$thirdBlobStartBlockNumber " + - "is not equal to parent blob end block number=$secondBlobEndBlockNumber + 1" + "is not equal to parent blob end block number=$secondBlobEndBlockNumber + 1", ) } @@ -153,7 +153,7 @@ class RollingBlobShnarfCalculatorTest { compressedData = Random.nextBytes(100), parentStateRootHash = Random.nextBytes(32), finalStateRootHash = Random.nextBytes(32), - conflationOrder = BlockIntervals(secondBlobStartBlockNumber, listOf(secondBlobEndBlockNumber)) + conflationOrder = BlockIntervals(secondBlobStartBlockNumber, listOf(secondBlobEndBlockNumber)), ).get() } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinatorTest.kt index e70fdec7..b672b54e 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/BlockToBatchSubmissionCoordinatorTest.kt @@ -38,7 +38,7 @@ class BlockToBatchSubmissionCoordinatorTest { private fun createBlockToBatchSubmissionCoordinator( vertx: Vertx, conflationService: ConflationService = defaultConflationService, - log: Logger = LogManager.getLogger(this::class.java) + log: Logger = LogManager.getLogger(this::class.java), ): BlockToBatchSubmissionCoordinator { val tracesCountersClient = mock().also { @@ -50,7 +50,7 @@ class BlockToBatchSubmissionCoordinatorTest { tracesCountersClient = tracesCountersClient, vertx = vertx, encoder = { blockRlpEncoded }, - log = log + log = log, ) } @@ -63,7 +63,7 @@ class BlockToBatchSubmissionCoordinatorTest { val blockToBatchSubmissionCoordinator = createBlockToBatchSubmissionCoordinator( vertx = vertx, conflationService = failingConflationService, - log = testLogger + log = testLogger, ) val captor = argumentCaptor() @@ -74,7 +74,7 @@ class BlockToBatchSubmissionCoordinatorTest { eq("Failed to conflate block={} errorMessage={}"), any(), any(), - captor.capture() + captor.capture(), ) } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimitTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimitTest.kt index 238b96ab..f496d61a 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimitTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByBlockLimitTest.kt @@ -49,7 +49,7 @@ class ConflationCalculatorByBlockLimitTest { blockNumber = blockNumber.toULong(), blockTimestamp = Instant.parse("2021-01-01T00:00:00.000Z"), tracesCounters = fakeTracesCountersV2(blockNumber.toUInt()), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressedTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressedTest.kt index c99e8645..3d32daa7 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressedTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByDataCompressedTest.kt @@ -29,12 +29,12 @@ class ConflationCalculatorByDataCompressedTest { BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 0, - compressedSizeAfter = block.size + compressedSizeAfter = block.size, ) } } calculator = ConflationCalculatorByDataCompressed( - blobCompressor + blobCompressor, ) } @@ -47,8 +47,8 @@ class ConflationCalculatorByDataCompressedTest { assertThat(calculator.checkOverflow(blockCounters())).isEqualTo( ConflationCalculator.OverflowTrigger( trigger = ConflationTrigger.DATA_LIMIT, - singleBlockOverSized = true - ) + singleBlockOverSized = true, + ), ) } @@ -62,8 +62,8 @@ class ConflationCalculatorByDataCompressedTest { assertThat(calculator.checkOverflow(blockCounters())).isEqualTo( ConflationCalculator.OverflowTrigger( trigger = ConflationTrigger.DATA_LIMIT, - singleBlockOverSized = true - ) + singleBlockOverSized = true, + ), ) } @@ -82,22 +82,22 @@ class ConflationCalculatorByDataCompressedTest { BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 0, - compressedSizeAfter = 50 - ) + compressedSizeAfter = 50, + ), ) whenever(blobCompressor.appendBlock(eq(block2RawData))).thenReturn( BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 2, - compressedSizeAfter = 100 - ) + compressedSizeAfter = 100, + ), ) whenever(blobCompressor.appendBlock(eq(block3RawData))).thenReturn( BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 3, - compressedSizeAfter = 150 - ) + compressedSizeAfter = 150, + ), ) calculator.checkAndAppendBlock(blockCounters(block1RawData)) @@ -120,8 +120,8 @@ class ConflationCalculatorByDataCompressedTest { BlobCompressor.AppendResult( blockAppended = false, compressedSizeBefore = 0, - compressedSizeAfter = 5000 - ) + compressedSizeAfter = 5000, + ), ) calculator.checkOverflow(blockCounters(block1RawData)) @@ -151,15 +151,15 @@ class ConflationCalculatorByDataCompressedTest { BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 0, - compressedSizeAfter = 50 - ) + compressedSizeAfter = 50, + ), ) whenever(blobCompressor.appendBlock(eq(block2RawData))).thenReturn( BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 2, - compressedSizeAfter = 100 - ) + compressedSizeAfter = 100, + ), ) whenever(blobCompressor.canAppendBlock(eq(block3RawData))) .thenReturn(false) @@ -168,8 +168,8 @@ class ConflationCalculatorByDataCompressedTest { BlobCompressor.AppendResult( blockAppended = true, compressedSizeBefore = 3, - compressedSizeAfter = 150 - ) + compressedSizeAfter = 150, + ), ) calculator.checkAndAppendBlock(blockCounters(block1RawData)) calculator.startNewBatch() @@ -197,6 +197,6 @@ class ConflationCalculatorByDataCompressedTest { blockNumber = 0u, blockTimestamp = Instant.parse("2021-01-01T00:00:00Z"), tracesCounters = fakeTracesCountersV2(0u), - blockRLPEncoded = rlpRawData + blockRLPEncoded = rlpRawData, ) } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTracesTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTracesTest.kt index 0bedf2af..5b718868 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTracesTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByExecutionTracesTest.kt @@ -21,7 +21,7 @@ class ConflationCalculatorByExecutionTracesTest { private val calculator = ConflationCalculatorByExecutionTraces( tracesLimit, TracesCountersV2.EMPTY_TRACES_COUNT, - metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test") + metricsFacade = MicrometerMetricsFacade(testMeterRegistry, "test"), ) private lateinit var conflationTriggerConsumer: ConflationTriggerConsumer @@ -108,7 +108,7 @@ class ConflationCalculatorByExecutionTracesTest { val overflowingTraces = listOf( TracingModuleV2.MMU, TracingModuleV2.ADD, - TracingModuleV2.RLP_TXN + TracingModuleV2.RLP_TXN, ) val oversizedTraceCounters = TracesCountersV2( TracingModuleV2.entries.associate { @@ -117,7 +117,7 @@ class ConflationCalculatorByExecutionTracesTest { } else { it to 0u } - } + }, ) TracingModuleV2.entries.forEach { module -> @@ -147,7 +147,7 @@ class ConflationCalculatorByExecutionTracesTest { } else { it to 0u } - } + }, ) calculator.appendBlock(blockCounters(fakeTracesCountersV2(10u))) @@ -168,13 +168,13 @@ class ConflationCalculatorByExecutionTracesTest { private fun blockCounters( tracesCounters: TracesCounters, - blockNumber: ULong = 1uL + blockNumber: ULong = 1uL, ): BlockCounters { return BlockCounters( blockNumber = blockNumber, blockTimestamp = Instant.parse("2021-01-01T00:00:00Z"), tracesCounters = tracesCounters, - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbersTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbersTest.kt index 1c38b984..7c484e4a 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbersTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTargetBlockNumbersTest.kt @@ -37,7 +37,7 @@ class ConflationCalculatorByTargetBlockNumbersTest { blockNumber = blockNumber, blockTimestamp = Instant.parse("2021-01-01T00:00:00.000Z"), tracesCounters = fakeTracesCountersV2(blockNumber.toUInt()), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) } } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadlineTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadlineTest.kt index 61db4cef..d7c3173a 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadlineTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationCalculatorByTimeDeadlineTest.kt @@ -30,7 +30,7 @@ import kotlin.time.toJavaDuration class ConflationCalculatorByTimeDeadlineTest { private val config = ConflationCalculatorByTimeDeadline.Config( conflationDeadline = 20.seconds, - conflationDeadlineLastBlockConfirmationDelay = 4.seconds + conflationDeadlineLastBlockConfirmationDelay = 4.seconds, ) private val blockTimestamp = Instant.parse("2021-01-01T00:00:00Z") private val clock: Clock = mock { on { now() } doReturn blockTimestamp } @@ -39,8 +39,8 @@ class ConflationCalculatorByTimeDeadlineTest { BlockHeaderSummary( number = 1u, timestamp = blockTimestamp, - hash = ByteArrayExt.random32() - ) + hash = ByteArrayExt.random32(), + ), ) } private lateinit var conflationTiggers: MutableList @@ -57,8 +57,8 @@ class ConflationCalculatorByTimeDeadlineTest { lastBlockNumber = 0u, clock = clock, latestBlockProvider = latestBlockProvider, - log = log - ) + log = log, + ), ).also { it.setConflationTriggerConsumer { conflationTiggers.add(clock.now()) @@ -96,9 +96,9 @@ class ConflationCalculatorByTimeDeadlineTest { BlockHeaderSummary( number = 3u, timestamp = block2Timestamp.plus(config.conflationDeadline).plus(5.seconds), - hash = ByteArrayExt.random32() - ) - ) + hash = ByteArrayExt.random32(), + ), + ), ) conflationCalculatorByTimeDeadline.checkConflationDeadline() @@ -117,9 +117,9 @@ class ConflationCalculatorByTimeDeadlineTest { BlockHeaderSummary( number = 2u, timestamp = block2Timestamp, - hash = ByteArrayExt.random32() - ) - ) + hash = ByteArrayExt.random32(), + ), + ), ) val time1 = blockTimestamp.plus(config.conflationDeadline).plus(10.seconds) @@ -148,9 +148,9 @@ class ConflationCalculatorByTimeDeadlineTest { BlockHeaderSummary( number = 2u, timestamp = block2Timestamp, - hash = ByteArrayExt.random32() - ) - ) + hash = ByteArrayExt.random32(), + ), + ), ) val time1 = blockTimestamp.plus(config.conflationDeadline).plus(10.seconds) @@ -171,9 +171,9 @@ class ConflationCalculatorByTimeDeadlineTest { BlockHeaderSummary( number = 1u, timestamp = blockTimestamp, - hash = ByteArrayExt.random32() - ) - ) + hash = ByteArrayExt.random32(), + ), + ), ) whenever(clock.now()).thenReturn(blockTimestamp.plus(config.conflationDeadline).plus(10.seconds)) @@ -183,7 +183,7 @@ class ConflationCalculatorByTimeDeadlineTest { verify(log).warn( eq("SafeBlock request failed. Will Retry conflation deadline on next tick errorMessage={}"), contains("Failed to fetch latest block"), - any() + any(), ) } @@ -192,7 +192,7 @@ class ConflationCalculatorByTimeDeadlineTest { blockNumber = blockNumber, blockTimestamp = timestamp, tracesCounters = fakeTracesCountersV2(1u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) } } @@ -204,7 +204,7 @@ class ConflationCalculatorByTimeDeadlineRunnerTest { fun `should call calculator every interval`() { val runner = DeadlineConflationCalculatorRunner( 10.milliseconds, - mockCalculator + mockCalculator, ) // it should be idempotent runner.start() diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImplTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImplTest.kt index 8145d686..299fd1e9 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImplTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ConflationServiceImplTest.kt @@ -32,10 +32,10 @@ class ConflationServiceImplTest { conflationCalculator = GlobalBlockConflationCalculator( lastBlockNumber = 0u, syncCalculators = listOf( - ConflationCalculatorByBlockLimit(conflationBlockLimit) + ConflationCalculatorByBlockLimit(conflationBlockLimit), ), deferredTriggerConflationCalculators = emptyList(), - emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ) conflationService = ConflationServiceImpl(conflationCalculator, mock(defaultAnswer = RETURNS_DEEP_STUBS)) } @@ -50,19 +50,19 @@ class ConflationServiceImplTest { blockNumber = 1UL, payload1Time.plus(0.seconds), tracesCounters = fakeTracesCountersV2(40u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) val payloadCounters2 = BlockCounters( blockNumber = 2UL, payload1Time.plus(2.seconds), tracesCounters = fakeTracesCountersV2(40u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) val payloadCounters3 = BlockCounters( blockNumber = 3UL, payload1Time.plus(4.seconds), tracesCounters = fakeTracesCountersV2(100u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) val conflationEvents = mutableListOf() @@ -85,10 +85,10 @@ class ConflationServiceImplTest { endBlockNumber = 2u, conflationTrigger = ConflationTrigger.BLOCKS_LIMIT, // these are not counted in conflation, so will be 0 - tracesCounters = fakeTracesCountersV2(0u) - ) - ) - ) + tracesCounters = fakeTracesCountersV2(0u), + ), + ), + ), ) } @@ -120,8 +120,8 @@ class ConflationServiceImplTest { blockNumber = it.number.toULong(), blockTimestamp = blockTime, tracesCounters = fixedTracesCounters, - blockRLPEncoded = ByteArray(0) - ) + blockRLPEncoded = ByteArray(0), + ), ) } } @@ -160,8 +160,8 @@ class ConflationServiceImplTest { blockNumber = block.number.toULong(), blockTimestamp = blockTime, tracesCounters = fixedTracesCounters, - blockRLPEncoded = ByteArray(0) - ) + blockRLPEncoded = ByteArray(0), + ), ) }.isEqualTo(expectedException) } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculatorTest.kt index 7a7e64fb..ee5b8cab 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlobAwareConflationCalculatorTest.kt @@ -69,10 +69,10 @@ class GlobalBlobAwareConflationCalculatorTest { fakeClock = FakeFixedClock(fakeClockTime) safeBlockProvider = mock { on { getLatestSafeBlock() }.thenReturn( - SafeFuture.failedFuture(RuntimeException("getLatestSafeBlock should not be called")) + SafeFuture.failedFuture(RuntimeException("getLatestSafeBlock should not be called")), ) on { getLatestSafeBlockHeader() }.thenReturn( - SafeFuture.failedFuture(RuntimeException("getLatestSafeBlockHeader not mocked yet")) + SafeFuture.failedFuture(RuntimeException("getLatestSafeBlockHeader not mocked yet")), ) } metricsFacade = spy(MicrometerMetricsFacade(registry = SimpleMeterRegistry())) @@ -83,7 +83,7 @@ class GlobalBlobAwareConflationCalculatorTest { any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeCompressedDataSizeInBlobHistogram = it }) .whenever(metricsFacade).createHistogram( @@ -92,108 +92,108 @@ class GlobalBlobAwareConflationCalculatorTest { any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeUncompressedDataSizeInBlobHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BLOB), eq("uncompressed.data.size"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeGasUsedInBatchHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BATCH), eq("gas"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeCompressedDataSizeInBatchHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BATCH), eq("compressed.data.size"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeUncompressedDataSizeInBatchHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BATCH), eq("uncompressed.data.size"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeAvgCompressedTxDataSizeInBatchHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BATCH), eq("avg.compressed.tx.data.size"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) doReturn(FakeHistogram().also { fakeAvgUncompressedTxDataSizeInBatchHistogram = it }) .whenever( - metricsFacade + metricsFacade, ).createHistogram( eq(LineaMetricsCategory.BATCH), eq("avg.uncompressed.tx.data.size"), any(), any(), any(), - anyOrNull() + anyOrNull(), ) calculatorByDealine = spy( ConflationCalculatorByTimeDeadline( config = ConflationCalculatorByTimeDeadline.Config( conflationDeadline = 2.seconds, - conflationDeadlineLastBlockConfirmationDelay = 10.milliseconds + conflationDeadlineLastBlockConfirmationDelay = 10.milliseconds, ), lastBlockNumber = lastBlockNumber, - latestBlockProvider = safeBlockProvider - ) + latestBlockProvider = safeBlockProvider, + ), ) blobCompressor = spy(FakeBlobCompressor(dataLimit = 100, fakeCompressionRatio = 1.0)) calculatorByDataCompressed = ConflationCalculatorByDataCompressed(blobCompressor = blobCompressor) calculatorByTraces = ConflationCalculatorByExecutionTraces( tracesCountersLimit = fakeTracesCountersV2(100u), emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, - metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) + metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), ) conflationTargetEndBlockNumbers.clear() calculatorByTargetBlockNumber = ConflationCalculatorByTargetBlockNumbers( - targetEndBlockNumbers = conflationTargetEndBlockNumbers + targetEndBlockNumbers = conflationTargetEndBlockNumbers, ) globalCalculator = GlobalBlockConflationCalculator( lastBlockNumber = lastBlockNumber, syncCalculators = listOf(calculatorByTraces, calculatorByDataCompressed, calculatorByTargetBlockNumber), deferredTriggerConflationCalculators = listOf(calculatorByDealine), - emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ) calculator = GlobalBlobAwareConflationCalculator( conflationCalculator = globalCalculator, blobCalculator = calculatorByDataCompressed, batchesLimit = defaultBatchesLimit, - metricsFacade = metricsFacade + metricsFacade = metricsFacade, ) conflations = mutableListOf() blobs = mutableListOf() @@ -219,7 +219,7 @@ class GlobalBlobAwareConflationCalculatorTest { tracesCounters = fakeTracesCountersV2(1u), blockRLPEncoded = ByteArray(11), numOfTransactions = 1u, - gasUsed = 10uL + gasUsed = 10uL, ) } blockCounters.forEach { @@ -231,15 +231,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TARGET_BLOCK_NUMBER, - tracesCounters = fakeTracesCountersV2(5u) + tracesCounters = fakeTracesCountersV2(5u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 10uL, conflationTrigger = ConflationTrigger.TARGET_BLOCK_NUMBER, - tracesCounters = fakeTracesCountersV2(5u) - ) - ) + tracesCounters = fakeTracesCountersV2(5u), + ), + ), ) assertThat(blobs).hasSize(2) assertThat(blobs[0].conflations).isEqualTo(conflations.subList(0, 1)) @@ -268,7 +268,7 @@ class GlobalBlobAwareConflationCalculatorTest { tracesCounters = fakeTracesCountersV2(10u), blockRLPEncoded = ByteArray(11), numOfTransactions = 1u, - gasUsed = 10uL + gasUsed = 10uL, ) val block2Counters = BlockCounters( blockNumber = 2uL, @@ -276,7 +276,7 @@ class GlobalBlobAwareConflationCalculatorTest { tracesCounters = fakeTracesCountersV2(10u), blockRLPEncoded = ByteArray(12), numOfTransactions = 1u, - gasUsed = 10uL + gasUsed = 10uL, ) val block3Counters = BlockCounters( blockNumber = 3uL, @@ -284,7 +284,7 @@ class GlobalBlobAwareConflationCalculatorTest { tracesCounters = fakeTracesCountersV2(10u), blockRLPEncoded = ByteArray(83), numOfTransactions = 1u, - gasUsed = 10uL + gasUsed = 10uL, ) val block4Counters = BlockCounters( blockNumber = 4uL, @@ -292,7 +292,7 @@ class GlobalBlobAwareConflationCalculatorTest { tracesCounters = fakeTracesCountersV2(10u), blockRLPEncoded = ByteArray(44), numOfTransactions = 1u, - gasUsed = 10uL + gasUsed = 10uL, ) calculator.newBlock(block1Counters) @@ -321,15 +321,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(20u) + tracesCounters = fakeTracesCountersV2(20u), ), ConflationCalculationResult( startBlockNumber = 3uL, endBlockNumber = 3uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(10u) - ) - ) + tracesCounters = fakeTracesCountersV2(10u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -357,47 +357,47 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(90u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) // over sized block val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(200u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) // blob size is 0 bytes up to this point (fake compression, limit 100) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // blob size is 15 bytes up to this point (fake compression, limit 100) val block6Counters = BlockCounters( blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(61) + blockRLPEncoded = ByteArray(61), ) // block 7 does not fit on top of 6, so it should emit conflation and blob events val block7Counters = BlockCounters( blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -414,27 +414,27 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(20u) + tracesCounters = fakeTracesCountersV2(20u), ), ConflationCalculationResult( startBlockNumber = 3uL, endBlockNumber = 3uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(90u) + tracesCounters = fakeTracesCountersV2(90u), ), ConflationCalculationResult( startBlockNumber = 4uL, endBlockNumber = 4uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(200u) + tracesCounters = fakeTracesCountersV2(200u), ), ConflationCalculationResult( startBlockNumber = 5uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(20u) - ) - ) + tracesCounters = fakeTracesCountersV2(20u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -452,31 +452,31 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // blob size is 65 bytes up to this point (fake compression, limit 100) // block 6 does not fit, so it should emit conflation and blob events @@ -484,14 +484,14 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(30u), - blockRLPEncoded = ByteArray(61) + blockRLPEncoded = ByteArray(61), ) // block 7 does not fit on top of 6, so it should emit conflation and blob events val block7Counters = BlockCounters( blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -507,9 +507,9 @@ class GlobalBlobAwareConflationCalculatorTest { BlockHeaderSummary( number = block5Counters.blockNumber, hash = ByteArrayExt.random32(), - timestamp = block5Counters.blockTimestamp - ) - ) + timestamp = block5Counters.blockTimestamp, + ), + ), ) calculatorByDealine.checkConflationDeadline() @@ -524,15 +524,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TIME_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(30u) - ) - ) + tracesCounters = fakeTracesCountersV2(30u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -552,38 +552,38 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // traces limit will be triggered val block6Counters = BlockCounters( blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(60u), - blockRLPEncoded = ByteArray(16) + blockRLPEncoded = ByteArray(16), ) // blob size is 71 bytes up to this point (fake compression, limit 100) // block 7 does not fit, so it should emit conflation and blob events @@ -591,7 +591,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -610,15 +610,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(60u) - ) - ) + tracesCounters = fakeTracesCountersV2(60u), + ), + ), ) assertThat(blobs).hasSize(1) @@ -634,35 +634,35 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(50u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) // traces limit will be triggered val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(100u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) // traces limit will be triggered val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(90u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) // traces limit will be triggered val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(100u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) // traces limit will be triggered val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(50u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // traces limit will be triggered and blob batch limit will be triggered // as well since there are three pending batches now in the blob aware @@ -671,7 +671,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(60u), - blockRLPEncoded = ByteArray(16) + blockRLPEncoded = ByteArray(16), ) calculator.newBlock(block1Counters) @@ -692,33 +692,33 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 1uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 2uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(100u) + tracesCounters = fakeTracesCountersV2(100u), ), ConflationCalculationResult( startBlockNumber = 3uL, endBlockNumber = 3uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(90u) + tracesCounters = fakeTracesCountersV2(90u), ), ConflationCalculationResult( startBlockNumber = 4uL, endBlockNumber = 4uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(100u) + tracesCounters = fakeTracesCountersV2(100u), ), ConflationCalculationResult( startBlockNumber = 5uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) - ) - ) + tracesCounters = fakeTracesCountersV2(50u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -738,38 +738,38 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // over-sized block traces limit will be triggered val block6Counters = BlockCounters( blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(200u), - blockRLPEncoded = ByteArray(16) + blockRLPEncoded = ByteArray(16), ) // blob size is 71 bytes up to this point (fake compression, limit 100) // block 7 does not fit, so it should emit conflation and blob events @@ -777,7 +777,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -796,15 +796,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(200u) - ) - ) + tracesCounters = fakeTracesCountersV2(200u), + ), + ), ) assertThat(blobs).hasSize(1) @@ -820,31 +820,31 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // traces limit and data limit will be triggered // blob size is 55 bytes up to this point (fake compression, limit 100) @@ -853,7 +853,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(60u), - blockRLPEncoded = ByteArray(61) + blockRLPEncoded = ByteArray(61), ) // blob size is 61 bytes up to this point (fake compression, limit 100) // block 7 does not fit, so it should emit conflation and blob events @@ -861,7 +861,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -880,15 +880,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(60u) - ) - ) + tracesCounters = fakeTracesCountersV2(60u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -908,31 +908,31 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // over-sized traces limit and data limit will be triggered // blob size is 55 bytes up to this point (fake compression, limit 100) @@ -941,7 +941,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(200u), - blockRLPEncoded = ByteArray(61) + blockRLPEncoded = ByteArray(61), ) // blob size is 61 bytes up to this point (fake compression, limit 100) // block 7 does not fit, so it should emit conflation and blob events @@ -949,7 +949,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -968,15 +968,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(200u) - ) - ) + tracesCounters = fakeTracesCountersV2(200u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -996,31 +996,31 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = block3Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(14) + blockRLPEncoded = ByteArray(14), ) val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = block4Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(15) + blockRLPEncoded = ByteArray(15), ) // over-sized block traces limit and data limit will be triggered // blob size is 55 bytes up to this point (fake compression, limit 100) @@ -1029,7 +1029,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 6uL, blockTimestamp = block5Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(200u), - blockRLPEncoded = ByteArray(61) + blockRLPEncoded = ByteArray(61), ) // blob size is 61 bytes up to this point (fake compression, limit 100) // block 7 does not fit, so it should emit conflation and blob events @@ -1037,7 +1037,7 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 7uL, blockTimestamp = block6Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(71) + blockRLPEncoded = ByteArray(71), ) calculator.newBlock(block1Counters) @@ -1053,9 +1053,9 @@ class GlobalBlobAwareConflationCalculatorTest { BlockHeaderSummary( number = block5Counters.blockNumber, hash = ByteArrayExt.random32(), - timestamp = block5Counters.blockTimestamp - ) - ) + timestamp = block5Counters.blockTimestamp, + ), + ), ) calculatorByDealine.checkConflationDeadline() @@ -1070,15 +1070,15 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 5uL, conflationTrigger = ConflationTrigger.TIME_LIMIT, - tracesCounters = fakeTracesCountersV2(50u) + tracesCounters = fakeTracesCountersV2(50u), ), ConflationCalculationResult( startBlockNumber = 6uL, endBlockNumber = 6uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeTracesCountersV2(200u) - ) - ) + tracesCounters = fakeTracesCountersV2(200u), + ), + ), ) assertThat(blobs).hasSize(2) @@ -1098,19 +1098,19 @@ class GlobalBlobAwareConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = fakeClockTime, tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(11) + blockRLPEncoded = ByteArray(11), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = block1Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(12) + blockRLPEncoded = ByteArray(12), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = block2Counters.blockTimestamp.plus(blockTime), tracesCounters = fakeTracesCountersV2(90u), - blockRLPEncoded = ByteArray(13) + blockRLPEncoded = ByteArray(13), ) whenever(blobCompressor.canAppendBlock(block3Counters.blockRLPEncoded)) @@ -1127,9 +1127,9 @@ class GlobalBlobAwareConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(20u) - ) - ) + tracesCounters = fakeTracesCountersV2(20u), + ), + ), ) assertThat(blobs).hasSize(1) diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorIntTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorIntTest.kt index 26e6d949..193077c9 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorIntTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorIntTest.kt @@ -41,27 +41,27 @@ class GlobalBlockConflationCalculatorIntTest { conflations = mutableListOf() safeBlockProvider = mock() { on { getLatestSafeBlock() }.thenReturn( - SafeFuture.failedFuture(RuntimeException("getLatestSafeBlock should not be called")) + SafeFuture.failedFuture(RuntimeException("getLatestSafeBlock should not be called")), ) on { getLatestSafeBlockHeader() }.thenReturn( - SafeFuture.failedFuture(RuntimeException("getLatestSafeBlockHeader not mocked yet")) + SafeFuture.failedFuture(RuntimeException("getLatestSafeBlockHeader not mocked yet")), ) } calculatorByDealine = spy( ConflationCalculatorByTimeDeadline( config = ConflationCalculatorByTimeDeadline.Config( conflationDeadline = 2.seconds, - conflationDeadlineLastBlockConfirmationDelay = 10.milliseconds + conflationDeadlineLastBlockConfirmationDelay = 10.milliseconds, ), lastBlockNumber = lastBlockNumber, - latestBlockProvider = safeBlockProvider - ) + latestBlockProvider = safeBlockProvider, + ), ) val fakeBlobCompressor = FakeBlobCompressor(1_000) val calculatorByData = spy( ConflationCalculatorByDataCompressed( - blobCompressor = fakeBlobCompressor - ) + blobCompressor = fakeBlobCompressor, + ), ) whenever(calculatorByData.reset()).then { fakeBlobCompressor.reset() @@ -70,13 +70,13 @@ class GlobalBlockConflationCalculatorIntTest { calculatorByTraces = ConflationCalculatorByExecutionTraces( tracesCountersLimit = fakeTracesCountersV2(100u), emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, - metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) + metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), ) globalCalculator = GlobalBlockConflationCalculator( lastBlockNumber = lastBlockNumber, syncCalculators = listOf(calculatorByTraces, calculatorByData), deferredTriggerConflationCalculators = listOf(calculatorByDealine), - emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ) globalCalculator.onConflatedBatch { trigger -> conflations.add(trigger) @@ -91,13 +91,13 @@ class GlobalBlockConflationCalculatorIntTest { blockNumber = 1uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(101u), - blockRLPEncoded = ByteArray(10) + blockRLPEncoded = ByteArray(10), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(10) + blockRLPEncoded = ByteArray(10), ) globalCalculator.newBlock(block1Counters) globalCalculator.newBlock(block2Counters) @@ -108,8 +108,8 @@ class GlobalBlockConflationCalculatorIntTest { startBlockNumber = 1uL, endBlockNumber = 1uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = block1Counters.tracesCounters - ) + tracesCounters = block1Counters.tracesCounters, + ), ) } @@ -120,13 +120,13 @@ class GlobalBlockConflationCalculatorIntTest { blockNumber = 1uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(60u), - blockRLPEncoded = ByteArray(10) + blockRLPEncoded = ByteArray(10), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(50u), - blockRLPEncoded = ByteArray(20) + blockRLPEncoded = ByteArray(20), ) globalCalculator.newBlock(block1Counters) globalCalculator.newBlock(block2Counters) @@ -137,8 +137,8 @@ class GlobalBlockConflationCalculatorIntTest { startBlockNumber = 1uL, endBlockNumber = 1uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = block1Counters.tracesCounters - ) + tracesCounters = block1Counters.tracesCounters, + ), ) } @@ -149,19 +149,19 @@ class GlobalBlockConflationCalculatorIntTest { blockNumber = 1uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(50u), - blockRLPEncoded = ByteArray(10) + blockRLPEncoded = ByteArray(10), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(50u), - blockRLPEncoded = ByteArray(20) + blockRLPEncoded = ByteArray(20), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(20) + blockRLPEncoded = ByteArray(20), ) globalCalculator.newBlock(block1Counters) globalCalculator.newBlock(block2Counters) @@ -173,8 +173,8 @@ class GlobalBlockConflationCalculatorIntTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = block1Counters.tracesCounters.add(block2Counters.tracesCounters) - ) + tracesCounters = block1Counters.tracesCounters.add(block2Counters.tracesCounters), + ), ) } @@ -185,19 +185,19 @@ class GlobalBlockConflationCalculatorIntTest { blockNumber = 1uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(500) + blockRLPEncoded = ByteArray(500), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(20u), - blockRLPEncoded = ByteArray(480) + blockRLPEncoded = ByteArray(480), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(20u), - blockRLPEncoded = ByteArray(21) + blockRLPEncoded = ByteArray(21), ) globalCalculator.newBlock(block1Counters) globalCalculator.newBlock(block2Counters) @@ -209,8 +209,8 @@ class GlobalBlockConflationCalculatorIntTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = block1Counters.tracesCounters.add(block2Counters.tracesCounters) - ) + tracesCounters = block1Counters.tracesCounters.add(block2Counters.tracesCounters), + ), ) } @@ -221,46 +221,46 @@ class GlobalBlockConflationCalculatorIntTest { blockNumber = 1uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(101u), - blockRLPEncoded = ByteArray(100) + blockRLPEncoded = ByteArray(100), ) // block with data in size limit val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(20u), - blockRLPEncoded = ByteArray(1_000) + blockRLPEncoded = ByteArray(1_000), ) val block3Counters = BlockCounters( blockNumber = 3uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(30u), - blockRLPEncoded = ByteArray(300) + blockRLPEncoded = ByteArray(300), ) val block4Counters = BlockCounters( blockNumber = 4uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(70u), - blockRLPEncoded = ByteArray(400) + blockRLPEncoded = ByteArray(400), ) // will trigger traces overflow val block5Counters = BlockCounters( blockNumber = 5uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(100) + blockRLPEncoded = ByteArray(100), ) val block6Counters = BlockCounters( blockNumber = 6uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(100) + blockRLPEncoded = ByteArray(100), ) val block7Counters = BlockCounters( blockNumber = 7uL, blockTimestamp = fakeClock.now(), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(100) + blockRLPEncoded = ByteArray(100), ) globalCalculator.newBlock(block1Counters) @@ -278,9 +278,9 @@ class GlobalBlockConflationCalculatorIntTest { BlockHeaderSummary( number = 7uL, hash = ByteArrayExt.random32(), - timestamp = block7Counters.blockTimestamp - ) - ) + timestamp = block7Counters.blockTimestamp, + ), + ), ) calculatorByDealine.checkConflationDeadline() @@ -290,24 +290,24 @@ class GlobalBlockConflationCalculatorIntTest { startBlockNumber = 1uL, endBlockNumber = 1uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = block1Counters.tracesCounters - ) + tracesCounters = block1Counters.tracesCounters, + ), ) assertThat(conflations[1]).isEqualTo( ConflationCalculationResult( startBlockNumber = 2uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = block2Counters.tracesCounters - ) + tracesCounters = block2Counters.tracesCounters, + ), ) assertThat(conflations[2]).isEqualTo( ConflationCalculationResult( startBlockNumber = 3uL, endBlockNumber = 4uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = block3Counters.tracesCounters.add(block4Counters.tracesCounters) - ) + tracesCounters = block3Counters.tracesCounters.add(block4Counters.tracesCounters), + ), ) assertThat(conflations[3]).isEqualTo( ConflationCalculationResult( @@ -315,8 +315,8 @@ class GlobalBlockConflationCalculatorIntTest { endBlockNumber = 7uL, conflationTrigger = ConflationTrigger.TIME_LIMIT, tracesCounters = - block5Counters.tracesCounters.add(block6Counters.tracesCounters).add(block7Counters.tracesCounters) - ) + block5Counters.tracesCounters.add(block6Counters.tracesCounters).add(block7Counters.tracesCounters), + ), ) assertThat(conflations).hasSize(4) } diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorTest.kt index c404732f..1f5a40a5 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/GlobalBlockConflationCalculatorTest.kt @@ -30,13 +30,13 @@ class GlobalBlockConflationCalculatorTest { blockNumber = 1uL, blockTimestamp = Instant.parse("2023-12-11T00:00:00.000Z"), tracesCounters = fakeTracesCountersV2(10u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) val block2Counters = BlockCounters( blockNumber = 2uL, blockTimestamp = Instant.parse("2023-12-11T00:00:02.000Z"), tracesCounters = fakeTracesCountersV2(20u), - blockRLPEncoded = ByteArray(0) + blockRLPEncoded = ByteArray(0), ) private lateinit var conflations: MutableList @@ -70,7 +70,7 @@ class GlobalBlockConflationCalculatorTest { lastBlockNumber = lastBlockNumber, syncCalculators = listOf(calculatorByTraces, calculatorByData), deferredTriggerConflationCalculators = listOf(calculatorByDealine), - emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ) conflations = mutableListOf() globalCalculator.onConflatedBatch { trigger -> @@ -86,7 +86,7 @@ class GlobalBlockConflationCalculatorTest { lastBlockNumber = lastBlockNumber, syncCalculators = listOf(calculatorByTraces, calculatorByData, calculatorByDealine), deferredTriggerConflationCalculators = listOf(calculatorByDealine), - emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + emptyTracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ) }.isInstanceOf(IllegalArgumentException::class.java) .hasMessageContaining("calculators must not contain duplicates") @@ -113,9 +113,9 @@ class GlobalBlockConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 1uL, conflationTrigger = ConflationTrigger.DATA_LIMIT, - tracesCounters = fakeCountersAfterConflation - ) - ) + tracesCounters = fakeCountersAfterConflation, + ), + ), ) calculatorByData.inOrder { @@ -154,9 +154,9 @@ class GlobalBlockConflationCalculatorTest { startBlockNumber = 1uL, endBlockNumber = 2uL, conflationTrigger = ConflationTrigger.TIME_LIMIT, - tracesCounters = fakeCountersAfterConflation - ) - ) + tracesCounters = fakeCountersAfterConflation, + ), + ), ) calculatorByData.inOrder { diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImplTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImplTest.kt index d407f980..e88930cc 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImplTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/conflation/ProofGeneratingConflationHandlerImplTest.kt @@ -24,7 +24,7 @@ class ProofGeneratingConflationHandlerImplTest { // // gap on 13 createBlock(12UL), createBlock(11UL), - createBlock(10UL) + createBlock(10UL), ) assertConsecutiveBlocksRange(blocks).let { result -> assertThat(result).isInstanceOf(Err::class.java) @@ -38,7 +38,7 @@ class ProofGeneratingConflationHandlerImplTest { createBlock(13UL), createBlock(12UL), createBlock(11UL), - createBlock(10UL) + createBlock(10UL), ) assertThat(assertConsecutiveBlocksRange(blocks)).isEqualTo(Ok(10UL..13UL)) diff --git a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImplTest.kt b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImplTest.kt index 811eee8f..0598efb7 100644 --- a/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImplTest.kt +++ b/coordinator/core/src/test/kotlin/net/consensys/zkevm/ethereum/coordination/proofcreation/ZkProofCreationCoordinatorImplTest.kt @@ -43,7 +43,7 @@ class ZkProofCreationCoordinatorImplTest { zkProofCreationCoordinator = ZkProofCreationCoordinatorImpl( executionProverClient = executionProverClient, messageServiceAddress = messageServiceAddress, - l2EthApiClient = l2EthApiClient + l2EthApiClient = l2EthApiClient, ) } @@ -54,11 +54,11 @@ class ZkProofCreationCoordinatorImplTest { val block2 = createBlock(number = 124UL, stateRoot = ByteArray(32) { 0x2 }) val block1Logs = listOf( createMessageSentEthLogV1(blockNumber = 123UL, contractAddress = messageServiceAddress), - createL2RollingHashUpdatedEthLogV1(blockNumber = 123UL, contractAddress = messageServiceAddress) + createL2RollingHashUpdatedEthLogV1(blockNumber = 123UL, contractAddress = messageServiceAddress), ) val block2Logs = listOf( createMessageSentEthLogV1(blockNumber = 124UL, contractAddress = messageServiceAddress), - createL2RollingHashUpdatedEthLogV1(blockNumber = 124UL, contractAddress = messageServiceAddress) + createL2RollingHashUpdatedEthLogV1(blockNumber = 124UL, contractAddress = messageServiceAddress), ) l2EthApiClient.addBlocks(listOf(block0, block1, block2)) @@ -71,11 +71,11 @@ class ZkProofCreationCoordinatorImplTest { zkStateMerkleProof = ArrayNode(null), zkParentStateRootHash = ByteArrayExt.random32(), zkEndStateRootHash = ByteArrayExt.random32(), - zkStateManagerVersion = "2.0.0" + zkStateManagerVersion = "2.0.0", ) val generateTracesResponse = GenerateTracesResponse( tracesFileName = "123-124-conflated-traces.json", - tracesEngineVersion = "1.0.0" + tracesEngineVersion = "1.0.0", ) whenever(executionProverClient.requestProof(any())) @@ -83,9 +83,9 @@ class ZkProofCreationCoordinatorImplTest { SafeFuture.completedFuture( BatchExecutionProofResponse( startBlockNumber = 123UL, - endBlockNumber = 124UL - ) - ) + endBlockNumber = 124UL, + ), + ), ) val batch = zkProofCreationCoordinator.createZkProof( @@ -95,13 +95,13 @@ class ZkProofCreationCoordinatorImplTest { startBlockNumber = 123UL, endBlockNumber = 124UL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = fakeTracesCountersV2(0u) - ) + tracesCounters = fakeTracesCountersV2(0u), + ), ), traces = BlocksTracesConflated( tracesResponse = generateTracesResponse, - zkStateTraces = type2StateResponse - ) + zkStateTraces = type2StateResponse, + ), ).get() assertThat(batch.startBlockNumber).isEqualTo(123UL) @@ -113,8 +113,8 @@ class ZkProofCreationCoordinatorImplTest { tracesResponse = generateTracesResponse, bridgeLogs = listOf(block1Logs, block2Logs).flatten(), type2StateData = type2StateResponse, - keccakParentStateRootHash = block0.stateRoot - ) + keccakParentStateRootHash = block0.stateRoot, + ), ) } } diff --git a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Aggregagtion.kt b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Aggregagtion.kt index 9135a86e..2c89d044 100644 --- a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Aggregagtion.kt +++ b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Aggregagtion.kt @@ -4,22 +4,22 @@ fun createAggregation( startBlockNumber: Long? = null, endBlockNumber: Long? = null, batchCount: Long = 1, - aggregationProof: ProofToFinalize? = null + aggregationProof: ProofToFinalize? = null, ): Aggregation { require( (startBlockNumber != null && endBlockNumber != null) || - aggregationProof != null + aggregationProof != null, ) { "Either aggregationProof or startBlockNumber, endBlockNumber must be provided" } val _aggregationProof = aggregationProof ?: createProofToFinalize( firstBlockNumber = startBlockNumber!!, - finalBlockNumber = endBlockNumber!! + finalBlockNumber = endBlockNumber!!, ) return Aggregation( startBlockNumber = _aggregationProof.firstBlockNumber.toULong(), endBlockNumber = _aggregationProof.finalBlockNumber.toULong(), batchCount = batchCount.toULong(), - aggregationProof = _aggregationProof + aggregationProof = _aggregationProof, ) } @@ -29,11 +29,11 @@ fun createAggregation( batchCount: Long = 1, aggregationProof: ProofToFinalize = createProofToFinalize( firstBlockNumber = (parentAggregation.endBlockNumber + 1UL).toLong(), - finalBlockNumber = endBlockNumber - ) + finalBlockNumber = endBlockNumber, + ), ): Aggregation { return createAggregation( batchCount = batchCount, - aggregationProof = aggregationProof + aggregationProof = aggregationProof, ) } diff --git a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Batch.kt b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Batch.kt index c742acc3..a3918416 100644 --- a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Batch.kt +++ b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/Batch.kt @@ -2,10 +2,10 @@ package net.consensys.zkevm.domain fun createBatch( startBlockNumber: Long, - endBlockNumber: Long + endBlockNumber: Long, ): Batch { return Batch( startBlockNumber = startBlockNumber.toULong(), - endBlockNumber = endBlockNumber.toULong() + endBlockNumber = endBlockNumber.toULong(), ) } diff --git a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobCounters.kt b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobCounters.kt index 6ce8f2c0..050e69c0 100644 --- a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobCounters.kt +++ b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobCounters.kt @@ -11,7 +11,7 @@ fun blobCounters( numberOfBatches: UInt = 2u, startBlockTimestamp: Instant = Clock.System.now(), endBlockTimestamp: Instant = startBlockTimestamp.plus(LINEA_BLOCK_INTERVAL * numberOfBatches.toInt()), - expectedShnarf: ByteArray = Random.nextBytes(32) + expectedShnarf: ByteArray = Random.nextBytes(32), ): BlobCounters { return BlobCounters( startBlockNumber = startBlockNumber, @@ -19,6 +19,6 @@ fun blobCounters( numberOfBatches = numberOfBatches, startBlockTimestamp = startBlockTimestamp, endBlockTimestamp = endBlockTimestamp, - expectedShnarf = expectedShnarf + expectedShnarf = expectedShnarf, ) } diff --git a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobRecord.kt b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobRecord.kt index c2896828..22ff4c26 100644 --- a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobRecord.kt +++ b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/BlobRecord.kt @@ -34,11 +34,11 @@ fun createBlobRecord( startBlockTime: Instant? = null, batchesCount: UInt = 1U, parentBlobRecord: BlobRecord? = null, - blobCompressionProof: BlobCompressionProof? = null + blobCompressionProof: BlobCompressionProof? = null, ): BlobRecord { require( blobCompressionProof != null || - (startBlockNumber != null && endBlockNumber != null) + (startBlockNumber != null && endBlockNumber != null), ) { "Either blobCompressionProof or startBlockNumber and endBlockNumber must be provided" } val _startBlockNumber = startBlockNumber ?: blobCompressionProof!!.conflationOrder.startingBlockNumber val _endBlockNumber = endBlockNumber ?: blobCompressionProof!!.conflationOrder.upperBoundaries.last() @@ -54,7 +54,7 @@ fun createBlobRecord( parentStateRootHash = _parentStateRootHash, finalStateRootHash = finalStateRootHash, prevShnarf = _prevShnarf, - conflationOrder = BlockIntervals(_startBlockNumber, listOf(_endBlockNumber)) + conflationOrder = BlockIntervals(_startBlockNumber, listOf(_endBlockNumber)), ) val _dataHash = blobHash ?: shnarfResult.dataHash val _parentDataHash = parentDataHash ?: parentBlobRecord?.blobCompressionProof?.dataHash ?: Random.nextBytes(32) @@ -75,7 +75,7 @@ fun createBlobRecord( verifierID = 6789, commitment = if (eip4844Enabled) Random.nextBytes(48) else ByteArray(0), kzgProofContract = if (eip4844Enabled) Random.nextBytes(48) else ByteArray(0), - kzgProofSidecar = if (eip4844Enabled) Random.nextBytes(48) else ByteArray(0) + kzgProofSidecar = if (eip4844Enabled) Random.nextBytes(48) else ByteArray(0), ) return BlobRecord( startBlockNumber = _startBlockNumber, @@ -85,7 +85,7 @@ fun createBlobRecord( endBlockTime = endBlockTime, batchesCount = batchesCount, expectedShnarf = _blobCompressionProof.expectedShnarf, - blobCompressionProof = _blobCompressionProof + blobCompressionProof = _blobCompressionProof, ) } @@ -93,14 +93,14 @@ fun createBlobRecords( blobsIntervals: BlockIntervals, parentDataHash: ByteArray = Random.nextBytes(32), parentShnarf: ByteArray = Random.nextBytes(32), - parentStateRootHash: ByteArray = Random.nextBytes(32) + parentStateRootHash: ByteArray = Random.nextBytes(32), ): List { val firstBlob = createBlobRecord( startBlockNumber = blobsIntervals.startingBlockNumber, endBlockNumber = blobsIntervals.upperBoundaries.first(), parentDataHash = parentDataHash, parentShnarf = parentShnarf, - parentStateRootHash = parentStateRootHash + parentStateRootHash = parentStateRootHash, ) return blobsIntervals @@ -110,7 +110,7 @@ fun createBlobRecords( val blob = createBlobRecord( startBlockNumber = interval.startBlockNumber, endBlockNumber = interval.endBlockNumber, - parentBlobRecord = acc.last() + parentBlobRecord = acc.last(), ) acc.add(blob) acc @@ -119,14 +119,14 @@ fun createBlobRecords( fun createBlobRecords( compressionProofs: List, - firstBlockStartBlockTime: Instant = Clock.System.now().trimToSecondPrecision() + firstBlockStartBlockTime: Instant = Clock.System.now().trimToSecondPrecision(), ): List { require(compressionProofs.isNotEmpty()) { "At least one compression proof must be provided" } val sortedCompressionProofs = compressionProofs.sortedBy { it.conflationOrder.startingBlockNumber } val firstBlob = createBlobRecord( startBlockTime = firstBlockStartBlockTime, - blobCompressionProof = sortedCompressionProofs.first() + blobCompressionProof = sortedCompressionProofs.first(), ) return sortedCompressionProofs @@ -136,7 +136,7 @@ fun createBlobRecords( val blob = createBlobRecord( startBlockTime = parentBlobRecord.endBlockTime.plus(LINEA_BLOCK_INTERVAL), parentBlobRecord = parentBlobRecord, - blobCompressionProof = proof + blobCompressionProof = proof, ) acc.add(blob) acc @@ -145,7 +145,7 @@ fun createBlobRecords( fun createBlobRecordFromBatches( batches: List, - blobCompressionProof: BlobCompressionProof? = null + blobCompressionProof: BlobCompressionProof? = null, ): BlobRecord { val startBlockNumber = batches.first().startBlockNumber val endBlockNumber = batches.last().endBlockNumber @@ -162,6 +162,6 @@ fun createBlobRecordFromBatches( endBlockTime = endBlockTime, batchesCount = batches.size.toUInt(), expectedShnarf = Random.nextBytes(32), - blobCompressionProof = blobCompressionProof + blobCompressionProof = blobCompressionProof, ) } diff --git a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/ProofToFinalize.kt b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/ProofToFinalize.kt index d713e334..d87c858e 100644 --- a/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/ProofToFinalize.kt +++ b/coordinator/core/src/testFixtures/kotlin/net/consensys/zkevm/domain/ProofToFinalize.kt @@ -23,7 +23,7 @@ fun createProofToFinalize( parentAggregationLastBlockTimestamp: Instant = parentAggregationProof?.finalTimestamp ?: startBlockTime.minus(2.seconds), finalTimestamp: Instant = startBlockTime.plus((2L * (finalBlockNumber - firstBlockNumber)).seconds), - l2MessagingBlockOffsets: ByteArray = ByteArray(32) + l2MessagingBlockOffsets: ByteArray = ByteArray(32), ): ProofToFinalize { return ProofToFinalize( aggregatedProof = Random.nextBytes(32).setFirstByteToZero(), @@ -40,7 +40,7 @@ fun createProofToFinalize( l1RollingHashMessageNumber = 0, l2MerkleRoots = listOf(Random.nextBytes(32).setFirstByteToZero()), l2MerkleTreesDepth = 0, - l2MessagingBlocksOffsets = l2MessagingBlockOffsets + l2MessagingBlocksOffsets = l2MessagingBlockOffsets, ) } @@ -51,7 +51,7 @@ fun createProofToFinalizeFromBlobs( parentStateRootHash: ByteArray = parentBlob?.blobCompressionProof?.finalStateRootHash ?: Random.nextBytes(32).setFirstByteToZero(), dataParentHash: ByteArray = parentBlob?.blobCompressionProof?.dataHash - ?: Random.nextBytes(32).setFirstByteToZero() + ?: Random.nextBytes(32).setFirstByteToZero(), ): ProofToFinalize { return createProofToFinalize( firstBlockNumber = blobRecords.first().startBlockNumber.toLong(), @@ -62,19 +62,19 @@ fun createProofToFinalizeFromBlobs( parentStateRootHash = parentStateRootHash, dataParentHash = dataParentHash, finalTimestamp = blobRecords.last().endBlockTime, - dataHashes = blobRecords.map { it.blobCompressionProof!!.dataHash } + dataHashes = blobRecords.map { it.blobCompressionProof!!.dataHash }, ) } fun createProofToFinalizeFromBlobs( blobsByAggregation: List>, parentStateRootHash: ByteArray = Random.nextBytes(32), - dataParentHash: ByteArray = Random.nextBytes(32) + dataParentHash: ByteArray = Random.nextBytes(32), ): List { val firstAggregationProof = createProofToFinalizeFromBlobs( blobRecords = blobsByAggregation.first(), parentStateRootHash = parentStateRootHash, - dataParentHash = dataParentHash + dataParentHash = dataParentHash, ) val aggregations = mutableListOf(firstAggregationProof) @@ -84,7 +84,7 @@ fun createProofToFinalizeFromBlobs( val aggregationProof = createProofToFinalizeFromBlobs( blobRecords = aggBlobs, parentAggregationProof = parentAggProof, - parentBlob = parentBlob + parentBlob = parentBlob, ) aggregations.add(aggregationProof) aggregationProof to aggBlobs.last() diff --git a/coordinator/ethereum/blob-submitter/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/finalization/BlobAndAggregationFinalizationIntTest.kt b/coordinator/ethereum/blob-submitter/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/finalization/BlobAndAggregationFinalizationIntTest.kt index 8da2600f..f787b6fd 100644 --- a/coordinator/ethereum/blob-submitter/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/finalization/BlobAndAggregationFinalizationIntTest.kt +++ b/coordinator/ethereum/blob-submitter/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/finalization/BlobAndAggregationFinalizationIntTest.kt @@ -65,7 +65,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { private fun setupTest( vertx: Vertx, - smartContractVersion: LineaContractVersion + smartContractVersion: LineaContractVersion, ) { // V6 is always used, this is left for when V7 is implemented. if (listOf(LineaContractVersion.V6).contains(smartContractVersion).not()) { @@ -76,7 +76,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { // load files from FS while smc deploy loadBlobsAndAggregations( blobsResponsesDir = "$testDataDir/compression/responses", - aggregationsResponsesDir = "$testDataDir/aggregation/responses" + aggregationsResponsesDir = "$testDataDir/aggregation/responses", ) .let { (blobs, aggregations) -> this.blobs = blobs @@ -91,8 +91,8 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { BlobsPostgresDao( config = BlobsPostgresDao.Config(maxBlobsToReturn = 100U), connection = sqlClient, - clock = fakeClock - ) + clock = fakeClock, + ), ) aggregationsRepository = AggregationsRepositoryImpl(PostgresAggregationsDao(sqlClient, fakeClock)) @@ -103,11 +103,11 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { @Suppress("DEPRECATION") val alreadySubmittedBlobFilter = L1ShnarfBasedAlreadySubmittedBlobsFilter( lineaRollup = lineaRollupContractForDataSubmissionV6, - acceptedBlobEndBlockNumberConsumer = acceptedBlobEndBlockNumberConsumer + acceptedBlobEndBlockNumberConsumer = acceptedBlobEndBlockNumberConsumer, ) val blobSubmittedEventConsumers = mapOf( Consumer { blobSubmittedEvent = it } to "Blob Submitted Consumer 1", - Consumer { blobSubmissionDelay = it.getSubmissionDelay() } to "Blob Submitted Consumer 2" + Consumer { blobSubmissionDelay = it.getSubmissionDelay() } to "Blob Submitted Consumer 2", ) blobSubmissionCoordinator = run { @@ -116,7 +116,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { pollingInterval = 6.seconds, proofSubmissionDelay = 0.seconds, maxBlobsToSubmitPerTick = 100u, - targetBlobsToSubmitPerTx = 9u + targetBlobsToSubmitPerTx = 9u, ), blobsRepository = blobsRepository, aggregationsRepository = aggregationsRepository, @@ -125,7 +125,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { gasPriceCapProvider = FakeGasPriceCapProvider(), blobSubmittedEventDispatcher = EventDispatcher(blobSubmittedEventConsumers), vertx = vertx, - clock = fakeClock + clock = fakeClock, ) } @@ -133,27 +133,27 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { lineaRollupContractForAggregationSubmission = MakeFileDelegatedContractsManager .connectToLineaRollupContract( rollupDeploymentResult.contractAddress, - rollupDeploymentResult.rollupOperators[1].txManager + rollupDeploymentResult.rollupOperators[1].txManager, ) val submittedFinalizationConsumers = mapOf( Consumer { finalizationSubmittedEvent = it } to "Finalization Submitted Consumer 1", Consumer { finalizationSubmissionDelay = it.getSubmissionDelay() } - to "Finalization Submitted Consumer 2" + to "Finalization Submitted Consumer 2", ) val aggregationSubmitter = AggregationSubmitterImpl( lineaRollup = lineaRollupContractForAggregationSubmission, gasPriceCapProvider = FakeGasPriceCapProvider(), aggregationSubmittedEventConsumer = EventDispatcher(submittedFinalizationConsumers), - clock = fakeClock + clock = fakeClock, ) AggregationFinalizationCoordinator( config = AggregationFinalizationCoordinator.Config( pollingInterval = 6.seconds, - proofSubmissionDelay = 0.seconds + proofSubmissionDelay = 0.seconds, ), aggregationSubmitter = aggregationSubmitter, aggregationsRepository = aggregationsRepository, @@ -161,7 +161,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { lineaRollup = lineaRollupContractForAggregationSubmission, alreadySubmittedBlobsFilter = alreadySubmittedBlobFilter, vertx = vertx, - clock = fakeClock + clock = fakeClock, ) } } @@ -169,13 +169,13 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { private fun testSubmission( vertx: Vertx, testContext: VertxTestContext, - smartContractVersion: LineaContractVersion + smartContractVersion: LineaContractVersion, ) { setupTest(vertx, smartContractVersion) SafeFuture.allOf( SafeFuture.collectAll(blobs.map { blobsRepository.saveNewBlob(it) }.stream()), - SafeFuture.collectAll(aggregations.map { aggregationsRepository.saveNewAggregation(it) }.stream()) + SafeFuture.collectAll(aggregations.map { aggregationsRepository.saveNewAggregation(it) }.stream()), ).get() val aggEndTime = aggregations.last().aggregationProof!!.finalTimestamp @@ -196,7 +196,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { assertThat(blobSubmittedEvent.blobs.last().endBlockNumber).isEqualTo(blobs[19].endBlockNumber) assertThat(acceptedBlob).isEqualTo(blobs[19].endBlockNumber) assertThat(finalizationSubmittedEvent.endBlockNumber).isEqualTo( - aggregations.last().endBlockNumber + aggregations.last().endBlockNumber, ) assertThat(blobSubmissionDelay).isGreaterThan(0L) assertThat(finalizationSubmissionDelay).isGreaterThan(0L) @@ -209,7 +209,7 @@ class BlobAndAggregationFinalizationIntTest : CleanDbTestSuiteParallel() { @Timeout(3, timeUnit = TimeUnit.MINUTES) fun `submission works with contract V6`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { testSubmission(vertx, testContext, LineaContractVersion.V6) } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationFinalizationCoordinator.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationFinalizationCoordinator.kt index f62eb452..37810516 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationFinalizationCoordinator.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationFinalizationCoordinator.kt @@ -25,15 +25,15 @@ class AggregationFinalizationCoordinator( private val aggregationSubmitter: AggregationSubmitter, private val vertx: Vertx, private val clock: Clock, - private val log: Logger = LogManager.getLogger(AggregationFinalizationCoordinator::class.java) + private val log: Logger = LogManager.getLogger(AggregationFinalizationCoordinator::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { class Config( val pollingInterval: Duration, - val proofSubmissionDelay: Duration + val proofSubmissionDelay: Duration, ) override fun action(): SafeFuture { @@ -46,7 +46,7 @@ class AggregationFinalizationCoordinator( if (aggregationData == null) { log.info( "No aggregation available to submit with endBlockCreatedBefore={}", - endBlockCreatedBefore + endBlockCreatedBefore, ) SafeFuture.completedFuture(Unit) } else { @@ -57,7 +57,7 @@ class AggregationFinalizationCoordinator( log.debug( "aggregation={} last blob={} not yet submitted on L1, waiting for it.", aggregationData.aggregationProof.intervalString(), - aggregationData.aggregationEndBlob.intervalString() + aggregationData.aggregationEndBlob.intervalString(), ) SafeFuture.completedFuture(Unit) } else { @@ -70,25 +70,25 @@ class AggregationFinalizationCoordinator( } private fun fetchAggregationStartAndEndBlob( - proofToFinalize: ProofToFinalize? + proofToFinalize: ProofToFinalize?, ): SafeFuture { return if (proofToFinalize == null) { SafeFuture.completedFuture(null) } else { SafeFuture.collectAll( blobsRepository.findBlobByStartBlockNumber(proofToFinalize.startBlockNumber.toLong()), - blobsRepository.findBlobByEndBlockNumber(proofToFinalize.endBlockNumber.toLong()) + blobsRepository.findBlobByEndBlockNumber(proofToFinalize.endBlockNumber.toLong()), ) .thenApply { (startBlob, endBlob) -> when { startBlob == null -> throw IllegalStateException( - "start blob of aggregation=${proofToFinalize.intervalString()} not found in the DB." + "start blob of aggregation=${proofToFinalize.intervalString()} not found in the DB.", ) endBlob == null -> throw IllegalStateException( - "end blob of aggregation=${proofToFinalize.intervalString()} not found in the DB." + "end blob of aggregation=${proofToFinalize.intervalString()} not found in the DB.", ) else -> ProofEdgeBlobs(proofToFinalize, startBlob, endBlob) @@ -98,12 +98,12 @@ class AggregationFinalizationCoordinator( } private fun fetchAggregationData( - lastFinalizedBlockNumber: ULong + lastFinalizedBlockNumber: ULong, ): SafeFuture { return aggregationsRepository.getProofsToFinalize( fromBlockNumber = lastFinalizedBlockNumber.toLong() + 1, finalEndBlockCreatedBefore = clock.now().minus(config.proofSubmissionDelay), - maximumNumberOfProofs = 1 + maximumNumberOfProofs = 1, ) .thenApply { it.firstOrNull() } .thenCompose(::fetchAggregationStartAndEndBlob) @@ -120,8 +120,8 @@ class AggregationFinalizationCoordinator( AggregationData.genesis( aggregationProof, aggregationEndBlob, - aggregationStartBlob.blobCompressionProof!!.prevShnarf - ) + aggregationStartBlob.blobCompressionProof!!.prevShnarf, + ), ) } else { aggregationsRepository @@ -134,15 +134,15 @@ class AggregationFinalizationCoordinator( aggregationEndBlob = aggregationEndBlob, parentShnarf = aggregationStartBlob.blobCompressionProof!!.prevShnarf, parentL1RollingHash = parentAggregationProof.l1RollingHash, - parentL1RollingHashMessageNumber = parentAggregationProof.l1RollingHashMessageNumber - ) + parentL1RollingHashMessageNumber = parentAggregationProof.l1RollingHashMessageNumber, + ), ) } ?: run { log.info( "parent aggregation not found for aggregation={} " + "lastFinalizedBlockNumber={} skipping because another finalization tx was executed.", aggregationProof.intervalString(), - parentAggregationProof + parentAggregationProof, ) SafeFuture.completedFuture(null) } @@ -153,14 +153,14 @@ class AggregationFinalizationCoordinator( } private fun finalizeAggregationAfterEthCall( - aggregationData: AggregationData + aggregationData: AggregationData, ): SafeFuture { return aggregationSubmitter.submitAggregationAfterEthCall( aggregationProof = aggregationData.aggregationProof, aggregationEndBlob = aggregationData.aggregationEndBlob, parentShnarf = aggregationData.parentShnarf, parentL1RollingHash = aggregationData.parentL1RollingHash, - parentL1RollingHashMessageNumber = aggregationData.parentL1RollingHashMessageNumber + parentL1RollingHashMessageNumber = aggregationData.parentL1RollingHashMessageNumber, ).thenApply { Unit } } @@ -173,20 +173,20 @@ class AggregationFinalizationCoordinator( val aggregationEndBlob: BlobRecord, val parentShnarf: ByteArray, val parentL1RollingHash: ByteArray, - val parentL1RollingHashMessageNumber: Long + val parentL1RollingHashMessageNumber: Long, ) { companion object { fun genesis( aggregationProof: ProofToFinalize, aggregationEndBlob: BlobRecord, - parentShnarf: ByteArray + parentShnarf: ByteArray, ): AggregationData { return AggregationData( aggregationProof = aggregationProof, aggregationEndBlob = aggregationEndBlob, parentShnarf = parentShnarf, parentL1RollingHash = ByteArray(32), - parentL1RollingHashMessageNumber = 0 + parentL1RollingHashMessageNumber = 0, ) } } @@ -195,7 +195,7 @@ class AggregationFinalizationCoordinator( private data class ProofEdgeBlobs( val proof: ProofToFinalize, val startBlob: BlobRecord, - val endBlob: BlobRecord + val endBlob: BlobRecord, ) companion object { @@ -207,7 +207,7 @@ class AggregationFinalizationCoordinator( alreadySubmittedBlobFilter: AsyncFilter, aggregationSubmitter: AggregationSubmitter, vertx: Vertx, - clock: Clock + clock: Clock, ): AggregationFinalizationCoordinator { return AggregationFinalizationCoordinator( config = config, @@ -217,7 +217,7 @@ class AggregationFinalizationCoordinator( aggregationSubmitter = aggregationSubmitter, alreadySubmittedBlobsFilter = alreadySubmittedBlobFilter, vertx = vertx, - clock = clock + clock = clock, ) } } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationSubmitter.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationSubmitter.kt index c11ce84c..e5ea2f3f 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationSubmitter.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/AggregationSubmitter.kt @@ -23,7 +23,7 @@ interface AggregationSubmitter { aggregationEndBlob: BlobRecord, parentShnarf: ByteArray, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): SafeFuture } @@ -32,7 +32,7 @@ class AggregationSubmitterImpl( private val gasPriceCapProvider: GasPriceCapProvider?, private val aggregationSubmittedEventConsumer: Consumer = Consumer { }, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : AggregationSubmitter { private val log = LogManager.getLogger(this::class.java) @@ -41,7 +41,7 @@ class AggregationSubmitterImpl( aggregationEndBlob: BlobRecord, parentShnarf: ByteArray, parentL1RollingHash: ByteArray, - parentL1RollingHashMessageNumber: Long + parentL1RollingHashMessageNumber: Long, ): SafeFuture { log.debug("submitting aggregation={}", aggregationProof.intervalString()) return ( @@ -54,14 +54,14 @@ class AggregationSubmitterImpl( aggregationLastBlob = aggregationEndBlob, parentL1RollingHash = parentL1RollingHash, parentL1RollingHashMessageNumber = parentL1RollingHashMessageNumber, - gasPriceCaps = gasPriceCaps + gasPriceCaps = gasPriceCaps, ).thenPeek { transactionHash -> log.info( "submitted aggregation={} transactionHash={} nonce={} gasPriceCaps={}", aggregationProof.intervalString(), transactionHash, nonce, - gasPriceCaps + gasPriceCaps, ) val aggregationSubmittedEvent = FinalizationSubmittedEvent( aggregationProof = aggregationProof, @@ -69,7 +69,7 @@ class AggregationSubmitterImpl( parentL1RollingHash = parentL1RollingHash, parentL1RollingHashMessageNumber = parentL1RollingHashMessageNumber, submissionTimestamp = clock.now(), - transactionHash = transactionHash.toByteArray() + transactionHash = transactionHash.toByteArray(), ) aggregationSubmittedEventConsumer.accept(aggregationSubmittedEvent) } @@ -81,14 +81,14 @@ class AggregationSubmitterImpl( private fun logAggregationSubmissionError( intervalString: String, error: Throwable, - isEthCall: Boolean = error.cause is ContractCallException + isEthCall: Boolean = error.cause is ContractCallException, ) { logSubmissionError( log, "{} for aggregation finalization failed: aggregation={} errorMessage={}", intervalString, error, - isEthCall + isEthCall, ) } } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinator.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinator.kt index 38c8425a..342ecace 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinator.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinator.kt @@ -31,17 +31,17 @@ class BlobSubmissionCoordinator( private val clock: Clock, private val blobSubmissionFilter: AsyncFilter, private val blobsGrouperForSubmission: BlobsGrouperForSubmission, - private val log: Logger = LogManager.getLogger(BlobSubmissionCoordinator::class.java) + private val log: Logger = LogManager.getLogger(BlobSubmissionCoordinator::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { class Config( val pollingInterval: Duration, val proofSubmissionDelay: Duration, val maxBlobsToSubmitPerTick: UInt, - val targetBlobsToSubmitPerTx: UInt + val targetBlobsToSubmitPerTx: UInt, ) { init { require(maxBlobsToSubmitPerTick > 0u) { @@ -66,7 +66,7 @@ class BlobSubmissionCoordinator( "tick: l1BlockNumber={} nonce={} lastFinalizedBlockNumber={}", l1Reference.blockNumber, l1Reference.nonce, - finalizedL2BlockNumber + finalizedL2BlockNumber, ) } } @@ -85,7 +85,7 @@ class BlobSubmissionCoordinator( return blobsRepository.getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive = lastFinalizedBlockNumber.inc().toLong(), - endBlockCreatedBefore = endBlockCreatedBefore + endBlockCreatedBefore = endBlockCreatedBefore, ).thenCompose { blobRecords -> blobSubmissionFilter.invoke(blobRecords) .thenApply { blobRecordsToSubmit -> @@ -96,7 +96,7 @@ class BlobSubmissionCoordinator( "skipping blob submission: lastFinalizedBlockNumber={} cutOffTime={} totalBlobs={}", lastFinalizedBlockNumber, endBlockCreatedBefore, - blobRecords.size + blobRecords.size, ) } else { log.info( @@ -107,7 +107,7 @@ class BlobSubmissionCoordinator( config.maxBlobsToSubmitPerTick, endBlockCreatedBefore, it.toBlockIntervalsString(), - (blobRecords - blobRecordsToSubmit.toSet()).toBlockIntervalsString() + (blobRecords - blobRecordsToSubmit.toSet()).toBlockIntervalsString(), ) } } @@ -119,7 +119,7 @@ class BlobSubmissionCoordinator( aggregationsRepository.getProofsToFinalize( fromBlockNumber = lastFinalizedBlockNumber.inc().toLong(), finalEndBlockCreatedBefore = clock.now().minus(config.proofSubmissionDelay), - maximumNumberOfProofs = config.maxBlobsToSubmitPerTick.toInt() + maximumNumberOfProofs = config.maxBlobsToSubmitPerTick.toInt(), ).thenApply { proofsToFinalize -> if ( proofsToFinalize.isEmpty() || @@ -131,7 +131,7 @@ class BlobSubmissionCoordinator( } else { val aggregations = proofsToFinalize .filterOutWithEndBlockNumberBefore( - endBlockNumberInclusive = blobRecordsToSubmitCappedToLimit.first().startBlockNumber - 1UL + endBlockNumberInclusive = blobRecordsToSubmitCappedToLimit.first().startBlockNumber - 1UL, ) .toBlockIntervals() log.debug( @@ -139,12 +139,12 @@ class BlobSubmissionCoordinator( lastFinalizedBlockNumber, blobRecordsToSubmitCappedToLimit.toBlockIntervalsString(), aggregations.toIntervalList().toBlockIntervalsString(), - proofsToFinalize.toBlockIntervalsString() + proofsToFinalize.toBlockIntervalsString(), ) blobsGrouperForSubmission.chunkBlobs( blobsIntervals = blobRecordsToSubmitCappedToLimit, - aggregations = aggregations + aggregations = aggregations, ) } } @@ -155,14 +155,14 @@ class BlobSubmissionCoordinator( private fun blobBelongsToAnyAggregation( blobRecord: BlobRecord, - proofsToFinalize: List + proofsToFinalize: List, ): Boolean { return proofsToFinalize .any { blobRecord.startBlockNumber in it.startBlockNumber..it.endBlockNumber } } private fun submitBlobsAfterEthCall( - blobsChunks: List> + blobsChunks: List>, ): SafeFuture { return blobSubmitter .submitBlobCall(blobsChunks.first()) @@ -172,7 +172,7 @@ class BlobSubmissionCoordinator( log, blobsChunks.first().first().intervalString(), th, - isEthCall = true + isEthCall = true, ) false } @@ -200,16 +200,16 @@ class BlobSubmissionCoordinator( alreadySubmittedBlobsFilter: AsyncFilter, blobSubmittedEventDispatcher: Consumer, vertx: Vertx, - clock: Clock + clock: Clock, ): BlobSubmissionCoordinator { val blobsGrouperForSubmission: BlobsGrouperForSubmission = BlobsGrouperForSubmissionSwitcherByTargetBock( - eip4844TargetBlobsPerTx = config.targetBlobsToSubmitPerTx + eip4844TargetBlobsPerTx = config.targetBlobsToSubmitPerTx, ) val blobSubmitter = BlobSubmitterAsEIP4844MultipleBlobsPerTx( contract = lineaSmartContractClient, gasPriceCapProvider = gasPriceCapProvider, blobSubmittedEventConsumer = blobSubmittedEventDispatcher, - clock = clock + clock = clock, ) return BlobSubmissionCoordinator( @@ -221,7 +221,7 @@ class BlobSubmissionCoordinator( vertx = vertx, clock = clock, blobSubmissionFilter = alreadySubmittedBlobsFilter, - blobsGrouperForSubmission = blobsGrouperForSubmission + blobsGrouperForSubmission = blobsGrouperForSubmission, ) } } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelper.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelper.kt index 9c1919da..1f37492e 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelper.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelper.kt @@ -26,7 +26,7 @@ import kotlin.math.min fun chunkBlobs( blobsIntervals: List, aggregations: BlockIntervals, - targetChunkSize: Int + targetChunkSize: Int, ): List> { require(targetChunkSize > 0) { "targetChunkSize must be greater than 0" } assertConsecutiveIntervals(blobsIntervals) @@ -62,7 +62,7 @@ fun chunkBlobs( private fun inconsistentBlobAggregationMessage( blobsIntervals: List, - aggregationsIntervals: List + aggregationsIntervals: List, ): String { return "blobs=${blobsIntervals.toBlockIntervalsString()} are inconsistent with " + "aggregations=${aggregationsIntervals.toBlockIntervalsString()}" @@ -72,13 +72,13 @@ internal fun logSubmissionError( log: Logger, intervalString: String, error: Throwable, - isEthCall: Boolean = false + isEthCall: Boolean = false, ) { logSubmissionError( log, "{} for blob submission failed: blob={} errorMessage={}", intervalString, error, - isEthCall + isEthCall, ) } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitter.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitter.kt index 635150e8..ee835e31 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitter.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitter.kt @@ -5,10 +5,10 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface BlobSubmitter { fun submitBlobs( - blobsChunks: List> + blobsChunks: List>, ): SafeFuture> fun submitBlobCall( - blobRecords: List + blobRecords: List, ): SafeFuture<*> } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitterAsEIP4844MultipleBlobsPerTx.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitterAsEIP4844MultipleBlobsPerTx.kt index 57989716..dcd39a11 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitterAsEIP4844MultipleBlobsPerTx.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmitterAsEIP4844MultipleBlobsPerTx.kt @@ -16,12 +16,12 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( private val contract: LineaRollupSmartContractClient, private val gasPriceCapProvider: GasPriceCapProvider?, private val blobSubmittedEventConsumer: Consumer = Consumer { }, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : BlobSubmitter { private val log: Logger = LogManager.getLogger(this::class.java) override fun submitBlobs( - blobsChunks: List> + blobsChunks: List>, ): SafeFuture> { return blobsChunks .fold(SafeFuture.completedFuture(emptyList())) { chainOfFutures, blobs -> @@ -35,7 +35,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( } private fun submitBlobsInSingleTx( - blobs: List + blobs: List, ): SafeFuture { return ( gasPriceCapProvider?.getGasPriceCaps(blobs.first().startBlockNumber.toLong()) @@ -47,7 +47,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( "submitting blobs: blobs={} nonce={} gasPriceCaps={}", blobs.toBlockIntervalsString(), nonce, - gasPriceCaps + gasPriceCaps, ) contract.submitBlobs(blobs, gasPriceCaps) .whenException { th -> @@ -55,7 +55,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( log, blobs.toBlockIntervalsString(), th, - isEthCall = false + isEthCall = false, ) } .thenPeek { transactionHash -> @@ -64,14 +64,14 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( blobs.toBlockIntervalsString(), transactionHash, nonce, - gasPriceCaps + gasPriceCaps, ) val blobSubmittedEvent = BlobSubmittedEvent( blobs = blobs.map { BlockIntervalData(it.startBlockNumber, it.endBlockNumber) }, endBlockTime = blobs.last().endBlockTime, lastShnarf = blobs.last().expectedShnarf, submissionTimestamp = clock.now(), - transactionHash = transactionHash.toByteArray() + transactionHash = transactionHash.toByteArray(), ) blobSubmittedEventConsumer.accept(blobSubmittedEvent) } @@ -79,7 +79,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( } override fun submitBlobCall( - blobRecords: List + blobRecords: List, ): SafeFuture<*> { return ( gasPriceCapProvider?.getGasPriceCapsWithCoefficient(blobRecords.first().startBlockNumber.toLong()) @@ -91,7 +91,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( "eth_call submitting blobs: blobs={} nonce={} gasPriceCaps={}", blobRecords.toBlockIntervalsString(), nonce, - gasPriceCaps + gasPriceCaps, ) contract.submitBlobsEthCall(blobRecords, gasPriceCaps) .whenException { th -> @@ -102,7 +102,7 @@ class BlobSubmitterAsEIP4844MultipleBlobsPerTx( "eth_call blobs submission passed: blob={} nonce={} gasPriceCaps={}", blobRecords.toBlockIntervalsString(), nonce, - gasPriceCaps + gasPriceCaps, ) } } diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobsGrouperForSubmission.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobsGrouperForSubmission.kt index 47ce8abb..d4b752b8 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobsGrouperForSubmission.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/BlobsGrouperForSubmission.kt @@ -6,16 +6,16 @@ import net.consensys.zkevm.domain.BlobRecord fun interface BlobsGrouperForSubmission { fun chunkBlobs( blobsIntervals: List, - aggregations: BlockIntervals + aggregations: BlockIntervals, ): List> } class BlobsGrouperForSubmissionSwitcherByTargetBock( - private val eip4844TargetBlobsPerTx: UInt = 9U + private val eip4844TargetBlobsPerTx: UInt = 9U, ) : BlobsGrouperForSubmission { override fun chunkBlobs( blobsIntervals: List, - aggregations: BlockIntervals + aggregations: BlockIntervals, ): List> { if (blobsIntervals.isEmpty()) { return emptyList() diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/ContractUpgradeSubmissionLatchFilter.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/ContractUpgradeSubmissionLatchFilter.kt index 275c7a9a..9dbcb60b 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/ContractUpgradeSubmissionLatchFilter.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/ContractUpgradeSubmissionLatchFilter.kt @@ -12,7 +12,7 @@ class ContractUpgradeSubmissionLatchFilter( private val l2SwitchBlockNumber: ULong? = null, private val contractVersionProvider: ContractVersionProvider, private val currentContractVersion: LineaContractVersion, - private val expectedNewContractVersion: LineaContractVersion + private val expectedNewContractVersion: LineaContractVersion, ) : AsyncFilter { private val log = LogManager.getLogger(this::class.java) private val latchEnabled = AtomicBoolean(false) @@ -35,7 +35,7 @@ class ContractUpgradeSubmissionLatchFilter( l2SwitchBlockNumber, items.firstOrNull()?.intervalString(), contractVersion, - expectedNewContractVersion + expectedNewContractVersion, ) } blobs @@ -48,7 +48,7 @@ class ContractUpgradeSubmissionLatchFilter( l2SwitchBlockNumber, items.firstOrNull()?.intervalString(), contractVersion, - expectedNewContractVersion + expectedNewContractVersion, ) } items diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilter.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilter.kt index 70d5216c..c957ca74 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilter.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilter.kt @@ -8,7 +8,7 @@ import java.util.function.Consumer class L1ShnarfBasedAlreadySubmittedBlobsFilter( private val lineaRollup: LineaRollupSmartContractClient, - private val acceptedBlobEndBlockNumberConsumer: Consumer = Consumer { } + private val acceptedBlobEndBlockNumberConsumer: Consumer = Consumer { }, ) : AsyncFilter { /** @@ -19,7 +19,7 @@ class L1ShnarfBasedAlreadySubmittedBlobsFilter( * if blobRecords=[b1, b2, b3, b4, b5, b6] the result will be [b4, b5, b6] */ override fun invoke( - items: List + items: List, ): SafeFuture> { val blockByShnarfQueryFutures = items.map { blobRecord -> lineaRollup diff --git a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelper.kt b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelper.kt index 814fc33b..d73d2722 100644 --- a/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelper.kt +++ b/coordinator/ethereum/blob-submitter/src/main/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelper.kt @@ -19,13 +19,13 @@ private fun rewriteInsufficientGasFeeErrorMessage(errorMessage: String): String? fun logUnhandledError( log: Logger, errorOrigin: String, - error: Throwable + error: Throwable, ) { if (error.message != null) { log.error( "Error from {}: errorMessage={}", errorOrigin, - error.message + error.message, ) } else { log.error("Error from {}: ", errorOrigin, error) @@ -42,7 +42,7 @@ fun logSubmissionError( logMessage: String, intervalString: String, error: Throwable, - isEthCall: Boolean = false + isEthCall: Boolean = false, ) { var matchedInsufficientGasFeeRegex = false val ethMethod = if (isEthCall) "eth_call" else "eth_sendRawTransaction" @@ -61,7 +61,7 @@ fun logSubmissionError( logMessage, ethMethod, intervalString, - errorMessage + errorMessage, ) } else { log.error( @@ -69,7 +69,7 @@ fun logSubmissionError( ethMethod, intervalString, errorMessage, - error + error, ) } } diff --git a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinatorTest.kt b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinatorTest.kt index cbb5bb9a..fdead11b 100644 --- a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinatorTest.kt +++ b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionCoordinatorTest.kt @@ -48,13 +48,13 @@ class BlobSubmissionCoordinatorTest { 79u, 89u, 99u, 109u, 119u, 129u, 139u, 149u, 159u, // Agg2 - 169u, 179u, 189u, 199u - ) - ) + 169u, 179u, 189u, 199u, + ), + ), ) private val aggregations = listOf( createAggregation(startBlockNumber = 1, endBlockNumber = 159), - createAggregation(startBlockNumber = 160, endBlockNumber = 199) + createAggregation(startBlockNumber = 160, endBlockNumber = 199), ) @BeforeEach @@ -71,7 +71,7 @@ class BlobSubmissionCoordinatorTest { blobsGrouperForSubmission = spy(object : BlobsGrouperForSubmission { override fun chunkBlobs( blobsIntervals: List, - aggregations: BlockIntervals + aggregations: BlockIntervals, ): List> = chunkBlobs(blobsIntervals, aggregations, targetChunkSize = 6) }) @@ -85,7 +85,7 @@ class BlobSubmissionCoordinatorTest { pollingInterval = 100.milliseconds, proofSubmissionDelay = 0.seconds, maxBlobsToSubmitPerTick = 200u, - targetBlobsToSubmitPerTx = 9u + targetBlobsToSubmitPerTx = 9u, ), blobsRepository = blobsRepository, aggregationsRepository = aggregationsRepository, @@ -95,8 +95,8 @@ class BlobSubmissionCoordinatorTest { clock = fakeClock, blobSubmissionFilter = blobSubmissionFilter, blobsGrouperForSubmission = blobsGrouperForSubmission, - log = log - ) + log = log, + ), ) whenever(blobsRepository.getConsecutiveBlobsFromBlockNumber(any(), any())) diff --git a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelperKtTest.kt b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelperKtTest.kt index 4cae9c4f..5a144511 100644 --- a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelperKtTest.kt +++ b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/BlobSubmissionHelperKtTest.kt @@ -29,34 +29,34 @@ class BlobSubmissionHelperKtTest { BlockIntervalData(90UL, 99UL), BlockIntervalData(100UL, 109UL), BlockIntervalData(110UL, 119UL), - BlockIntervalData(120UL, 121UL) + BlockIntervalData(120UL, 121UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(69UL, 89UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) + BlockIntervalData(20UL, 29UL), ), listOf( BlockIntervalData(30UL, 39UL), BlockIntervalData(40UL, 49UL), - BlockIntervalData(50UL, 59UL) + BlockIntervalData(50UL, 59UL), ), listOf( - BlockIntervalData(60UL, 69UL) + BlockIntervalData(60UL, 69UL), ), listOf( BlockIntervalData(70UL, 79UL), - BlockIntervalData(80UL, 89UL) - ) - ) + BlockIntervalData(80UL, 89UL), + ), + ), ) } @@ -72,27 +72,27 @@ class BlobSubmissionHelperKtTest { BlockIntervalData(60UL, 69UL), BlockIntervalData(70UL, 79UL), - BlockIntervalData(80UL, 89UL) + BlockIntervalData(80UL, 89UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(300UL, 500UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( BlockIntervalData(10UL, 19UL), BlockIntervalData(20UL, 29UL), - BlockIntervalData(30UL, 39UL) + BlockIntervalData(30UL, 39UL), ), listOf( BlockIntervalData(40UL, 49UL), BlockIntervalData(50UL, 59UL), - BlockIntervalData(60UL, 69UL) - ) - ) + BlockIntervalData(60UL, 69UL), + ), + ), ) } @@ -110,32 +110,32 @@ class BlobSubmissionHelperKtTest { BlockIntervalData(60UL, 69UL), BlockIntervalData(70UL, 79UL), - BlockIntervalData(80UL, 89UL) + BlockIntervalData(80UL, 89UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(59UL, 89UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) + BlockIntervalData(20UL, 29UL), ), listOf( BlockIntervalData(30UL, 39UL), BlockIntervalData(40UL, 49UL), - BlockIntervalData(50UL, 59UL) + BlockIntervalData(50UL, 59UL), ), listOf( BlockIntervalData(60UL, 69UL), BlockIntervalData(70UL, 79UL), - BlockIntervalData(80UL, 89UL) - ) - ) + BlockIntervalData(80UL, 89UL), + ), + ), ) } @@ -147,26 +147,26 @@ class BlobSubmissionHelperKtTest { BlockIntervalData(20UL, 29UL), BlockIntervalData(30UL, 39UL), - BlockIntervalData(40UL, 49UL) + BlockIntervalData(40UL, 49UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(49UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) + BlockIntervalData(20UL, 29UL), ), listOf( BlockIntervalData(30UL, 39UL), - BlockIntervalData(40UL, 49UL) - ) - ) + BlockIntervalData(40UL, 49UL), + ), + ), ) } @@ -185,30 +185,30 @@ class BlobSubmissionHelperKtTest { BlockIntervalData(60UL, 69UL), BlockIntervalData(70UL, 79UL), - BlockIntervalData(80UL, 89UL) + BlockIntervalData(80UL, 89UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(9UL, 500UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( - BlockIntervalData(0UL, 9UL) + BlockIntervalData(0UL, 9UL), ), listOf( BlockIntervalData(10UL, 19UL), BlockIntervalData(20UL, 29UL), - BlockIntervalData(30UL, 39UL) + BlockIntervalData(30UL, 39UL), ), listOf( BlockIntervalData(40UL, 49UL), BlockIntervalData(50UL, 59UL), - BlockIntervalData(60UL, 69UL) - ) - ) + BlockIntervalData(60UL, 69UL), + ), + ), ) } @@ -219,20 +219,20 @@ class BlobSubmissionHelperKtTest { // agg: 0, 9 BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) + BlockIntervalData(20UL, 29UL), ) val result = chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(9UL, 500UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) assertThat(result).isEqualTo( listOf( listOf( - BlockIntervalData(0UL, 9UL) - ) - ) + BlockIntervalData(0UL, 9UL), + ), + ), ) } @@ -241,14 +241,14 @@ class BlobSubmissionHelperKtTest { val blobs = listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) + BlockIntervalData(20UL, 29UL), ) assertThrows { chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(15UL, 29UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) }.let { error -> assertThat(error).hasMessageMatching("blobs.* are inconsistent with aggregations.*") @@ -258,7 +258,7 @@ class BlobSubmissionHelperKtTest { chunkBlobs( blobs, aggregations = BlockIntervals(startingBlockNumber = 0UL, listOf(9UL, 21UL)), - targetChunkSize = 3 + targetChunkSize = 3, ) }.let { error -> assertThat(error).hasMessageMatching("blobs.* are inconsistent with aggregations.*") diff --git a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilterTest.kt b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilterTest.kt index adee1087..db0f22df 100644 --- a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilterTest.kt +++ b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/L1ShnarfBasedAlreadySubmittedBlobsFilterTest.kt @@ -42,7 +42,7 @@ class L1ShnarfBasedAlreadySubmittedBlobsFilterTest { val acceptedBlobEndBlockNumberConsumer = Consumer { acceptedBlob = it } val blobsFilter = L1ShnarfBasedAlreadySubmittedBlobsFilter( lineaRollup = l1SmcClient, - acceptedBlobEndBlockNumberConsumer = acceptedBlobEndBlockNumberConsumer + acceptedBlobEndBlockNumberConsumer = acceptedBlobEndBlockNumberConsumer, ) val filteredBlobs = blobsFilter.invoke(blobs).get() diff --git a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelperTest.kt b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelperTest.kt index b288799a..67874085 100644 --- a/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelperTest.kt +++ b/coordinator/ethereum/blob-submitter/src/test/kotlin/net/consensys/zkevm/ethereum/submission/LoggingHelperTest.kt @@ -44,7 +44,7 @@ class LoggingHelperTest { logMessage = blobSubmissionFailedLogMsg, intervalString = blobSubmissionFailedIntervalStr, error = error, - isEthCall = true + isEthCall = true, ) val expectedErrorMessage = "maxFeePerGas less than block base fee:" + @@ -55,7 +55,7 @@ class LoggingHelperTest { eq(blobSubmissionFailedLogMsg), eq("eth_call"), eq(blobSubmissionFailedIntervalStr), - eq(expectedErrorMessage) + eq(expectedErrorMessage), ) } @@ -67,7 +67,7 @@ class LoggingHelperTest { logMessage = blobSubmissionFailedLogMsg, intervalString = blobSubmissionFailedIntervalStr, error = error, - isEthCall = true + isEthCall = true, ) val expectedErrorMessage = "maxFeePerBlobGas less than block blob gas fee:" + @@ -78,7 +78,7 @@ class LoggingHelperTest { eq(blobSubmissionFailedLogMsg), eq("eth_call"), eq(blobSubmissionFailedIntervalStr), - eq(expectedErrorMessage) + eq(expectedErrorMessage), ) } @@ -90,7 +90,7 @@ class LoggingHelperTest { logMessage = blobSubmissionFailedLogMsg, intervalString = blobSubmissionFailedIntervalStr, error = error, - isEthCall = false + isEthCall = false, ) verify(logger).error( @@ -98,7 +98,7 @@ class LoggingHelperTest { eq("eth_sendRawTransaction"), eq(blobSubmissionFailedIntervalStr), eq(insufficientMaxFeePerGasErrMsg), - eq(error) + eq(error), ) } @@ -110,7 +110,7 @@ class LoggingHelperTest { logMessage = blobSubmissionFailedLogMsg, intervalString = blobSubmissionFailedIntervalStr, error = error, - isEthCall = false + isEthCall = false, ) verify(logger).error( @@ -118,7 +118,7 @@ class LoggingHelperTest { eq("eth_sendRawTransaction"), eq(blobSubmissionFailedIntervalStr), eq(insufficientMaxFeePerBlobGasErrMsg), - eq(error) + eq(error), ) } @@ -130,7 +130,7 @@ class LoggingHelperTest { logMessage = blobSubmissionFailedLogMsg, intervalString = blobSubmissionFailedIntervalStr, error = error, - isEthCall = true + isEthCall = true, ) verify(logger).error( @@ -138,7 +138,7 @@ class LoggingHelperTest { eq("eth_call"), eq(blobSubmissionFailedIntervalStr), eq(unknownErrMsg), - eq(error) + eq(error), ) } } diff --git a/coordinator/ethereum/common/src/main/kotlin/net/consensys/zkevm/ethereum/error/handling/ErrorHandling.kt b/coordinator/ethereum/common/src/main/kotlin/net/consensys/zkevm/ethereum/error/handling/ErrorHandling.kt index 3ad98f16..25c4f46d 100644 --- a/coordinator/ethereum/common/src/main/kotlin/net/consensys/zkevm/ethereum/error/handling/ErrorHandling.kt +++ b/coordinator/ethereum/common/src/main/kotlin/net/consensys/zkevm/ethereum/error/handling/ErrorHandling.kt @@ -7,7 +7,7 @@ object ErrorHandling { fun handleError( messagePrefix: String, error: Throwable, - ethCall: () -> SafeFuture<*> + ethCall: () -> SafeFuture<*>, ): SafeFuture { return ethCall().handleException { errorWithRevertReason -> val txHash = extractTransactionHashFromErrorMessage(error.message!!) diff --git a/coordinator/ethereum/finalization-monitor/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImpl.kt b/coordinator/ethereum/finalization-monitor/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImpl.kt index 230077c6..85b0432f 100644 --- a/coordinator/ethereum/finalization-monitor/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImpl.kt +++ b/coordinator/ethereum/finalization-monitor/src/main/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImpl.kt @@ -21,20 +21,20 @@ class FinalizationMonitorImpl( private val contract: LineaRollupSmartContractClientReadOnly, private val l2Client: Web3j, private val vertx: Vertx, - private val log: Logger = LogManager.getLogger(FinalizationMonitor::class.java) + private val log: Logger = LogManager.getLogger(FinalizationMonitor::class.java), ) : FinalizationMonitor, PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { data class Config( val pollingInterval: Duration = 500.milliseconds, - val l1QueryBlockTag: BlockParameter.Tag = BlockParameter.Tag.FINALIZED + val l1QueryBlockTag: BlockParameter.Tag = BlockParameter.Tag.FINALIZED, ) private val finalizationHandlers: MutableMap = - Collections.synchronizedMap(LinkedHashMap()) + Collections.synchronizedMap(LinkedHashMap()) private val lastFinalizationUpdate = AtomicReference(null) override fun handleError(error: Throwable) { @@ -55,7 +55,7 @@ class FinalizationMonitorImpl( log.info( "finalization update: previousFinalizedBlock={} newFinalizedBlock={}", lastFinalizationUpdate.get().blockNumber, - currentState + currentState, ) lastFinalizationUpdate.set(currentState) onUpdate(currentState) @@ -75,13 +75,13 @@ class FinalizationMonitorImpl( .thenCombine( contract.blockStateRootHash( blockParameter = config.l1QueryBlockTag, - lineaL2BlockNumber = lineaFinalizedBlockNumber - ) + lineaL2BlockNumber = lineaFinalizedBlockNumber, + ), ) { finalizedBlock, stateRootHash -> FinalizationMonitor.FinalizationUpdate( lineaFinalizedBlockNumber, Bytes32.wrap(stateRootHash), - Bytes32.fromHexString(finalizedBlock.block.hash) + Bytes32.fromHexString(finalizedBlock.block.hash), ) } } @@ -95,7 +95,7 @@ class FinalizationMonitorImpl( log.trace( "calling finalization handler: handler={} update={}", handlerName, - finalizationUpdate.blockNumber + finalizationUpdate.blockNumber, ) try { finalizationHandler.handleUpdate(finalizationUpdate) @@ -114,7 +114,7 @@ class FinalizationMonitorImpl( override fun addFinalizationHandler( handlerName: String, - handler: FinalizationHandler + handler: FinalizationHandler, ) { synchronized(finalizationHandlers) { finalizationHandlers[handlerName] = handler diff --git a/coordinator/ethereum/finalization-monitor/src/test/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImplTest.kt b/coordinator/ethereum/finalization-monitor/src/test/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImplTest.kt index aa48d0ff..68db44dd 100644 --- a/coordinator/ethereum/finalization-monitor/src/test/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImplTest.kt +++ b/coordinator/ethereum/finalization-monitor/src/test/kotlin/net/consensys/zkevm/ethereum/finalization/FinalizationMonitorImplTest.kt @@ -71,7 +71,7 @@ class FinalizationMonitorImplTest { config = config, contract = contractMock, l2Client = mockL2Client, - vertx = vertx + vertx = vertx, ) finalizationMonitorImpl .start() @@ -114,7 +114,7 @@ class FinalizationMonitorImplTest { config = config, contract = contractMock, l2Client = mockL2Client, - vertx = vertx + vertx = vertx, ) val updatesReceived1 = mutableListOf() val updatesReceived2 = mutableListOf() @@ -152,7 +152,7 @@ class FinalizationMonitorImplTest { @Test fun finalizationUpdatesDontCrashTheWholeMonitorInCaseOfErrors( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { var blockNumber = 0 whenever(contractMock.finalizedL2BlockNumber(any())).thenAnswer { @@ -177,7 +177,7 @@ class FinalizationMonitorImplTest { config = config, contract = contractMock, l2Client = mockL2Client, - vertx = vertx + vertx = vertx, ) val updatesReceived = CopyOnWriteArrayList() val numberOfEventsBeforeError = AtomicInteger(0) @@ -248,7 +248,7 @@ class FinalizationMonitorImplTest { config = config, contract = contractMock, l2Client = mockL2Client, - vertx = vertx + vertx = vertx, ) finalizationMonitorImpl.addFinalizationHandler("handler1") { @@ -292,7 +292,7 @@ class FinalizationMonitorImplTest { config = config.copy(pollingInterval = pollingInterval * 2), contract = contractMock, l2Client = mockL2Client, - vertx = vertx + vertx = vertx, ) val updatesReceived = CopyOnWriteArrayList>() @@ -331,7 +331,7 @@ class FinalizationMonitorImplTest { assertThat( updatesReceived.windowed(3, 3).all { finalizationUpdates -> finalizationUpdates.map { it.second } == listOf(handlerName1, handlerName2, handlerName3) - } + }, ) .overridingErrorMessage("Updates aren't in the right order! $updatesReceived") .isTrue() diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/DynamicGasPriceCap.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/DynamicGasPriceCap.kt index 0fef5bf5..b0dce041 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/DynamicGasPriceCap.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/DynamicGasPriceCap.kt @@ -14,7 +14,7 @@ val MAX_FEE_HISTORIES_STORAGE_PERIOD = 30.days data class PercentileGasFees( val percentileBaseFeePerGas: ULong, val percentileBaseFeePerBlobGas: ULong, - val percentileAvgReward: ULong + val percentileAvgReward: ULong, ) { override fun toString(): String { return "percentileBaseFeePerGas=${percentileBaseFeePerGas.toGWei()} GWei," + @@ -46,7 +46,7 @@ interface GasPriceCapCalculator { finalizationTargetMaxDelay: Duration, historicGasPriceCap: ULong, elapsedTimeSinceBlockTimestamp: Duration, - timeOfDayMultiplier: Double = 1.0 + timeOfDayMultiplier: Double = 1.0, ): ULong } @@ -55,14 +55,14 @@ interface GasPriceCapFeeHistoryCache { fun cacheNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun getCachedPercentileGasFees(): PercentileGasFees fun cachePercentileGasFees( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoriesRepository.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoriesRepository.kt index c10cad19..46df982a 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoriesRepository.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoriesRepository.kt @@ -8,29 +8,29 @@ interface FeeHistoriesRepository { fun findBaseFeePerGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findBaseFeePerBlobGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findAverageRewardAtPercentile( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findHighestBlockNumberWithPercentile( - rewardPercentile: Double + rewardPercentile: Double, ): SafeFuture fun getNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive: Long + blockNumberInclusive: Long, ): SafeFuture } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingService.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingService.kt index 430ed63b..0e8795cc 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingService.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingService.kt @@ -14,11 +14,11 @@ class FeeHistoryCachingService( private val web3jClient: Web3j, private val feeHistoryFetcher: GasPriceCapFeeHistoryFetcher, private val feeHistoriesRepository: FeeHistoriesRepositoryWithCache, - private val log: Logger = LogManager.getLogger(FeeHistoryCachingService::class.java) + private val log: Logger = LogManager.getLogger(FeeHistoryCachingService::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { data class Config( val pollingInterval: Duration, @@ -26,7 +26,7 @@ class FeeHistoryCachingService( val gasFeePercentile: Double, val feeHistoryWindowInBlocks: UInt, val feeHistoryStoragePeriodInBlocks: UInt, - val numOfBlocksBeforeLatest: UInt + val numOfBlocksBeforeLatest: UInt, ) private fun fetchAndSaveFeeHistories(maxL1BlockNumberToFetch: Long): SafeFuture { @@ -34,7 +34,7 @@ class FeeHistoryCachingService( .coerceAtLeast(0L).inc() return feeHistoriesRepository.findHighestBlockNumberWithPercentile( - config.gasFeePercentile + config.gasFeePercentile, ) .thenCompose { val highestStoredL1BlockNumber = it ?: 0L @@ -51,14 +51,14 @@ class FeeHistoryCachingService( } else { feeHistoryFetcher.getEthFeeHistoryData( startBlockNumberInclusive = startBlockNumberInclusive, - endBlockNumberInclusive = endBlockNumberInclusive + endBlockNumberInclusive = endBlockNumberInclusive, ).thenCompose { feeHistory -> feeHistoriesRepository.saveNewFeeHistory(feeHistory) }.thenCompose { if (endBlockNumberInclusive == maxL1BlockNumberToFetch) { feeHistoriesRepository.cachePercentileGasFees( percentile = config.gasFeePercentile, - fromBlockNumber = minFromBlockNumberInclusive + fromBlockNumber = minFromBlockNumberInclusive, ) } else { SafeFuture.completedFuture(Unit) @@ -69,16 +69,16 @@ class FeeHistoryCachingService( log.warn( "failure occurred when fetch and save fee histories but will be ignored: errorMessage={}", th.message, - th + th, ) }.alwaysRun { feeHistoriesRepository.deleteFeeHistoriesUpToBlockNumber( maxL1BlockNumberToFetch.minus(config.feeHistoryStoragePeriodInBlocks.toLong()) - .coerceAtLeast(0L) + .coerceAtLeast(0L), ).thenCompose { feeHistoriesRepository.cacheNumOfFeeHistoriesFromBlockNumber( rewardPercentile = config.gasFeePercentile, - fromBlockNumber = minFromBlockNumberInclusive + fromBlockNumber = minFromBlockNumberInclusive, ) } } @@ -93,7 +93,7 @@ class FeeHistoryCachingService( // from nodes that were not catching up with the head yet maxL1BlockNumberToFetch = latestL1BlockNumber.blockNumber.toLong() .minus(config.numOfBlocksBeforeLatest.toLong()) - .coerceAtLeast(1L) + .coerceAtLeast(1L), ) } } @@ -102,7 +102,7 @@ class FeeHistoryCachingService( log.error( "Error with fee history caching service: errorMessage={}", error.message, - error + error, ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImpl.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImpl.kt index 6d84606e..8678d9d8 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImpl.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImpl.kt @@ -13,7 +13,7 @@ class GasPriceCapCalculatorImpl : GasPriceCapCalculator { adjustmentConstant: UInt, finalizationTargetMaxDelay: Duration, elapsedTimeSinceBlockTimestamp: Duration, - timeOfDayMultiplier: Double + timeOfDayMultiplier: Double, ): Double { val finalizationDelayMultiplier = elapsedTimeSinceBlockTimestamp.inWholeSeconds.toDouble() .div(finalizationTargetMaxDelay.inWholeSeconds.toDouble()).pow(2) @@ -27,7 +27,7 @@ class GasPriceCapCalculatorImpl : GasPriceCapCalculator { finalizationTargetMaxDelay: Duration, historicGasPriceCap: ULong, elapsedTimeSinceBlockTimestamp: Duration, - timeOfDayMultiplier: Double + timeOfDayMultiplier: Double, ): ULong { require(finalizationTargetMaxDelay > Duration.ZERO) { "finalizationTargetMaxDelay duration must be longer than zero second." + @@ -38,7 +38,7 @@ class GasPriceCapCalculatorImpl : GasPriceCapCalculator { adjustmentConstant, finalizationTargetMaxDelay, elapsedTimeSinceBlockTimestamp, - timeOfDayMultiplier + timeOfDayMultiplier, ) val gasPriceCap = historicGasPriceCap.toDouble() * overallMultiplier @@ -54,7 +54,7 @@ class GasPriceCapCalculatorImpl : GasPriceCapCalculator { finalizationTargetMaxDelay.inWholeSeconds, elapsedTimeSinceBlockTimestamp.inWholeSeconds, timeOfDayMultiplier, - overallMultiplier + overallMultiplier, ) return gasPriceCap.toULong() diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImpl.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImpl.kt index b5de50e2..ec5f77da 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImpl.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImpl.kt @@ -10,13 +10,13 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class GasPriceCapFeeHistoryFetcherImpl( private val web3jService: Web3jBlobExtended, - private val config: Config + private val config: Config, ) : GasPriceCapFeeHistoryFetcher { private val log: Logger = LogManager.getLogger(this::class.java) data class Config( val maxBlockCount: UInt, - val rewardPercentiles: List + val rewardPercentiles: List, ) { init { require(rewardPercentiles.isNotEmpty()) { @@ -37,8 +37,8 @@ class GasPriceCapFeeHistoryFetcherImpl( web3jService.ethFeeHistoryWithBlob( blockCount, newestBlock, - config.rewardPercentiles - ).sendAsync() + config.rewardPercentiles, + ).sendAsync(), ).thenApply { if (it.hasError()) { throw Exception(it.error.message) @@ -50,7 +50,7 @@ class GasPriceCapFeeHistoryFetcherImpl( override fun getEthFeeHistoryData( startBlockNumberInclusive: Long, - endBlockNumberInclusive: Long + endBlockNumberInclusive: Long, ): SafeFuture { require(endBlockNumberInclusive >= startBlockNumberInclusive) { "endBlockNumberInclusive=$endBlockNumberInclusive must be equal or higher " + @@ -72,7 +72,7 @@ class GasPriceCapFeeHistoryFetcherImpl( startBlockNumberInclusive, endBlockNumberInclusive, newestBlock.blockNumber, - blockCount + blockCount, ) return getFeeHistory(newestBlock, blockCount) diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmission.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmission.kt index 8cfc82dd..c23cc4b7 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmission.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmission.kt @@ -10,12 +10,12 @@ import java.util.concurrent.atomic.AtomicReference class GasPriceCapProviderForDataSubmission( private val config: Config, private val gasPriceCapProvider: GasPriceCapProvider, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ) : GasPriceCapProvider { data class Config( val maxPriorityFeePerGasCap: ULong, val maxFeePerGasCap: ULong, - val maxFeePerBlobGasCap: ULong + val maxFeePerBlobGasCap: ULong, ) private var lastGasPriceCap: AtomicReference = AtomicReference(null) @@ -36,19 +36,19 @@ class GasPriceCapProviderForDataSubmission( category = LineaMetricsCategory.GAS_PRICE_CAP, name = "l1.blobsubmission.maxpriorityfeepergascap", description = "Max priority fee per gas cap for blob submission on L1", - measurementSupplier = { lastGasPriceCap.get()?.maxPriorityFeePerGasCap?.toLong() ?: 0 } + measurementSupplier = { lastGasPriceCap.get()?.maxPriorityFeePerGasCap?.toLong() ?: 0 }, ) metricsFacade.createGauge( category = LineaMetricsCategory.GAS_PRICE_CAP, name = "l1.blobsubmission.maxfeepergascap", description = "Max fee per gas cap for blob submission on L1", - measurementSupplier = { lastGasPriceCap.get()?.maxFeePerGasCap?.toLong() ?: 0 } + measurementSupplier = { lastGasPriceCap.get()?.maxFeePerGasCap?.toLong() ?: 0 }, ) metricsFacade.createGauge( category = LineaMetricsCategory.GAS_PRICE_CAP, name = "l1.blobsubmission.maxfeeperblobgascap", description = "Max fee per blob gas cap for blob submission on L1", - measurementSupplier = { lastGasPriceCap.get()?.maxFeePerBlobGasCap?.toLong() ?: 0 } + measurementSupplier = { lastGasPriceCap.get()?.maxFeePerBlobGasCap?.toLong() ?: 0 }, ) } @@ -74,7 +74,7 @@ class GasPriceCapProviderForDataSubmission( return GasPriceCaps( maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap + maxFeePerBlobGasCap = maxFeePerBlobGasCap, ) } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalization.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalization.kt index 6bcd9192..934e4183 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalization.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalization.kt @@ -10,12 +10,12 @@ import java.util.concurrent.atomic.AtomicReference class GasPriceCapProviderForFinalization( private val config: Config, private val gasPriceCapProvider: GasPriceCapProvider, - metricsFacade: MetricsFacade + metricsFacade: MetricsFacade, ) : GasPriceCapProvider { data class Config( val maxPriorityFeePerGasCap: ULong, val maxFeePerGasCap: ULong, - val gasPriceCapMultiplier: Double = 1.0 + val gasPriceCapMultiplier: Double = 1.0, ) private var lastGasPriceCap: AtomicReference = AtomicReference(null) @@ -36,14 +36,14 @@ class GasPriceCapProviderForFinalization( category = LineaMetricsCategory.GAS_PRICE_CAP, name = "l1.finalization.maxpriorityfeepergascap", description = "Max priority fee per gas cap for finalization on L1", - measurementSupplier = { lastGasPriceCap.get()?.maxPriorityFeePerGasCap?.toLong() ?: 0 } + measurementSupplier = { lastGasPriceCap.get()?.maxPriorityFeePerGasCap?.toLong() ?: 0 }, ) metricsFacade.createGauge( category = LineaMetricsCategory.GAS_PRICE_CAP, name = "l1.finalization.maxfeepergascap", description = "Max fee per gas cap for finalization on L1", - measurementSupplier = { lastGasPriceCap.get()?.maxFeePerGasCap?.toLong() ?: 0 } + measurementSupplier = { lastGasPriceCap.get()?.maxFeePerGasCap?.toLong() ?: 0 }, ) } @@ -68,7 +68,7 @@ class GasPriceCapProviderForFinalization( return GasPriceCaps( maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, maxFeePerGasCap = maxFeePerGasCap, - maxFeePerBlobGasCap = 0uL + maxFeePerBlobGasCap = 0uL, ) } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImpl.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImpl.kt index 4c6ae8c4..df72d88b 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImpl.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImpl.kt @@ -20,7 +20,7 @@ class GasPriceCapProviderImpl( private val l2ExtendedWeb3JClient: ExtendedWeb3J, private val feeHistoriesRepository: FeeHistoriesRepositoryWithCache, private val gasPriceCapCalculator: GasPriceCapCalculator, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : GasPriceCapProvider { data class Config( val enabled: Boolean, @@ -31,7 +31,7 @@ class GasPriceCapProviderImpl( val adjustmentConstant: UInt, val blobAdjustmentConstant: UInt, val finalizationTargetMaxDelay: Duration, - val gasPriceCapsCoefficient: Double + val gasPriceCapsCoefficient: Double, ) private val log: Logger = LogManager.getLogger(this::class.java) @@ -65,7 +65,7 @@ class GasPriceCapProviderImpl( "Not enough fee history data for gas price cap update: numOfValidFeeHistoriesInDb={}, " + "minNumOfFeeHistoriesNeeded={}", numOfValidFeeHistories, - minNumOfFeeHistoriesNeeded + minNumOfFeeHistoriesNeeded, ) } return isEnoughData @@ -82,7 +82,7 @@ class GasPriceCapProviderImpl( } private fun calculateGasPriceCapsHelper( - targetL2BlockNumber: Long + targetL2BlockNumber: Long, ): SafeFuture { return if (isEnoughDataForGasPriceCapCalculation()) { l2ExtendedWeb3JClient.ethGetBlockTimestampByNumber(targetL2BlockNumber).thenApply { @@ -94,26 +94,26 @@ class GasPriceCapProviderImpl( finalizationTargetMaxDelay = config.finalizationTargetMaxDelay, historicGasPriceCap = percentileGasFees.percentileAvgReward, elapsedTimeSinceBlockTimestamp = elapsedTimeSinceBlockTimestamp, - timeOfDayMultiplier = getTimeOfDayMultiplierForNow(config.timeOfDayMultipliers) + timeOfDayMultiplier = getTimeOfDayMultiplierForNow(config.timeOfDayMultipliers), ) val maxBaseFeePerGasCap = gasPriceCapCalculator.calculateGasPriceCap( adjustmentConstant = config.adjustmentConstant, finalizationTargetMaxDelay = config.finalizationTargetMaxDelay, historicGasPriceCap = percentileGasFees.percentileBaseFeePerGas, elapsedTimeSinceBlockTimestamp = elapsedTimeSinceBlockTimestamp, - timeOfDayMultiplier = getTimeOfDayMultiplierForNow(config.timeOfDayMultipliers) + timeOfDayMultiplier = getTimeOfDayMultiplierForNow(config.timeOfDayMultipliers), ) val maxFeePerBlobGasCap = gasPriceCapCalculator.calculateGasPriceCap( adjustmentConstant = config.blobAdjustmentConstant, finalizationTargetMaxDelay = config.finalizationTargetMaxDelay, historicGasPriceCap = percentileGasFees.percentileBaseFeePerBlobGas, - elapsedTimeSinceBlockTimestamp = elapsedTimeSinceBlockTimestamp + elapsedTimeSinceBlockTimestamp = elapsedTimeSinceBlockTimestamp, ) GasPriceCaps( maxBaseFeePerGasCap = maxBaseFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, maxFeePerGasCap = maxPriorityFeePerGasCap + maxBaseFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap + maxFeePerBlobGasCap = maxFeePerBlobGasCap, ) }.thenPeek { gasPriceCaps -> log.debug( @@ -124,14 +124,14 @@ class GasPriceCapProviderImpl( gasPriceCaps.maxPriorityFeePerGasCap.toGWei(), gasPriceCaps.maxFeePerGasCap.toGWei(), gasPriceCaps.maxFeePerBlobGasCap.toGWei(), - config.gasFeePercentile + config.gasFeePercentile, ) }.exceptionallyCompose { th -> log.error( "Gas price caps returned as null due to failure occurred: " + "errorMessage={}", th.message, - th + th, ) SafeFuture.completedFuture(null) } @@ -143,7 +143,7 @@ class GasPriceCapProviderImpl( private fun calculateGasPriceCaps(targetL2BlockNumber: Long): SafeFuture { return if (config.enabled) { calculateGasPriceCapsHelper( - targetL2BlockNumber = targetL2BlockNumber + targetL2BlockNumber = targetL2BlockNumber, ) } else { SafeFuture.completedFuture(null) @@ -165,7 +165,7 @@ class GasPriceCapProviderImpl( maxBaseFeePerGasCap = multipliedMaxBaseFeePerGasCap.toULong(), maxPriorityFeePerGasCap = multipliedMaxPriorityFeePerGas.toULong(), maxFeePerGasCap = (multipliedMaxBaseFeePerGasCap + multipliedMaxPriorityFeePerGas).toULong(), - maxFeePerBlobGasCap = multipliedMaxFeePerBlobGasCap.toULong() + maxFeePerBlobGasCap = multipliedMaxFeePerBlobGasCap.toULong(), ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingServiceTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingServiceTest.kt index 5a071a1c..5689f568 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingServiceTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/FeeHistoryCachingServiceTest.kt @@ -38,7 +38,7 @@ class FeeHistoryCachingServiceTest { reward = listOf(2000, 2100, 2200, 2300, 2400).map { listOf(it.toULong().times(OneMWei)) }, gasUsedRatio = listOf(0.2, 0.4, 0.6, 0.8, 1.0).map { it }, baseFeePerBlobGas = listOf(100, 110, 120, 130, 140, 150).map { it.toULong().times(OneMWei) }, - blobGasUsedRatio = listOf(0.5, 0.333, 0.167, 1.0, 0.667).map { it } + blobGasUsedRatio = listOf(0.5, 0.333, 0.167, 1.0, 0.667).map { it }, ) private val highestStoredL1BlockNumber = 100L private val latestL1BlockNumber = 200L @@ -56,7 +56,7 @@ class FeeHistoryCachingServiceTest { private fun createFeeHistoryCachingService( vertx: Vertx, - mockedL1FeeHistoriesRepository: FeeHistoriesRepositoryWithCache + mockedL1FeeHistoriesRepository: FeeHistoriesRepositoryWithCache, ): FeeHistoryCachingService { return FeeHistoryCachingService( config = FeeHistoryCachingService.Config( @@ -65,12 +65,12 @@ class FeeHistoryCachingServiceTest { gasFeePercentile = gasFeePercentile, feeHistoryStoragePeriodInBlocks = feeHistoryStoragePeriodInBlocks, feeHistoryWindowInBlocks = feeHistoryWindowInBlocks, - numOfBlocksBeforeLatest = numOfBlocksBeforeLatest + numOfBlocksBeforeLatest = numOfBlocksBeforeLatest, ), vertx = vertx, web3jClient = mockedL1Web3jClient, feeHistoryFetcher = mockedL1FeeHistoryFetcher, - feeHistoriesRepository = mockedL1FeeHistoriesRepository + feeHistoriesRepository = mockedL1FeeHistoriesRepository, ) } @@ -92,7 +92,7 @@ class FeeHistoryCachingServiceTest { on { cachePercentileGasFees(any(), any()) } doReturn SafeFuture.completedFuture(Unit) on { deleteFeeHistoriesUpToBlockNumber(any()) } doReturn SafeFuture.completedFuture(deletedFeeHistoriesNum) on { cacheNumOfFeeHistoriesFromBlockNumber(any(), any()) } doReturn SafeFuture.completedFuture( - storedFeeHistoriesNum + storedFeeHistoriesNum, ) } } @@ -107,27 +107,27 @@ class FeeHistoryCachingServiceTest { .untilAsserted { verify(mockedL1Web3jClient, atLeast(2)).ethBlockNumber() verify(mockedL1FeeHistoriesRepository, atLeastOnce()).findHighestBlockNumberWithPercentile( - gasFeePercentile + gasFeePercentile, ) verify(mockedL1FeeHistoryFetcher, atLeast(2)).getEthFeeHistoryData( latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L, - latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + feeHistoryMaxBlockCount.toLong() + latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + feeHistoryMaxBlockCount.toLong(), ) verify(mockedL1FeeHistoriesRepository, atLeast(2)).saveNewFeeHistory( - feeHistory + feeHistory, ) verify(mockedL1FeeHistoriesRepository, atLeast(2)).cachePercentileGasFees( gasFeePercentile, - latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L + latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L, ) verify(mockedL1FeeHistoriesRepository, atLeast(2)) .deleteFeeHistoriesUpToBlockNumber( - latestL1BlockNumber - feeHistoryStoragePeriodInBlocks.toLong() + latestL1BlockNumber - feeHistoryStoragePeriodInBlocks.toLong(), ) verify(mockedL1FeeHistoriesRepository, atLeast(2)) .cacheNumOfFeeHistoriesFromBlockNumber( gasFeePercentile, - latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L + latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L, ) } testContext.completeNow() @@ -139,11 +139,11 @@ class FeeHistoryCachingServiceTest { fun start_alwaysDeleteFeeHistoriesWhenError(vertx: Vertx, testContext: VertxTestContext) { mockedL1FeeHistoriesRepository = mock { on { findHighestBlockNumberWithPercentile(any()) } doReturn SafeFuture.failedFuture( - Error("Throw error for testing") + Error("Throw error for testing"), ) on { deleteFeeHistoriesUpToBlockNumber(any()) } doReturn SafeFuture.completedFuture(deletedFeeHistoriesNum) on { cacheNumOfFeeHistoriesFromBlockNumber(any(), any()) } doReturn SafeFuture.completedFuture( - storedFeeHistoriesNum + storedFeeHistoriesNum, ) } createFeeHistoryCachingService(vertx, mockedL1FeeHistoriesRepository).start() @@ -154,12 +154,12 @@ class FeeHistoryCachingServiceTest { verify(mockedL1Web3jClient, atLeast(2)).ethBlockNumber() verify(mockedL1FeeHistoriesRepository, atLeast(2)) .deleteFeeHistoriesUpToBlockNumber( - latestL1BlockNumber - feeHistoryStoragePeriodInBlocks.toLong() + latestL1BlockNumber - feeHistoryStoragePeriodInBlocks.toLong(), ) verify(mockedL1FeeHistoriesRepository, atLeast(2)) .cacheNumOfFeeHistoriesFromBlockNumber( gasFeePercentile, - latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L + latestL1BlockNumber - feeHistoryWindowInBlocks.toLong() + 1L, ) } testContext.completeNow() diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImplTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImplTest.kt index 24eb7858..a45b7188 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImplTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapCalculatorImplTest.kt @@ -21,7 +21,7 @@ class GasPriceCapCalculatorImplTest { finalizationTargetMaxDelay = 32.hours, historicGasPriceCap = 1000000000uL, // 1GWei elapsedTimeSinceBlockTimestamp = 1.hours, - timeOfDayMultiplier = 1.75 // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml + timeOfDayMultiplier = 1.75, // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml ) assertThat(calculatedGasPriceCap).isEqualTo(1042724609uL) } @@ -38,7 +38,7 @@ class GasPriceCapCalculatorImplTest { finalizationTargetMaxDelay = 32.hours, historicGasPriceCap = 1000000000uL, // 1GWei elapsedTimeSinceBlockTimestamp = 16.hours, - timeOfDayMultiplier = 1.75 // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml + timeOfDayMultiplier = 1.75, // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml ) assertThat(calculatedGasPriceCap).isEqualTo(11937500000uL) } @@ -55,7 +55,7 @@ class GasPriceCapCalculatorImplTest { finalizationTargetMaxDelay = 32.hours, historicGasPriceCap = 1000000000uL, // 1GWei elapsedTimeSinceBlockTimestamp = 32.hours, - timeOfDayMultiplier = 1.75 // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml + timeOfDayMultiplier = 1.75, // i.e. SUNDAY_2 in config/common/gas-price-cap-time-of-day-multipliers.toml ) assertThat(calculatedGasPriceCap).isEqualTo(44750000000uL) } @@ -71,7 +71,7 @@ class GasPriceCapCalculatorImplTest { adjustmentConstant = 25U, finalizationTargetMaxDelay = 32.hours, historicGasPriceCap = 1000000000uL, // 1GWei - elapsedTimeSinceBlockTimestamp = 32.hours + elapsedTimeSinceBlockTimestamp = 32.hours, // timeOfDayMultiplier = 1.0 as default ) assertThat(calculatedGasPriceCap).isEqualTo(26000000000uL) @@ -84,12 +84,12 @@ class GasPriceCapCalculatorImplTest { adjustmentConstant = 25U, finalizationTargetMaxDelay = 0.hours, historicGasPriceCap = 1000000000uL, // 1GWei - elapsedTimeSinceBlockTimestamp = 32.hours + elapsedTimeSinceBlockTimestamp = 32.hours, ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "finalizationTargetMaxDelay duration must be longer than zero second. Value=0s" + "finalizationTargetMaxDelay duration must be longer than zero second. Value=0s", ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImplTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImplTest.kt index d343f575..e3a13683 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImplTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapFeeHistoryFetcherImplTest.kt @@ -26,12 +26,12 @@ class GasPriceCapFeeHistoryFetcherImplTest { @Timeout(10, timeUnit = TimeUnit.SECONDS) fun getEthFeeHistoryData_returnsFeeHistoryData(testContext: VertxTestContext) { val feeHistoryFetcherImpl = createFeeHistoryFetcherImpl( - l1Web3jServiceMock = createMockedWeb3jBlobExtended() + l1Web3jServiceMock = createMockedWeb3jBlobExtended(), ) feeHistoryFetcherImpl.getEthFeeHistoryData( startBlockNumberInclusive = 101L, - endBlockNumberInclusive = 110L + endBlockNumberInclusive = 110L, ) .thenApply { testContext @@ -53,12 +53,12 @@ class GasPriceCapFeeHistoryFetcherImplTest { @Test fun getEthFeeHistoryData_returnsFeeHistoryDataWithEmptyBlobData(testContext: VertxTestContext) { val feeHistoryFetcherImpl = createFeeHistoryFetcherImpl( - l1Web3jServiceMock = createMockedWeb3jBlobExtendedWithoutBlobData() + l1Web3jServiceMock = createMockedWeb3jBlobExtendedWithoutBlobData(), ) feeHistoryFetcherImpl.getEthFeeHistoryData( startBlockNumberInclusive = 101L, - endBlockNumberInclusive = 110L + endBlockNumberInclusive = 110L, ) .thenApply { testContext @@ -89,13 +89,13 @@ class GasPriceCapFeeHistoryFetcherImplTest { l1Web3jServiceMock, GasPriceCapFeeHistoryFetcherImpl.Config( maxBlockCount, - rewardPercentiles = listOf() - ) + rewardPercentiles = listOf(), + ), ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "Reward percentiles must be a non-empty list." + "Reward percentiles must be a non-empty list.", ) } }.completeNow() @@ -112,13 +112,13 @@ class GasPriceCapFeeHistoryFetcherImplTest { l1Web3jServiceMock, GasPriceCapFeeHistoryFetcherImpl.Config( maxBlockCount, - rewardPercentiles = listOf(101.0, -12.2) - ) + rewardPercentiles = listOf(101.0, -12.2), + ), ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "Reward percentile must be within 0.0 and 100.0." + " Value=101.0" + "Reward percentile must be within 0.0 and 100.0." + " Value=101.0", ) } @@ -127,13 +127,13 @@ class GasPriceCapFeeHistoryFetcherImplTest { l1Web3jServiceMock, GasPriceCapFeeHistoryFetcherImpl.Config( maxBlockCount, - rewardPercentiles = listOf(-12.2, 1000.0) - ) + rewardPercentiles = listOf(-12.2, 1000.0), + ), ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "Reward percentile must be within 0.0 and 100.0." + " Value=-12.2" + "Reward percentile must be within 0.0 and 100.0." + " Value=-12.2", ) } }.completeNow() @@ -143,19 +143,19 @@ class GasPriceCapFeeHistoryFetcherImplTest { @Timeout(10, timeUnit = TimeUnit.SECONDS) fun getEthFeeHistoryData_throwsErrorIfStartBlockIsHigherThanTargetBlock(testContext: VertxTestContext) { val feeHistoryFetcherImpl = createFeeHistoryFetcherImpl( - l1Web3jServiceMock = createMockedWeb3jBlobExtended() + l1Web3jServiceMock = createMockedWeb3jBlobExtended(), ) testContext.verify { assertThrows { feeHistoryFetcherImpl.getEthFeeHistoryData( startBlockNumberInclusive = 111L, - endBlockNumberInclusive = 100L + endBlockNumberInclusive = 100L, ).get() }.also { exception -> assertThat(exception.message) .isEqualTo( - "endBlockNumberInclusive=100 must be equal or higher than startBlockNumberInclusive=111" + "endBlockNumberInclusive=100 must be equal or higher than startBlockNumberInclusive=111", ) } }.completeNow() @@ -165,20 +165,20 @@ class GasPriceCapFeeHistoryFetcherImplTest { @Timeout(10, timeUnit = TimeUnit.SECONDS) fun getEthFeeHistoryData_throwsErrorIfBlockDiffIsLargerThanMaxBlockCount(testContext: VertxTestContext) { val feeHistoryFetcherImpl = createFeeHistoryFetcherImpl( - l1Web3jServiceMock = createMockedWeb3jBlobExtended() + l1Web3jServiceMock = createMockedWeb3jBlobExtended(), ) testContext.verify { assertThrows { feeHistoryFetcherImpl.getEthFeeHistoryData( startBlockNumberInclusive = 101L, - endBlockNumberInclusive = 120L + endBlockNumberInclusive = 120L, ).get() }.also { exception -> assertThat(exception.message) .isEqualTo( "difference between endBlockNumberInclusive=120 and startBlockNumberInclusive=101 " + - "must be less than maxBlockCount=10" + "must be less than maxBlockCount=10", ) } }.completeNow() @@ -191,9 +191,9 @@ class GasPriceCapFeeHistoryFetcherImplTest { .ethFeeHistoryWithBlob( any(), any(), - eq(rewardPercentiles) + eq(rewardPercentiles), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { val feeHistoryResponse = EthFeeHistoryBlobExtended() @@ -208,7 +208,7 @@ class GasPriceCapFeeHistoryFetcherImplTest { baseFeePerBlobGas = (10000 until 10000 + maxBlockCount.toLong() + 1) .map { it.toString() }, blobGasUsedRatio = (10 until 10 + maxBlockCount.toLong()) - .map { it / 100.0 } + .map { it / 100.0 }, ) feeHistoryResponse.result = feeHistory SafeFuture.completedFuture(feeHistoryResponse) @@ -224,9 +224,9 @@ class GasPriceCapFeeHistoryFetcherImplTest { .ethFeeHistoryWithBlob( any(), any(), - eq(rewardPercentiles) + eq(rewardPercentiles), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { val feeHistoryResponse = EthFeeHistoryBlobExtended() @@ -239,7 +239,7 @@ class GasPriceCapFeeHistoryFetcherImplTest { gasUsedRatio = (10 until 10 + maxBlockCount.toLong()) .map { it / 100.0 }, baseFeePerBlobGas = emptyList(), - blobGasUsedRatio = emptyList() + blobGasUsedRatio = emptyList(), ) feeHistoryResponse.result = feeHistory SafeFuture.completedFuture(feeHistoryResponse) @@ -249,14 +249,14 @@ class GasPriceCapFeeHistoryFetcherImplTest { } private fun createFeeHistoryFetcherImpl( - l1Web3jServiceMock: Web3jBlobExtended + l1Web3jServiceMock: Web3jBlobExtended, ): GasPriceCapFeeHistoryFetcherImpl { return GasPriceCapFeeHistoryFetcherImpl( l1Web3jServiceMock, GasPriceCapFeeHistoryFetcherImpl.Config( maxBlockCount, - rewardPercentiles - ) + rewardPercentiles, + ), ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmissionTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmissionTest.kt index 02e28a18..5da0bd68 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmissionTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForDataSubmissionTest.kt @@ -20,13 +20,13 @@ class GasPriceCapProviderForDataSubmissionTest { maxBaseFeePerGasCap = 7000000000uL, // 7GWei maxPriorityFeePerGasCap = 1000000000uL, // 1GWei maxFeePerGasCap = 8000000000uL, // 8GWei - maxFeePerBlobGasCap = 500000000uL // 0.5GWei + maxFeePerBlobGasCap = 500000000uL, // 0.5GWei ) private val returnMultipliedRawGasPriceCaps = GasPriceCaps( maxBaseFeePerGasCap = (returnRawGasPriceCaps.maxBaseFeePerGasCap!!.toDouble() * 0.9).toULong(), // 6.3GWei maxPriorityFeePerGasCap = (returnRawGasPriceCaps.maxPriorityFeePerGasCap.toDouble() * 0.9).toULong(), // 0.9GWei maxFeePerGasCap = 7200000000uL, // 7.2GWei - maxFeePerBlobGasCap = (returnRawGasPriceCaps.maxFeePerBlobGasCap.toDouble() * 0.9).toULong() // 0.45GWei + maxFeePerBlobGasCap = (returnRawGasPriceCaps.maxFeePerBlobGasCap.toDouble() * 0.9).toULong(), // 0.45GWei ) private val expectedMaxPriorityFeePerGasCap = 3000000000uL // 3GWei private val expectedMaxFeePerGasCap = 10000000000uL // 10GWei @@ -41,8 +41,8 @@ class GasPriceCapProviderForDataSubmissionTest { config: GasPriceCapProviderForDataSubmission.Config = GasPriceCapProviderForDataSubmission.Config( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, maxFeePerGasCap = expectedMaxFeePerGasCap, - maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap, + ), ): GasPriceCapProviderForDataSubmission { mockedGasPriceCapProvider = mock { on { getGasPriceCaps(any()) } doReturn SafeFuture.completedFuture(returnRawGasPriceCaps) @@ -53,7 +53,7 @@ class GasPriceCapProviderForDataSubmissionTest { return GasPriceCapProviderForDataSubmission( config = config, gasPriceCapProvider = mockedGasPriceCapProvider, - metricsFacade = mockedMetricsFacade + metricsFacade = mockedMetricsFacade, ) } @@ -65,26 +65,26 @@ class GasPriceCapProviderForDataSubmissionTest { @Test fun `gas price caps of data submission should be returned correctly`() { assertThat( - gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get() + gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = 1000000000uL, // 1GWei maxFeePerGasCap = 8000000000uL, // 8GWei - maxFeePerBlobGasCap = 500000000uL // 0.5GWei - ) + maxFeePerBlobGasCap = 500000000uL, // 0.5GWei + ), ) } @Test fun `gas price caps with coefficient of data submission should be returned correctly`() { assertThat( - gasPriceCapProviderForDataSubmission.getGasPriceCapsWithCoefficient(100L).get() + gasPriceCapProviderForDataSubmission.getGasPriceCapsWithCoefficient(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = returnMultipliedRawGasPriceCaps.maxPriorityFeePerGasCap, maxFeePerGasCap = returnMultipliedRawGasPriceCaps.maxFeePerGasCap, - maxFeePerBlobGasCap = returnMultipliedRawGasPriceCaps.maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = returnMultipliedRawGasPriceCaps.maxFeePerBlobGasCap, + ), ) } @@ -95,17 +95,17 @@ class GasPriceCapProviderForDataSubmissionTest { maxBaseFeePerGasCap = 9000000000uL, // 9GWei maxPriorityFeePerGasCap = 8000000000uL, // 8GWei (exceeds 3GWei upper bound) maxFeePerGasCap = 17000000000uL, // 17GWei (exceeds 10GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (exceeds 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (exceeds 0.7GWei upper bound) + ), ) assertThat( - gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get() + gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, // 3GWei (capped at 3GWei upper bound) maxFeePerGasCap = expectedMaxFeePerGasCap, // 10GWei (capped at 10GWei upper bound) - maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap // 0.7GWei (capped at 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap, // 0.7GWei (capped at 0.7GWei upper bound) + ), ) gasPriceCapProviderForDataSubmission = createGasPriceCapProviderForDataSubmission( @@ -113,17 +113,17 @@ class GasPriceCapProviderForDataSubmissionTest { maxBaseFeePerGasCap = 5000000000uL, // 5GWei maxPriorityFeePerGasCap = 8000000000uL, // 8GWei (exceeds 3GWei upper bound) maxFeePerGasCap = 13000000000uL, // 13GWei (exceeds 10GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (exceeds 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (exceeds 0.7GWei upper bound) + ), ) assertThat( - gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get() + gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, // 3GWei (capped at 3GWei upper bound) maxFeePerGasCap = 8000000000uL, // 8GWei - maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap // 0.7GWei (capped at 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap, // 0.7GWei (capped at 0.7GWei upper bound) + ), ) gasPriceCapProviderForDataSubmission = createGasPriceCapProviderForDataSubmission( @@ -131,17 +131,17 @@ class GasPriceCapProviderForDataSubmissionTest { maxBaseFeePerGasCap = 15000000000uL, // 15GWei (exceeds 10GWei upper bound) maxPriorityFeePerGasCap = 8000000000uL, // 8GWei (exceeds 3GWei upper bound) maxFeePerGasCap = 23000000000uL, // 23GWei (exceeds 10GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (exceeds 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (exceeds 0.7GWei upper bound) + ), ) assertThat( - gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get() + gasPriceCapProviderForDataSubmission.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, // 3GWei (capped at 3GWei upper bound) maxFeePerGasCap = expectedMaxFeePerGasCap, // 10GWei (capped at 10GWei upper bound) - maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap // 0.7GWei (capped at 0.7GWei upper bound) - ) + maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap, // 0.7GWei (capped at 0.7GWei upper bound) + ), ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalizationTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalizationTest.kt index 6a3922b5..663a21d1 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalizationTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderForFinalizationTest.kt @@ -17,13 +17,13 @@ class GasPriceCapProviderForFinalizationTest { maxBaseFeePerGasCap = 7000000000uL, // 7GWei maxPriorityFeePerGasCap = 1000000000uL, // 1GWei maxFeePerGasCap = 8000000000uL, // 8GWei - maxFeePerBlobGasCap = 500000000uL // 0.5GWei + maxFeePerBlobGasCap = 500000000uL, // 0.5GWei ) private val returnMultipliedRawGasPriceCaps = GasPriceCaps( maxBaseFeePerGasCap = (returnRawGasPriceCaps.maxBaseFeePerGasCap!!.toDouble() * 0.9).toULong(), // 6.3GWei maxPriorityFeePerGasCap = (returnRawGasPriceCaps.maxPriorityFeePerGasCap.toDouble() * 0.9).toULong(), // 0.9GWei maxFeePerGasCap = 7200000000uL, // 7.2GWei - maxFeePerBlobGasCap = (returnRawGasPriceCaps.maxFeePerBlobGasCap.toDouble() * 0.9).toULong() // 0.45GWei + maxFeePerBlobGasCap = (returnRawGasPriceCaps.maxFeePerBlobGasCap.toDouble() * 0.9).toULong(), // 0.45GWei ) private val maxPriorityFeePerGasCap = 3000000000uL // 3GWei private val maxFeePerGasCap = 10000000000uL // 10GWei @@ -42,8 +42,8 @@ class GasPriceCapProviderForFinalizationTest { config: GasPriceCapProviderForFinalization.Config = GasPriceCapProviderForFinalization.Config( maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, maxFeePerGasCap = maxFeePerGasCap, - gasPriceCapMultiplier = gasPriceCapMultiplier - ) + gasPriceCapMultiplier = gasPriceCapMultiplier, + ), ): GasPriceCapProviderForFinalization { mockedGasPriceCapProvider = mock { on { getGasPriceCaps(any()) } doReturn SafeFuture.completedFuture(returnRawGasPriceCaps) @@ -54,7 +54,7 @@ class GasPriceCapProviderForFinalizationTest { return GasPriceCapProviderForFinalization( config = config, gasPriceCapProvider = mockedGasPriceCapProvider, - metricsFacade = mockedMetricsFacade + metricsFacade = mockedMetricsFacade, ) } @@ -66,26 +66,26 @@ class GasPriceCapProviderForFinalizationTest { @Test fun `gas price caps of finalization should be returned correctly`() { assertThat( - gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get() + gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = returnRawGasPriceCaps.maxPriorityFeePerGasCap, maxFeePerGasCap = returnRawGasPriceCaps.maxFeePerGasCap, - maxFeePerBlobGasCap = 0uL - ) + maxFeePerBlobGasCap = 0uL, + ), ) } @Test fun `gas price caps with coefficient of finalization should be returned correctly`() { assertThat( - gasPriceCapProviderForFinalization.getGasPriceCapsWithCoefficient(100L).get() + gasPriceCapProviderForFinalization.getGasPriceCapsWithCoefficient(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = returnMultipliedRawGasPriceCaps.maxPriorityFeePerGasCap, maxFeePerGasCap = returnMultipliedRawGasPriceCaps.maxFeePerGasCap, - maxFeePerBlobGasCap = 0uL - ) + maxFeePerBlobGasCap = 0uL, + ), ) } @@ -96,17 +96,17 @@ class GasPriceCapProviderForFinalizationTest { maxBaseFeePerGasCap = 22000000000uL, // 22GWei (exceeds 20GWei upper bound) maxPriorityFeePerGasCap = 8000000000uL, // 8GWei (exceeds 6GWei upper bound) maxFeePerGasCap = 30000000000uL, // 30GWei (exceeds 20GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (ignorable) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (ignorable) + ), ) assertThat( - gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get() + gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, // 6GWei (capped at 6GWei upper bound) maxFeePerGasCap = expectedMaxFeePerGasCap, // 20GWei (capped at 20GWei upper bound) - maxFeePerBlobGasCap = 0uL - ) + maxFeePerBlobGasCap = 0uL, + ), ) gasPriceCapProviderForFinalization = createGasPriceCapProviderForFinalization( @@ -114,17 +114,17 @@ class GasPriceCapProviderForFinalizationTest { maxBaseFeePerGasCap = 21000000000uL, // 21GWei (exceeds 20GWei upper bound) maxPriorityFeePerGasCap = 4000000000uL, maxFeePerGasCap = 25000000000uL, // 25GWei (exceeds 20GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (ignorable) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (ignorable) + ), ) assertThat( - gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get() + gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = 4000000000uL, maxFeePerGasCap = expectedMaxFeePerGasCap, // 20GWei (capped at 20GWei upper bound) - maxFeePerBlobGasCap = 0uL - ) + maxFeePerBlobGasCap = 0uL, + ), ) gasPriceCapProviderForFinalization = createGasPriceCapProviderForFinalization( @@ -132,17 +132,17 @@ class GasPriceCapProviderForFinalizationTest { maxBaseFeePerGasCap = 13000000000uL, // 13GWei maxPriorityFeePerGasCap = 10000000000uL, // 10GWei (exceeds 6GWei upper bound) maxFeePerGasCap = 23000000000uL, // 26GWei (exceeds 20GWei upper bound) - maxFeePerBlobGasCap = 8000000000uL // 8GWei (ignorable) - ) + maxFeePerBlobGasCap = 8000000000uL, // 8GWei (ignorable) + ), ) assertThat( - gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get() + gasPriceCapProviderForFinalization.getGasPriceCaps(100L).get(), ).isEqualTo( GasPriceCaps( maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, // 6GWei (capped at 6GWei upper bound) maxFeePerGasCap = 19000000000uL, - maxFeePerBlobGasCap = 0uL - ) + maxFeePerBlobGasCap = 0uL, + ), ) } } diff --git a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImplTest.kt b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImplTest.kt index fad313da..ad30ca5f 100644 --- a/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImplTest.kt +++ b/coordinator/ethereum/gas-pricing/dynamic-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/dynamiccap/GasPriceCapProviderImplTest.kt @@ -28,7 +28,7 @@ class GasPriceCapProviderImplTest { "WEDNESDAY_0" to 1.0, "WEDNESDAY_1" to 2.0, "WEDNESDAY_2" to 3.0, - "WEDNESDAY_3" to 4.0 + "WEDNESDAY_3" to 4.0, ) private val p10BaseFeeGas = 1000000000uL // 1GWei private val p10BaseFeeBlobGas = 100000000uL // 0.1GWei @@ -57,7 +57,7 @@ class GasPriceCapProviderImplTest { l2ExtendedWeb3JClient: ExtendedWeb3J = mockedL2ExtendedWeb3JClient, feeHistoriesRepository: FeeHistoriesRepositoryWithCache = mockedL1FeeHistoriesRepository, gasPriceCapCalculator: GasPriceCapCalculator = this.gasPriceCapCalculator, - clock: Clock = mockedClock + clock: Clock = mockedClock, ): GasPriceCapProviderImpl { return GasPriceCapProviderImpl( config = GasPriceCapProviderImpl.Config( @@ -69,12 +69,12 @@ class GasPriceCapProviderImplTest { adjustmentConstant = adjustmentConstant, blobAdjustmentConstant = blobAdjustmentConstant, finalizationTargetMaxDelay = finalizationTargetMaxDelay, - gasPriceCapsCoefficient = gasPriceCapsCoefficient + gasPriceCapsCoefficient = gasPriceCapsCoefficient, ), l2ExtendedWeb3JClient = l2ExtendedWeb3JClient, feeHistoriesRepository = feeHistoriesRepository, gasPriceCapCalculator = gasPriceCapCalculator, - clock = clock + clock = clock, ) } @@ -83,7 +83,7 @@ class GasPriceCapProviderImplTest { targetBlockTime = currentTime - 1.hours mockedL2ExtendedWeb3JClient = mock { on { ethGetBlockTimestampByNumber(any()) } doReturn SafeFuture.completedFuture( - BigInteger.valueOf(targetBlockTime.epochSeconds) + BigInteger.valueOf(targetBlockTime.epochSeconds), ) } @@ -92,7 +92,7 @@ class GasPriceCapProviderImplTest { on { getCachedPercentileGasFees() } doReturn PercentileGasFees( percentileBaseFeePerGas = p10BaseFeeGas, percentileBaseFeePerBlobGas = p10BaseFeeBlobGas, - percentileAvgReward = avgP10Reward + percentileAvgReward = avgP10Reward, ) } @@ -106,36 +106,36 @@ class GasPriceCapProviderImplTest { val negativePercentile = -10.0 assertThrows { createGasPriceCapProvider( - gasFeePercentile = negativePercentile + gasFeePercentile = negativePercentile, ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "gasFeePercentile must be no less than 0.0. Value=$negativePercentile" + "gasFeePercentile must be no less than 0.0. Value=$negativePercentile", ) } val negativeDuration = (-1).hours assertThrows { createGasPriceCapProvider( - finalizationTargetMaxDelay = negativeDuration + finalizationTargetMaxDelay = negativeDuration, ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "finalizationTargetMaxDelay duration must be longer than zero second. Value=$negativeDuration" + "finalizationTargetMaxDelay duration must be longer than zero second. Value=$negativeDuration", ) } val negativeCoefficient = -1.0 assertThrows { createGasPriceCapProvider( - gasPriceCapsCoefficient = negativeCoefficient + gasPriceCapsCoefficient = negativeCoefficient, ) }.also { exception -> assertThat(exception.message) .isEqualTo( - "gasPriceCapsCoefficient must be greater than 0.0. Value=$negativeCoefficient" + "gasPriceCapsCoefficient must be greater than 0.0. Value=$negativeCoefficient", ) } } @@ -146,14 +146,14 @@ class GasPriceCapProviderImplTest { val gasPriceCapProvider = createGasPriceCapProvider() assertThat( - gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get(), ).isEqualTo( GasPriceCaps( maxBaseFeePerGasCap = 1694444444uL, maxPriorityFeePerGasCap = 338888888uL, maxFeePerGasCap = 2033333332uL, - maxFeePerBlobGasCap = 169444444uL - ) + maxFeePerBlobGasCap = 169444444uL, + ), ) } @@ -166,14 +166,14 @@ class GasPriceCapProviderImplTest { val expectedMaxFeePerBlobGasCap = (169444444 * gasPriceCapsCoefficient).toULong() assertThat( - gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get(), ).isEqualTo( GasPriceCaps( maxBaseFeePerGasCap = expectedMaxBaseFeePerGasCap, maxPriorityFeePerGasCap = expectedMaxPriorityFeePerGasCap, maxFeePerGasCap = (expectedMaxBaseFeePerGasCap + expectedMaxPriorityFeePerGasCap), - maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = expectedMaxFeePerBlobGasCap, + ), ) } @@ -181,15 +181,15 @@ class GasPriceCapProviderImplTest { fun `gas price caps should be null if disabled`() { val targetL2BlockNumber = 100L val gasPriceCapProvider = createGasPriceCapProvider( - enabled = false + enabled = false, ) assertThat( - gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get(), ).isNull() assertThat( - gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get(), ).isNull() } @@ -197,15 +197,15 @@ class GasPriceCapProviderImplTest { fun `gas price caps should be null if not enough fee history data`() { val targetL2BlockNumber = 100L val gasPriceCapProvider = createGasPriceCapProvider( - gasFeePercentileWindowInBlocks = 200U + gasFeePercentileWindowInBlocks = 200U, ) assertThat( - gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get(), ).isNull() assertThat( - gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get(), ).isNull() } @@ -214,19 +214,19 @@ class GasPriceCapProviderImplTest { val targetL2BlockNumber = 100L mockedL1FeeHistoriesRepository = mock { on { getNumOfFeeHistoriesFromBlockNumber(any(), any()) } doReturn SafeFuture.failedFuture( - Error("Throw error for testing") + Error("Throw error for testing"), ) } val gasPriceCapProvider = createGasPriceCapProvider( - l2ExtendedWeb3JClient = mockedL2ExtendedWeb3JClient + l2ExtendedWeb3JClient = mockedL2ExtendedWeb3JClient, ) assertThat( - gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get(), ).isNull() assertThat( - gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get(), ).isNull() } @@ -235,19 +235,19 @@ class GasPriceCapProviderImplTest { val targetL2BlockNumber = 100L mockedL2ExtendedWeb3JClient = mock { on { ethGetBlockTimestampByNumber(any()) } doReturn SafeFuture.failedFuture( - Error("Throw error for testing") + Error("Throw error for testing"), ) } val gasPriceCapProvider = createGasPriceCapProvider( - l2ExtendedWeb3JClient = mockedL2ExtendedWeb3JClient + l2ExtendedWeb3JClient = mockedL2ExtendedWeb3JClient, ) assertThat( - gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCaps(targetL2BlockNumber).get(), ).isNull() assertThat( - gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get() + gasPriceCapProvider.getGasPriceCapsWithCoefficient(targetL2BlockNumber).get(), ).isNull() } } diff --git a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculator.kt b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculator.kt index 18057142..891f0e9c 100644 --- a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculator.kt +++ b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculator.kt @@ -8,12 +8,12 @@ import org.apache.logging.log4j.Logger class BoundableFeeCalculator( val config: Config, - private val feesCalculator: FeesCalculator + private val feesCalculator: FeesCalculator, ) : FeesCalculator { data class Config( val feeUpperBound: Double, val feeLowerBound: Double, - val feeMargin: Double + val feeMargin: Double, ) { init { require(feeUpperBound >= 0.0 && feeLowerBound >= 0.0 && feeMargin >= 0.0) { @@ -37,7 +37,7 @@ class BoundableFeeCalculator( " Will default to the upper bound value", fee.toGWei(), blockRange.toIntervalString(), - config.feeUpperBound.toGWei() + config.feeUpperBound.toGWei(), ) config.feeUpperBound } else if (fee.compareTo(config.feeLowerBound) == -1) { @@ -46,14 +46,14 @@ class BoundableFeeCalculator( " Will default to the lower bound value", fee.toGWei(), blockRange.toIntervalString(), - config.feeLowerBound.toGWei() + config.feeLowerBound.toGWei(), ) config.feeLowerBound } else { log.debug( "Gas fee update: gasPrice={}GWei, l1Blocks={}.", fee.toGWei(), - blockRange.toIntervalString() + blockRange.toIntervalString(), ) fee } diff --git a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/DynamicGasPrice.kt b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/DynamicGasPrice.kt index 72faebec..059c4a61 100644 --- a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/DynamicGasPrice.kt +++ b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/DynamicGasPrice.kt @@ -23,13 +23,13 @@ interface GasPriceUpdater { } enum class MinerExtraDataVersions(val version: Byte) { - V1(0x1) + V1(0x1), } data class MinerExtraDataV1( val fixedCostInKWei: UInt, val variableCostInKWei: UInt, - val ethGasPriceInKWei: UInt + val ethGasPriceInKWei: UInt, ) { val version: Byte = MinerExtraDataVersions.V1.version diff --git a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculator.kt b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculator.kt index 2fdb2f8f..07e85a80 100644 --- a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculator.kt +++ b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculator.kt @@ -11,11 +11,11 @@ import org.apache.logging.log4j.Logger * (sumOf(reward[i] * ratio[i] * (i+1)) / sumOf(ratio[i] * (i+1))) * priorityFeeWmaCoefficient */ class WMAFeesCalculator( - private val config: Config + private val config: Config, ) : FeesCalculator { data class Config( val baseFeeCoefficient: Double, - val priorityFeeWmaCoefficient: Double + val priorityFeeWmaCoefficient: Double, ) private val log: Logger = LogManager.getLogger(this::class.java) @@ -46,7 +46,7 @@ class WMAFeesCalculator( "Calculated gasPrice={} wei, l1Blocks={} feeHistory={}", calculatedGasPrice, feeHistory.blocksRange().toIntervalString(), - feeHistory + feeHistory, ) return calculatedGasPrice } catch (e: Exception) { @@ -56,7 +56,7 @@ class WMAFeesCalculator( weightedRatiosSum, feeHistory, e.message, - e + e, ) throw e } diff --git a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProvider.kt b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProvider.kt index 7fcdf8da..bc5b42df 100644 --- a/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProvider.kt +++ b/coordinator/ethereum/gas-pricing/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProvider.kt @@ -12,14 +12,14 @@ class WMAGasProvider( private val chainId: Long, private val feesFetcher: FeesFetcher, private val priorityFeeCalculator: FeesCalculator, - private val config: Config + private val config: Config, ) : AtomicContractEIP1559GasProvider, EIP4844GasProvider { data class Config( val gasLimit: ULong, val maxFeePerGasCap: ULong, val maxFeePerBlobGasCap: ULong, - val maxPriorityFeePerGasCap: ULong + val maxPriorityFeePerGasCap: ULong, ) private fun getRecentFees(): EIP4844GasFees { @@ -32,9 +32,9 @@ class WMAGasProvider( EIP4844GasFees( EIP1559GasFees( maxPriorityFeePerGas.toULong(), - maxFeePerGas.toULong() + maxFeePerGas.toULong(), ), - maxFeePerBlobGas + maxFeePerBlobGas, ) }.get() } @@ -79,7 +79,7 @@ class WMAGasProvider( return getRecentFees().run { EIP1559GasFees( maxPriorityFeePerGas = min(this.eip1559GasFees.maxPriorityFeePerGas, config.maxFeePerGasCap), - maxFeePerGas = min(this.eip1559GasFees.maxFeePerGas, config.maxFeePerGasCap) + maxFeePerGas = min(this.eip1559GasFees.maxFeePerGas, config.maxFeePerGasCap), ) } } @@ -90,14 +90,14 @@ class WMAGasProvider( eip1559GasFees = EIP1559GasFees( maxPriorityFeePerGas = min( this.eip1559GasFees.maxPriorityFeePerGas, - config.maxFeePerGasCap + config.maxFeePerGasCap, ), maxFeePerGas = min( this.eip1559GasFees.maxFeePerGas, - config.maxFeePerGasCap - ) + config.maxFeePerGasCap, + ), ), - maxFeePerBlobGas = min(this.maxFeePerBlobGas, config.maxFeePerBlobGasCap) + maxFeePerBlobGas = min(this.maxFeePerBlobGas, config.maxFeePerBlobGasCap), ) } } diff --git a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculatorTest.kt b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculatorTest.kt index 94726bb4..286d80f9 100644 --- a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/BoundableFeeCalculatorTest.kt @@ -18,15 +18,15 @@ class BoundableFeeCalculatorTest { 0.25, 0.5, 0.75, - 0.9 + 0.9, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.25, 0.5, 0.75, - 0.9 - ) + 0.9, + ), ) @Test @@ -41,7 +41,7 @@ class BoundableFeeCalculatorTest { } val boundableFeeCalculator = BoundableFeeCalculator( BoundableFeeCalculator.Config(gasPriceUpperBound, gasPriceLowerBound, gasPriceFixedCost), - mockFeesCalculator + mockFeesCalculator, ) Assertions.assertThat(boundableFeeCalculator.calculateFees(feeHistory)).isEqualTo(expectedGasPrice) } @@ -59,7 +59,7 @@ class BoundableFeeCalculatorTest { } val boundableFeeCalculator = BoundableFeeCalculator( BoundableFeeCalculator.Config(gasPriceUpperBound, gasPriceLowerBound, gasPriceFixedCost), - mockFeesCalculator + mockFeesCalculator, ) Assertions.assertThat(boundableFeeCalculator.calculateFees(feeHistory)).isEqualTo(expectedGasPrice) } @@ -77,7 +77,7 @@ class BoundableFeeCalculatorTest { } val boundableFeeCalculator = BoundableFeeCalculator( BoundableFeeCalculator.Config(gasPriceUpperBound, gasPriceLowerBound, gasPriceFixedCost), - mockFeesCalculator + mockFeesCalculator, ) Assertions.assertThat(boundableFeeCalculator.calculateFees(feeHistory)).isEqualTo(expectedGasPrice) } @@ -89,9 +89,9 @@ class BoundableFeeCalculatorTest { BoundableFeeCalculator.Config( -1000.0, -10000.0, - -100.0 + -100.0, ), - mock() + mock(), ) } Assertions.assertThat(exception) @@ -106,9 +106,9 @@ class BoundableFeeCalculatorTest { BoundableFeeCalculator.Config( 1000.0, 10000.0, - 10.0 + 10.0, ), - mock() + mock(), ) } Assertions.assertThat(exception) diff --git a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/MinerExtraDataV1Test.kt b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/MinerExtraDataV1Test.kt index 83fd2f73..d27fc507 100644 --- a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/MinerExtraDataV1Test.kt +++ b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/MinerExtraDataV1Test.kt @@ -49,20 +49,20 @@ class MinerExtraDataV1Test { val minerExtraData1 = MinerExtraDataV1( fixedCostInKWei = Int.MAX_VALUE.toUInt() - 1u, // 2147483646u, 2147483646, 0x7FFF_FFFE variableCostInKWei = Int.MAX_VALUE.toUInt(), // 2147483647u, 2147483647, 0x7FFF_FFFF - ethGasPriceInKWei = Int.MAX_VALUE.toUInt() + 1u // 2147483648u, -2147483648, 0x8000_0000 + ethGasPriceInKWei = Int.MAX_VALUE.toUInt() + 1u, // 2147483648u, -2147483648, 0x8000_0000 ) val encodedMinerExtraData1 = readableBytesToPaddedHex("0x01|7FFF_FFFE|7FFF_FFFF|8000_0000") val minerExtraData2 = MinerExtraDataV1( fixedCostInKWei = UInt.MIN_VALUE, // 0u, 0, 0x0000_0000 variableCostInKWei = Int.MAX_VALUE.toUInt(), // 2147483647u, 2147483647, 0x7FFF_FFFF - ethGasPriceInKWei = UInt.MAX_VALUE // 4294967295u, -1, 0xFFFF_FFFF + ethGasPriceInKWei = UInt.MAX_VALUE, // 4294967295u, -1, 0xFFFF_FFFF ) val encodedMinerExtraData2 = readableBytesToPaddedHex("0x01|0000_0000|7FFF_FFFF|FFFF_FFFF") return Stream.of( Arguments.of(encodedMinerExtraData1, minerExtraData1), - Arguments.of(encodedMinerExtraData2, minerExtraData2) + Arguments.of(encodedMinerExtraData2, minerExtraData2), ) } } diff --git a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculatorTest.kt b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculatorTest.kt index 29082ab2..2c15cd36 100644 --- a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAFeesCalculatorTest.kt @@ -11,8 +11,8 @@ class WMAFeesCalculatorTest { WMAFeesCalculator( WMAFeesCalculator.Config( baseFeeCoefficient = 0.1, - priorityFeeWmaCoefficient = 1.2 - ) + priorityFeeWmaCoefficient = 1.2, + ), ) val feeHistory = FeeHistory( @@ -21,7 +21,7 @@ class WMAFeesCalculatorTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, - blobGasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9) + blobGasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9), ) // WMA = (140*0.1) + ((1000*0.25*1 + 1100*0.5*2 + 1200*0.75*3 + 1300*0.9*4) / (0.25*1 + 0.5*2 + 0.75*3 + 0.9*4)) * 1.2 = 1489.49295 @@ -42,8 +42,8 @@ class WMAFeesCalculatorTest { WMAFeesCalculator( WMAFeesCalculator.Config( baseFeeCoefficient = 0.1, - priorityFeeWmaCoefficient = 1.2 - ) + priorityFeeWmaCoefficient = 1.2, + ), ) val feeHistory = FeeHistory( @@ -52,7 +52,7 @@ class WMAFeesCalculatorTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.0, 0.0, 0.0, 0.0), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, - blobGasUsedRatio = listOf(0.0, 0.0, 0.0, 0.0) + blobGasUsedRatio = listOf(0.0, 0.0, 0.0, 0.0), ) // WMA = (140*0.1) = 14.0 diff --git a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProviderTest.kt b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProviderTest.kt index ca340761..792bfae4 100644 --- a/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProviderTest.kt +++ b/coordinator/ethereum/gas-pricing/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/WMAGasProviderTest.kt @@ -15,7 +15,7 @@ class WMAGasProviderTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, - blobGasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9) + blobGasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9), ) private val chainId = 999 private val gasLimit = 100000uL @@ -25,8 +25,8 @@ class WMAGasProviderTest { private val l1PriorityFeeCalculator: FeesCalculator = WMAFeesCalculator( WMAFeesCalculator.Config( baseFeeCoefficient = 0.0, - priorityFeeWmaCoefficient = 1.0 - ) + priorityFeeWmaCoefficient = 1.0, + ), ) @Test @@ -43,8 +43,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) // WMA = (140*0.0) + ((1000*0.25*1 + 1100*0.5*2 + 1200*0.75*3 + 1300*0.9*4) / (0.25*1 + 0.5*2 + 0.75*3 + 0.9*4)) * 1.0 = 1229.57746 @@ -67,8 +67,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedMaxPriorityFeePerGas = wmaGasProvider.getMaxPriorityFeePerGas(null).toULong() @@ -89,8 +89,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedMaxFeePerGas = wmaGasProvider.getMaxFeePerGas(null).toULong() @@ -111,8 +111,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedMaxPriorityFeePerGas = wmaGasProvider.getMaxPriorityFeePerGas(null).toULong() @@ -133,8 +133,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedFees = wmaGasProvider.getEIP1559GasFees() @@ -156,8 +156,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedFees = wmaGasProvider.getEIP1559GasFees() @@ -179,8 +179,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedFees = wmaGasProvider.getEIP4844GasFees() @@ -203,8 +203,8 @@ class WMAGasProviderTest { gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, maxPriorityFeePerGasCap = maxPriorityFeePerGasCap, - maxFeePerBlobGasCap = maxFeePerBlobGasCap - ) + maxFeePerBlobGasCap = maxFeePerBlobGasCap, + ), ) val calculatedFees = wmaGasProvider.getEIP4844GasFees() diff --git a/coordinator/ethereum/gas-pricing/src/testFixtures/kotlin/net/consensys/linea/ethereum/gaspricing/FakeGasPriceCapProvider.kt b/coordinator/ethereum/gas-pricing/src/testFixtures/kotlin/net/consensys/linea/ethereum/gaspricing/FakeGasPriceCapProvider.kt index 976a3947..505838fb 100644 --- a/coordinator/ethereum/gas-pricing/src/testFixtures/kotlin/net/consensys/linea/ethereum/gaspricing/FakeGasPriceCapProvider.kt +++ b/coordinator/ethereum/gas-pricing/src/testFixtures/kotlin/net/consensys/linea/ethereum/gaspricing/FakeGasPriceCapProvider.kt @@ -7,11 +7,11 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture val defaultGasPriceCaps = GasPriceCaps( maxPriorityFeePerGasCap = 10_000_000_000uL, // 10 gwei maxFeePerGasCap = 15_000_000_000uL, - maxFeePerBlobGasCap = 10_00_000_000uL + maxFeePerBlobGasCap = 10_00_000_000uL, ) class FakeGasPriceCapProvider( - private val gasPriceCaps: GasPriceCaps = defaultGasPriceCaps + private val gasPriceCaps: GasPriceCaps = defaultGasPriceCaps, ) : GasPriceCapProvider { override fun getGasPriceCaps(targetL2BlockNumber: Long): SafeFuture { return SafeFuture.completedFuture(gasPriceCaps) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/dynamicgasprice/MinMineableFeesPricerServiceIntegrationTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/dynamicgasprice/MinMineableFeesPricerServiceIntegrationTest.kt index 9cec7418..b1299f64 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/dynamicgasprice/MinMineableFeesPricerServiceIntegrationTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/dynamicgasprice/MinMineableFeesPricerServiceIntegrationTest.kt @@ -87,7 +87,7 @@ class MinMineableFeesPricerServiceIntegrationTest { BoundableFeeCalculator.Config( l2GasPriceUpperBound.toDouble(), l2GasPriceLowerBound.toDouble(), - l2GasPriceFixedCost + l2GasPriceFixedCost, ), GasUsageRatioWeightedAverageFeesCalculator( GasUsageRatioWeightedAverageFeesCalculator.Config( @@ -95,9 +95,9 @@ class MinMineableFeesPricerServiceIntegrationTest { priorityFeeCoefficient = 0.1, baseFeeBlobCoefficient = 0.1, blobSubmissionExpectedExecutionGas = 131_000, - expectedBlobGas = 120_000 - ) - ) + expectedBlobGas = 120_000, + ), + ), ) companion object { @@ -120,7 +120,7 @@ class MinMineableFeesPricerServiceIntegrationTest { @Timeout(5, timeUnit = TimeUnit.MINUTES) fun `miner set gas price are sent to recipients correctly and underpriced txn is pending`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { // we need this mocked web3j client because the gas fee history in layer 1 is full of zeros initially val l1Web3jClientMock = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) @@ -128,7 +128,7 @@ class MinMineableFeesPricerServiceIntegrationTest { whenever( l1Web3jClientMock .ethBlockNumber() - .sendAsync() + .sendAsync(), ) .thenAnswer { val l1Response = l1Web3jClient.ethBlockNumber().send() @@ -143,9 +143,9 @@ class MinMineableFeesPricerServiceIntegrationTest { .ethFeeHistory( ArgumentMatchers.eq(feeHistoryBlockCount.toInt()), ArgumentMatchers.eq(DefaultBlockParameterName.LATEST), - ArgumentMatchers.eq(listOf(feeHistoryRewardPercentile)) + ArgumentMatchers.eq(listOf(feeHistoryRewardPercentile)), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { val lastFakeFeeHistory = buildFakeEthFeeHistory( @@ -153,7 +153,7 @@ class MinMineableFeesPricerServiceIntegrationTest { initialReward, initialBaseFeePerGas = initialBaseFeePerGas.times(2u), initialGasUsedRatio, - feeHistoryBlockCount + feeHistoryBlockCount, ) SafeFuture.completedFuture(lastFakeFeeHistory) } @@ -161,7 +161,7 @@ class MinMineableFeesPricerServiceIntegrationTest { val dynamicGasPriceService = initialiseServices( vertx, l1Web3jClientMock, - initialBaseFeePerGas.div(10u) + initialBaseFeePerGas.div(10u), ) dynamicGasPriceService.start() @@ -182,12 +182,13 @@ class MinMineableFeesPricerServiceIntegrationTest { val sendResp = l2NodeTxManager.sendEIP1559Transaction( l2ChainId, setMineableGasPrice.subtract(BigInteger.valueOf(1)), // 1679999999 - /*maxFeePerGas*/updatedL2NodeGasPrice, // 2520000001 + /*maxFeePerGas*/ + updatedL2NodeGasPrice, // 2520000001 DefaultGasProvider().gasLimit, l2NodeTxManager.fromAddress, Bytes.random(32).toHexString(), // avoid tx already known error BigInteger.valueOf(1000), - false + false, ) println("maxPriorityGasFee: ${setMineableGasPrice.subtract(BigInteger.valueOf(1))}") // save the txn hash in the static variable to be retrieved in subsequent tests @@ -209,7 +210,7 @@ class MinMineableFeesPricerServiceIntegrationTest { @Timeout(90, timeUnit = TimeUnit.SECONDS) fun `underpriced txn is mined after miner gas price set to a lower value`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { var l1LatestBlockNumber = BigInteger.valueOf(2) val l1Web3jClientMock = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) @@ -218,9 +219,9 @@ class MinMineableFeesPricerServiceIntegrationTest { .ethFeeHistory( ArgumentMatchers.eq(feeHistoryBlockCount.toInt()), ArgumentMatchers.eq(DefaultBlockParameterName.LATEST), - ArgumentMatchers.eq(listOf(feeHistoryRewardPercentile)) + ArgumentMatchers.eq(listOf(feeHistoryRewardPercentile)), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { // The following should yield l2 calculated gas fee as 110,000,001 @@ -229,14 +230,14 @@ class MinMineableFeesPricerServiceIntegrationTest { (initialReward / 10u), (initialBaseFeePerGas / 10u), initialGasUsedRatio, - feeHistoryBlockCount + feeHistoryBlockCount, ) SafeFuture.completedFuture(feeHistoryResponse) } whenever( l1Web3jClientMock .ethBlockNumber() - .sendAsync() + .sendAsync(), ) .thenAnswer { val ethBlockNumber = EthBlockNumber() @@ -275,7 +276,7 @@ class MinMineableFeesPricerServiceIntegrationTest { @Timeout(90, timeUnit = TimeUnit.SECONDS) fun `txn with max fee per gas as current gas price is sent to l2-node and is mined correctly`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { val l2NodeGasPrice = l2NodeWeb3jClient.ethGasPrice().send().gasPrice // 165000001 @@ -288,7 +289,7 @@ class MinMineableFeesPricerServiceIntegrationTest { l2NodeTxManager.fromAddress, "0x", BigInteger.valueOf(1000), - false + false, ) sendTxnHash = sendResp.transactionHash @@ -307,7 +308,7 @@ class MinMineableFeesPricerServiceIntegrationTest { BigInteger.valueOf(25000), l2Credentials2.address, "", - BigInteger.ZERO + BigInteger.ZERO, ) } @@ -316,13 +317,13 @@ class MinMineableFeesPricerServiceIntegrationTest { initialReward: ULong, initialBaseFeePerGas: ULong, initialGasUsedRatio: UInt, - feeHistoryBlockCount: UInt + feeHistoryBlockCount: UInt, ): EthFeeHistory { val feeHistory = EthFeeHistory.FeeHistory() feeHistory.setReward((initialReward until initialReward + feeHistoryBlockCount).map { listOf(it.toString()) }) feeHistory.setBaseFeePerGas( (initialBaseFeePerGas until initialBaseFeePerGas + feeHistoryBlockCount + 1u) - .map { it.toString() } + .map { it.toString() }, ) feeHistory.gasUsedRatio = (initialGasUsedRatio until initialGasUsedRatio + feeHistoryBlockCount).map { it.toDouble() / 100.0 } @@ -336,17 +337,17 @@ class MinMineableFeesPricerServiceIntegrationTest { private fun initialiseServices( vertx: Vertx, l1Web3jClient: Web3j, - initialGasPrice: ULong? = null + initialGasPrice: ULong? = null, ): MinMineableFeesPricerService { val feesFetcher: FeesFetcher = FeeHistoryFetcherImpl( web3jClient = l1Web3jClient, web3jService = Web3jBlobExtended( - HttpService(System.getProperty("L1_RPC_URL", "http://localhost:8445")) + HttpService(System.getProperty("L1_RPC_URL", "http://localhost:8445")), ), config = FeeHistoryFetcherImpl.Config( feeHistoryBlockCount, - feeHistoryRewardPercentile - ) + feeHistoryRewardPercentile, + ), ) val l2SetGasPriceUpdater: GasPriceUpdater = createGasPriceUpdater(vertx) @@ -360,7 +361,7 @@ class MinMineableFeesPricerServiceIntegrationTest { vertx = vertx, feesFetcher = feesFetcher, feesCalculator = l2MinMinerTipCalculator, - gasPriceUpdater = l2SetGasPriceUpdater + gasPriceUpdater = l2SetGasPriceUpdater, ) } @@ -371,8 +372,8 @@ class MinMineableFeesPricerServiceIntegrationTest { besuEndPoints = besuRecipients.map { URI(it).toURL() }, retryConfig = RequestRetryConfig( maxRetries = 3u, - backoffDelay = 1.seconds - ) - ) + backoffDelay = 1.seconds, + ), + ), ) } diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculator.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculator.kt index a675eb98..56c16e3e 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculator.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculator.kt @@ -9,7 +9,7 @@ import org.apache.logging.log4j.Logger open class AverageWeightedFeesCalculator( val feeListFetcher: (FeeHistory) -> List, val ratioListFetcher: (FeeHistory) -> List, - val log: Logger + val log: Logger, ) : FeesCalculator { override fun calculateFees(feeHistory: FeeHistory): Double { val feeList = feeListFetcher(feeHistory) @@ -19,7 +19,7 @@ open class AverageWeightedFeesCalculator( val ratioList = if (ratioListFetcher(feeHistory).sumOf { it } == 0.0) { log.warn( "RatioSum is zero for all l1Blocks={}. Will fallback to Simple Average.", - feeHistory.blocksRange().toIntervalString() + feeHistory.blocksRange().toIntervalString(), ) List(ratioListFetcher(feeHistory).size) { 1.0 } } else { @@ -34,13 +34,13 @@ open class AverageWeightedFeesCalculator( object AverageWeightedBaseFeesCalculator : AverageWeightedFeesCalculator( feeListFetcher = { feeHistory -> feeHistory.baseFeePerGas }, ratioListFetcher = { feeHistory -> feeHistory.gasUsedRatio }, - log = LogManager.getLogger(AverageWeightedBaseFeesCalculator::class.java) + log = LogManager.getLogger(AverageWeightedBaseFeesCalculator::class.java), ) object AverageWeightedPriorityFeesCalculator : AverageWeightedFeesCalculator( feeListFetcher = { feeHistory -> feeHistory.reward.map { it.first() } }, ratioListFetcher = { feeHistory -> feeHistory.gasUsedRatio }, - log = LogManager.getLogger(AverageWeightedPriorityFeesCalculator::class.java) + log = LogManager.getLogger(AverageWeightedPriorityFeesCalculator::class.java), ) object AverageWeightedBlobBaseFeesCalculator : AverageWeightedFeesCalculator( @@ -48,5 +48,5 @@ object AverageWeightedBlobBaseFeesCalculator : AverageWeightedFeesCalculator( feeHistory.baseFeePerBlobGas.ifEmpty { List(feeHistory.baseFeePerGas.size) { 0uL } } }, ratioListFetcher = { feeHistory -> feeHistory.blobGasUsedRatio }, - log = LogManager.getLogger(AverageWeightedBlobBaseFeesCalculator::class.java) + log = LogManager.getLogger(AverageWeightedBlobBaseFeesCalculator::class.java), ) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerService.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerService.kt index b1d0f2dc..4edea8a9 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerService.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerService.kt @@ -17,11 +17,11 @@ class ExtraDataV1PricerService( private val feesFetcher: FeesFetcher, private val minerExtraDataCalculatorImpl: MinerExtraDataV1CalculatorImpl, private val extraDataUpdater: ExtraDataUpdater, - private val log: Logger = LogManager.getLogger(ExtraDataV1PricerService::class.java) + private val log: Logger = LogManager.getLogger(ExtraDataV1PricerService::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { private var lastExtraData: MinerExtraDataV1? = null @@ -37,7 +37,7 @@ class ExtraDataV1PricerService( log.info( "L2 extra data update: extraData={} l1Blocks={}", newExtraData, - blockRange.toIntervalString() + blockRange.toIntervalString(), ) } // even if extraData value is old, still call sequencer node, they may be restarted diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImpl.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImpl.kt index 3752681a..8e3666c6 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImpl.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImpl.kt @@ -17,7 +17,7 @@ import java.util.concurrent.atomic.AtomicLong class ExtraDataV1UpdaterImpl( httpJsonRpcClientFactory: VertxHttpJsonRpcClientFactory, - config: Config + config: Config, ) : ExtraDataUpdater { companion object { const val SET_MINER_EXTRA_DATA_METHOD_NAME = "miner_setExtraData" @@ -25,7 +25,7 @@ class ExtraDataV1UpdaterImpl( data class Config( val sequencerEndpoint: URL, - val retryConfig: RequestRetryConfig + val retryConfig: RequestRetryConfig, ) private val id: AtomicLong = AtomicLong(0) @@ -35,7 +35,7 @@ class ExtraDataV1UpdaterImpl( endpoint = config.sequencerEndpoint, methodsToRetry = setOf(SET_MINER_EXTRA_DATA_METHOD_NAME), retryConfig = config.retryConfig, - log = log + log = log, ) override fun updateMinerExtraData(extraData: MinerExtraDataV1): SafeFuture { @@ -43,7 +43,7 @@ class ExtraDataV1UpdaterImpl( jsonrpc = "2.0", id = id.incrementAndGet(), method = SET_MINER_EXTRA_DATA_METHOD_NAME, - params = listOf(extraData.encode()) + params = listOf(extraData.encode()), ) return setMinerExtraDataRpcClient.makeRequest(jsonRequest) .toSafeFuture() diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImpl.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImpl.kt index bf9b8346..4c852b99 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImpl.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImpl.kt @@ -14,13 +14,13 @@ import java.math.BigInteger class FeeHistoryFetcherImpl( private val web3jClient: Web3j, private val web3jService: Web3jBlobExtended, - private val config: Config + private val config: Config, ) : FeesFetcher { private val log: Logger = LogManager.getLogger(this::class.java) data class Config( val feeHistoryBlockCount: UInt, - val feeHistoryRewardPercentile: Double + val feeHistoryRewardPercentile: Double, ) { init { require(feeHistoryRewardPercentile in 0.0..100.0) { @@ -43,7 +43,7 @@ class FeeHistoryFetcherImpl( .ethFeeHistoryWithBlob( config.feeHistoryBlockCount.toInt(), DefaultBlockParameterName.LATEST, - listOf(config.feeHistoryRewardPercentile) + listOf(config.feeHistoryRewardPercentile), ) .sendAsync() .thenApply { @@ -59,7 +59,7 @@ class FeeHistoryFetcherImpl( feeHistory.reward.map { percentiles -> percentiles[0] }, feeHistory.gasUsedRatio, feeHistory.baseFeePerBlobGas[feeHistory.baseFeePerBlobGas.lastIndex], - feeHistory.blobGasUsedRatio + feeHistory.blobGasUsedRatio, ) } else { log.trace( @@ -68,7 +68,7 @@ class FeeHistoryFetcherImpl( feeHistory.blocksRange().toIntervalString(), feeHistory.baseFeePerGas[feeHistory.baseFeePerGas.lastIndex], feeHistory.reward.map { percentiles -> percentiles[0] }, - feeHistory.gasUsedRatio + feeHistory.gasUsedRatio, ) } feesCache = feeHistory diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImpl.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImpl.kt index 7b40f3c7..73ff03d8 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImpl.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImpl.kt @@ -8,12 +8,12 @@ import java.net.URL class GasPriceUpdaterImpl( private val httpJsonRpcClientFactory: VertxHttpJsonRpcClientFactory, - private val config: Config + private val config: Config, ) : GasPriceUpdater { data class Config( val gethEndpoints: List, val besuEndPoints: List, - val retryConfig: RequestRetryConfig + val retryConfig: RequestRetryConfig, ) { init { require(gethEndpoints.isNotEmpty() || besuEndPoints.isNotEmpty()) { @@ -24,23 +24,23 @@ class GasPriceUpdaterImpl( private val gethGasPriceUpdater: GenericGasPriceUpdater? = createPriceUpdater( endpoints = config.gethEndpoints, - setMinerGasPriceMethodName = "miner_setGasPrice" + setMinerGasPriceMethodName = "miner_setGasPrice", ) private val besuGasPriceUpdater: GenericGasPriceUpdater? = createPriceUpdater( endpoints = config.besuEndPoints, - setMinerGasPriceMethodName = "miner_setMinGasPrice" + setMinerGasPriceMethodName = "miner_setMinGasPrice", ) override fun updateMinerGasPrice(gasPrice: ULong): SafeFuture { return SafeFuture.allOf( gethGasPriceUpdater?.updateMinerGasPrice(gasPrice) ?: SafeFuture.COMPLETE, - besuGasPriceUpdater?.updateMinerGasPrice(gasPrice) ?: SafeFuture.COMPLETE + besuGasPriceUpdater?.updateMinerGasPrice(gasPrice) ?: SafeFuture.COMPLETE, ).thenApply {} } private fun createPriceUpdater( endpoints: List, - setMinerGasPriceMethodName: String + setMinerGasPriceMethodName: String, ): GenericGasPriceUpdater? { if (endpoints.isEmpty()) return null @@ -48,9 +48,9 @@ class GasPriceUpdaterImpl( httpJsonRpcClientFactory = httpJsonRpcClientFactory, config = GenericGasPriceUpdater.Config( endpoints = endpoints, - retryConfig = config.retryConfig + retryConfig = config.retryConfig, ), - setMinerGasPriceMethodName = setMinerGasPriceMethodName + setMinerGasPriceMethodName = setMinerGasPriceMethodName, ) } } diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculator.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculator.kt index 7ec542a1..8c0cbf10 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculator.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculator.kt @@ -13,14 +13,14 @@ import org.apache.logging.log4j.Logger * L2FinalGasPrice = L2BaseGasPrice + WeightedL2BlobGasPrice */ class GasUsageRatioWeightedAverageFeesCalculator( - val config: Config + val config: Config, ) : FeesCalculator { data class Config( val baseFeeCoefficient: Double, val priorityFeeCoefficient: Double, val baseFeeBlobCoefficient: Double, val blobSubmissionExpectedExecutionGas: Int, - val expectedBlobGas: Int + val expectedBlobGas: Int, ) private val log: Logger = LogManager.getLogger(this::class.java) @@ -43,7 +43,7 @@ class GasUsageRatioWeightedAverageFeesCalculator( executionGasPrice, weightedL2BlobGasPrice, feeHistory.blocksRange().toIntervalString(), - feeHistory + feeHistory, ) return l2GasPrice } @@ -51,7 +51,7 @@ class GasUsageRatioWeightedAverageFeesCalculator( private fun calculateExecutionGasPrice( feeHistory: FeeHistory, baseFeePerGasList: List, - priorityFeesPerGasList: List + priorityFeesPerGasList: List, ): Double { var gasUsageRatioList = feeHistory.gasUsedRatio var gasUsageRatiosSum = gasUsageRatioList.sumOf { it } @@ -59,7 +59,7 @@ class GasUsageRatioWeightedAverageFeesCalculator( if (gasUsageRatiosSum.compareTo(0.0) == 0) { log.warn( "GasUsedRatio is zero for all l1Blocks={}. Will fallback to Simple Average.", - feeHistory.blocksRange().toIntervalString() + feeHistory.blocksRange().toIntervalString(), ) // Giving a weight of one will yield the simple average gasUsageRatioList = feeHistory.gasUsedRatio.map { 1.0 } @@ -78,12 +78,12 @@ class GasUsageRatioWeightedAverageFeesCalculator( private fun calculateWeightedBlobGasPrice( feeHistory: FeeHistory, - baseFeePerBlobGasList: List + baseFeePerBlobGasList: List, ): Double { val blobGasUsageRatio = if (feeHistory.blobGasUsedRatio.sumOf { it }.compareTo(0.0) == 0) { log.warn( "BlobGasUsedRatio is zero for all l1Blocks={}. Will fallback to Simple Average.", - feeHistory.blocksRange().toIntervalString() + feeHistory.blocksRange().toIntervalString(), ) List(feeHistory.gasUsedRatio.size) { 1.0 } } else { diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GenericGasPriceUpdater.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GenericGasPriceUpdater.kt index e1c47619..11c1851b 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GenericGasPriceUpdater.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GenericGasPriceUpdater.kt @@ -22,11 +22,11 @@ import java.util.concurrent.atomic.AtomicLong class GenericGasPriceUpdater( httpJsonRpcClientFactory: VertxHttpJsonRpcClientFactory, config: Config, - private val setMinerGasPriceMethodName: String + private val setMinerGasPriceMethodName: String, ) : GasPriceUpdater { class Config( val endpoints: List, - val retryConfig: RequestRetryConfig + val retryConfig: RequestRetryConfig, ) { init { require(endpoints.isNotEmpty()) { "At least one endpoint is required" } @@ -41,7 +41,7 @@ class GenericGasPriceUpdater( endpoints = config.endpoints, methodsToRetry = setOf(setMinerGasPriceMethodName), retryConfig = config.retryConfig, - log = log + log = log, ) override fun updateMinerGasPrice(gasPrice: ULong): SafeFuture { @@ -51,13 +51,13 @@ class GenericGasPriceUpdater( } private fun fireAndForget( - gasPrice: ULong + gasPrice: ULong, ): Future { val jsonRequest = JsonRpcRequestListParams( jsonrpc = "2.0", id = id.incrementAndGet(), method = setMinerGasPriceMethodName, - params = listOf("0x${gasPrice.toString(16)}") + params = listOf("0x${gasPrice.toString(16)}"), ) return setPriceRequestFanOut.makeRequest(jsonRequest) @@ -83,14 +83,14 @@ class GenericGasPriceUpdater( endpoints: List, methodsToRetry: Set, retryConfig: RequestRetryConfig, - log: Logger + log: Logger, ): JsonRpcRequestFanOut { val rpcClients: List = endpoints.map { endpoint -> httpJsonRpcClientFactory.createWithRetries( endpoint = endpoint, retryConfig = retryConfig, methodsToRetry = methodsToRetry, - log = log + log = log, ) } return JsonRpcRequestFanOut(rpcClients) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerService.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerService.kt index a27e3df0..dbf4a2bf 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerService.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerService.kt @@ -18,11 +18,11 @@ class MinMineableFeesPricerService( private val feesFetcher: FeesFetcher, private val feesCalculator: FeesCalculator, private val gasPriceUpdater: GasPriceUpdater, - private val log: Logger = LogManager.getLogger(MinMineableFeesPricerService::class.java) + private val log: Logger = LogManager.getLogger(MinMineableFeesPricerService::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { private var lastPriceUpdate = 0uL @@ -39,7 +39,7 @@ class MinMineableFeesPricerService( log.info( "L2 Gas price update: gasPrice={} GWei l1Blocks={}", gasPrice.toGWei(), - blockRange.toIntervalString() + blockRange.toIntervalString(), ) } // even if price was not update, still call Besu/Geth nodes, they may be restarted diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinerExtraDataV1CalculatorImpl.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinerExtraDataV1CalculatorImpl.kt index 197ba454..2c5842e2 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinerExtraDataV1CalculatorImpl.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinerExtraDataV1CalculatorImpl.kt @@ -9,12 +9,12 @@ import net.consensys.linea.ethereum.gaspricing.MinerExtraDataV1 class MinerExtraDataV1CalculatorImpl( val config: Config, private val variableFeesCalculator: FeesCalculator, - private val legacyFeesCalculator: FeesCalculator + private val legacyFeesCalculator: FeesCalculator, ) : MinerExtraDataCalculator { data class Config( val fixedCostInKWei: UInt, - val ethGasPriceMultiplier: Double + val ethGasPriceMultiplier: Double, ) override fun calculateMinerExtraData(feeHistory: FeeHistory): MinerExtraDataV1 { @@ -23,7 +23,7 @@ class MinerExtraDataV1CalculatorImpl( return MinerExtraDataV1( fixedCostInKWei = config.fixedCostInKWei, variableCostInKWei = variableFees.tokWeiUInt(), - ethGasPriceInKWei = legacyFees.tokWeiUInt() + ethGasPriceInKWei = legacyFees.tokWeiUInt(), ) } } diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculator.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculator.kt index 783f2ea2..3e7ad51a 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculator.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculator.kt @@ -12,13 +12,13 @@ import org.apache.logging.log4j.Logger * */ class TransactionCostCalculator( private val dataCostCalculator: FeesCalculator, - private val config: Config + private val config: Config, ) : FeesCalculator { data class Config( val sampleTransactionCostMultiplier: Double, val fixedCostWei: ULong, val compressedTxSize: Int = 125, - val expectedGas: Int = 21000 + val expectedGas: Int = 21000, ) private val log: Logger = LogManager.getLogger(this::class.java) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculator.kt b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculator.kt index cf8cfbc8..3cbda2cb 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculator.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/main/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculator.kt @@ -15,13 +15,13 @@ class VariableFeesCalculator( val config: Config, val averageWeightedBaseFeesCalculator: FeesCalculator = AverageWeightedBaseFeesCalculator, val averageWeightedPriorityFeesCalculator: FeesCalculator = AverageWeightedPriorityFeesCalculator, - val averageWeightedBlobBaseFeesCalculator: FeesCalculator = AverageWeightedBlobBaseFeesCalculator + val averageWeightedBlobBaseFeesCalculator: FeesCalculator = AverageWeightedBlobBaseFeesCalculator, ) : FeesCalculator { data class Config( val blobSubmissionExpectedExecutionGas: UInt, val bytesPerDataSubmission: UInt, val expectedBlobGas: UInt, - val margin: Double + val margin: Double, ) private val log = LogManager.getLogger(this::class.java) @@ -44,7 +44,7 @@ class VariableFeesCalculator( executionFee, blobFee, config.bytesPerDataSubmission, - feeHistory.blocksRange().toIntervalString() + feeHistory.blocksRange().toIntervalString(), ) log.trace("feeHistory={}", feeHistory) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculatorTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculatorTest.kt index 97ffa236..152a6451 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/AverageWeightedFeesCalculatorTest.kt @@ -16,7 +16,7 @@ class AverageWeightedFeesCalculatorTest { fun `test AverageWeightedFeesCalculator`( @Suppress("UNUSED_PARAMETER") name: String, expectedWeightedAverage: Double, - feeHistory: FeeHistory + feeHistory: FeeHistory, ) { val mockLog = mock() val feeList = { fh: FeeHistory -> fh.baseFeePerGas } @@ -31,7 +31,7 @@ class AverageWeightedFeesCalculatorTest { fun `test AverageWeightedBaseFeesCalculator`( @Suppress("UNUSED_PARAMETER") name: String, expectedWeightedAverage: Double, - feeHistory: FeeHistory + feeHistory: FeeHistory, ) { val actualWeightedAverage = AverageWeightedBaseFeesCalculator.calculateFees(feeHistory) assertThat(actualWeightedAverage).isEqualTo(expectedWeightedAverage) @@ -42,7 +42,7 @@ class AverageWeightedFeesCalculatorTest { fun `test AverageWeightedPriorityFeesCalculator`( @Suppress("UNUSED_PARAMETER") name: String, expectedWeightedAverage: Double, - feeHistory: FeeHistory + feeHistory: FeeHistory, ) { val actualWeightedAverage = AverageWeightedPriorityFeesCalculator.calculateFees(feeHistory) assertThat(actualWeightedAverage).isEqualTo(expectedWeightedAverage) @@ -53,7 +53,7 @@ class AverageWeightedFeesCalculatorTest { fun `test AverageWeightedBlobBaseFeesCalculator`( @Suppress("UNUSED_PARAMETER") name: String, expectedWeightedAverage: Double, - feeHistory: FeeHistory + feeHistory: FeeHistory, ) { val actualWeightedAverage = AverageWeightedBlobBaseFeesCalculator.calculateFees(feeHistory) assertThat(actualWeightedAverage).isEqualTo(expectedWeightedAverage) @@ -66,7 +66,7 @@ class AverageWeightedFeesCalculatorTest { val feeHistory: FeeHistory, val weightedAverageBaseFee: Double, val weightedAveragePriorityFee: Double, - val weightedAverageBlobBaseFee: Double + val weightedAverageBlobBaseFee: Double, ) private val feeHistoryTestCases = listOf( @@ -78,11 +78,11 @@ class AverageWeightedFeesCalculatorTest { reward = listOf(1000).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25).map { it }, baseFeePerBlobGas = listOf(200, 210).map { it.toULong() }, - blobGasUsedRatio = listOf(0.16).map { it } + blobGasUsedRatio = listOf(0.16).map { it }, ), weightedAverageBaseFee = 100.0, // 100*0.25/0.25 weightedAveragePriorityFee = 1000.0, // 1000*0.25/0.25 - weightedAverageBlobBaseFee = 200.0 // 200*0.16/0.16 + weightedAverageBlobBaseFee = 200.0, // 200*0.16/0.16 ), FeeHistoryTestCase( name = "Single block history with zero ratio sum -> Simple average", @@ -92,11 +92,11 @@ class AverageWeightedFeesCalculatorTest { reward = listOf(1000).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.0).map { it }, baseFeePerBlobGas = listOf(200, 210).map { it.toULong() }, - blobGasUsedRatio = listOf(0.0).map { it } + blobGasUsedRatio = listOf(0.0).map { it }, ), weightedAverageBaseFee = 100.0, weightedAveragePriorityFee = 1000.0, - weightedAverageBlobBaseFee = 200.0 + weightedAverageBlobBaseFee = 200.0, ), FeeHistoryTestCase( name = "Multiple block history", @@ -106,7 +106,7 @@ class AverageWeightedFeesCalculatorTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25, 0.5, 0.75, 0.9).map { it }, baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, - blobGasUsedRatio = listOf(0.16, 0.5, 0.66, 0.83).map { it } + blobGasUsedRatio = listOf(0.16, 0.5, 0.66, 0.83).map { it }, ), weightedAverageBaseFee = listOf(100, 110, 120, 130, 140).map { it } .zip(listOf(0.25, 0.5, 0.75, 0.9).map { it }) @@ -125,7 +125,7 @@ class AverageWeightedFeesCalculatorTest { .sumOf { it.first * it.second } / ( listOf(0.16, 0.5, 0.66, 0.83).map { it }.sumOf { it } - ) + ), ), FeeHistoryTestCase( name = "Multiple block history equal ratio -> Simple Average", @@ -135,11 +135,11 @@ class AverageWeightedFeesCalculatorTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25, 0.25, 0.25, 0.25).map { it }, baseFeePerBlobGas = listOf(200, 210, 220, 230, 240).map { it.toULong() }, - blobGasUsedRatio = listOf(0.16, 0.16, 0.16, 0.16).map { it } + blobGasUsedRatio = listOf(0.16, 0.16, 0.16, 0.16).map { it }, ), weightedAverageBaseFee = 115.0, weightedAveragePriorityFee = 1150.0, - weightedAverageBlobBaseFee = 215.0 + weightedAverageBlobBaseFee = 215.0, ), FeeHistoryTestCase( name = "Multiple block history zero ratio sum -> Simple Average", @@ -149,11 +149,11 @@ class AverageWeightedFeesCalculatorTest { reward = listOf(1000, 1100, 1200, 1300).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0, 0, 0, 0).map { it.toDouble() }, baseFeePerBlobGas = listOf(200, 210, 220, 230, 240).map { it.toULong() }, - blobGasUsedRatio = listOf(0, 0, 0, 0).map { it.toDouble() } + blobGasUsedRatio = listOf(0, 0, 0, 0).map { it.toDouble() }, ), weightedAverageBaseFee = 115.0, weightedAveragePriorityFee = 1150.0, - weightedAverageBlobBaseFee = 215.0 + weightedAverageBlobBaseFee = 215.0, ), FeeHistoryTestCase( name = "Empty history", @@ -163,12 +163,12 @@ class AverageWeightedFeesCalculatorTest { reward = emptyList(), gasUsedRatio = emptyList(), baseFeePerBlobGas = emptyList(), - blobGasUsedRatio = emptyList() + blobGasUsedRatio = emptyList(), ), weightedAverageBaseFee = 0.0, weightedAveragePriorityFee = 0.0, - weightedAverageBlobBaseFee = 0.0 - ) + weightedAverageBlobBaseFee = 0.0, + ), ) @JvmStatic diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerServiceTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerServiceTest.kt index 48227d06..2d365d8c 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerServiceTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1PricerServiceTest.kt @@ -37,15 +37,15 @@ class ExtraDataV1PricerServiceTest { 0.25, 0.5, 0.75, - 0.9 + 0.9, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.25, 0.5, 0.75, - 0.9 - ) + 0.9, + ), ) @Test @@ -69,10 +69,10 @@ class ExtraDataV1PricerServiceTest { val boundableFeeCalculator = MinerExtraDataV1CalculatorImpl( MinerExtraDataV1CalculatorImpl.Config( defaultFixedCost, - defaultEthGasPriceMultiplier + defaultEthGasPriceMultiplier, ), variableFeesCalculator = mockVariableFeesCalculator, - legacyFeesCalculator = mockLegacyFeesCalculator + legacyFeesCalculator = mockLegacyFeesCalculator, ) val mockExtraDataUpdater = mock { on { updateMinerExtraData(any()) } doAnswer { SafeFuture.completedFuture(Unit) } @@ -83,13 +83,13 @@ class ExtraDataV1PricerServiceTest { vertx = vertx, feesFetcher = mockFeesFetcher, minerExtraDataCalculatorImpl = boundableFeeCalculator, - extraDataUpdater = mockExtraDataUpdater + extraDataUpdater = mockExtraDataUpdater, ) val expectedExtraData = MinerExtraDataV1( defaultFixedCost, expectedVariableFees.toKWei().toUInt(), - expectedEthGasPrice.toKWei().toUInt() + expectedEthGasPrice.toKWei().toUInt(), ) // Start the service diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImplTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImplTest.kt index bec46002..0ac951e8 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImplTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/ExtraDataV1UpdaterImplTest.kt @@ -34,14 +34,14 @@ class ExtraDataV1UpdaterImplTest { val requestRetry = RequestRetryConfig( maxRetries = 2u, backoffDelay = 10.milliseconds, - failuresWarningThreshold = 1u + failuresWarningThreshold = 1u, ) lateinit var wiremock: WireMockServer private lateinit var jsonRpcClientFactory: VertxHttpJsonRpcClientFactory private val minerExtraData = MinerExtraDataV1( fixedCostInKWei = 1u, variableCostInKWei = 2u, - ethGasPriceInKWei = 10u + ethGasPriceInKWei = 10u, ) val setMinerExtraDataSuccessResponse = JsonObject.of( @@ -50,7 +50,7 @@ class ExtraDataV1UpdaterImplTest { "id", 1, "result", - true + true, ) val expectedRequest = JsonObject.of( "jsonrpc", @@ -58,7 +58,7 @@ class ExtraDataV1UpdaterImplTest { "method", "miner_setExtraData", "params", - listOf(minerExtraData.encode()) + listOf(minerExtraData.encode()), ) @BeforeEach @@ -85,8 +85,8 @@ class ExtraDataV1UpdaterImplTest { jsonRpcClientFactory, ExtraDataV1UpdaterImpl.Config( sequencerEndpoint = sequencerEndpoint, - retryConfig = requestRetry - ) + retryConfig = requestRetry, + ), ) extraDataUpdaterImpl.updateMinerExtraData(extraData = minerExtraData) .thenApply { @@ -101,15 +101,15 @@ class ExtraDataV1UpdaterImplTest { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(response.toString()) - ) + .withBody(response.toString()), + ), ) } private fun verifyRequest( wiremock: WireMockServer, requestOriginEndpoint: URL, - request: JsonObject + request: JsonObject, ) { wiremock.verify( RequestPatternBuilder.newRequestPattern() @@ -120,9 +120,9 @@ class ExtraDataV1UpdaterImplTest { EqualToJsonPattern( request.toString(), /*ignoreArrayOrder*/ false, /*ignoreExtraElements*/ - true - ) - ) + true, + ), + ), ) } } diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImplTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImplTest.kt index ce038f6a..55711fc6 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImplTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/FeeHistoryFetcherImplTest.kt @@ -38,8 +38,8 @@ class FeeHistoryFetcherImplTest { l1Web3jServiceMock, FeeHistoryFetcherImpl.Config( feeHistoryBlockCount, - feeHistoryRewardPercentile - ) + feeHistoryRewardPercentile, + ), ) feeHistoryFetcherImpl.getL1EthGasPriceData() @@ -71,8 +71,8 @@ class FeeHistoryFetcherImplTest { l1Web3jServiceMock, FeeHistoryFetcherImpl.Config( feeHistoryBlockCount, - feeHistoryRewardPercentile - ) + feeHistoryRewardPercentile, + ), ) feeHistoryFetcherImpl.getL1EthGasPriceData() @@ -99,7 +99,7 @@ class FeeHistoryFetcherImplTest { whenever( web3jClient .ethGasPrice() - .sendAsync() + .sendAsync(), ) .thenAnswer { val gasPriceResponse = EthGasPrice() @@ -121,9 +121,9 @@ class FeeHistoryFetcherImplTest { .ethFeeHistoryWithBlob( eq(feeHistoryBlockCount.toInt()), eq(DefaultBlockParameterName.LATEST), - eq(listOf(feeHistoryRewardPercentile)) + eq(listOf(feeHistoryRewardPercentile)), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { val feeHistoryResponse = EthFeeHistoryBlobExtended() @@ -133,7 +133,7 @@ class FeeHistoryFetcherImplTest { baseFeePerGas = (10000 until 10011).map { it.toString() }, gasUsedRatio = (10 until 20).map { it / 100.0 }, baseFeePerBlobGas = (10000 until 10011).map { it.toString() }, - blobGasUsedRatio = (10 until 20).map { it / 100.0 } + blobGasUsedRatio = (10 until 20).map { it / 100.0 }, ) feeHistoryResponse.result = feeHistory SafeFuture.completedFuture(feeHistoryResponse) @@ -149,9 +149,9 @@ class FeeHistoryFetcherImplTest { .ethFeeHistoryWithBlob( eq(feeHistoryBlockCount.toInt()), eq(DefaultBlockParameterName.LATEST), - eq(listOf(feeHistoryRewardPercentile)) + eq(listOf(feeHistoryRewardPercentile)), ) - .sendAsync() + .sendAsync(), ) .thenAnswer { val feeHistoryResponse = EthFeeHistoryBlobExtended() @@ -161,7 +161,7 @@ class FeeHistoryFetcherImplTest { baseFeePerGas = (10000 until 10011).map { it.toString() }, gasUsedRatio = (10 until 20).map { it / 100.0 }, baseFeePerBlobGas = emptyList(), - blobGasUsedRatio = emptyList() + blobGasUsedRatio = emptyList(), ) feeHistoryResponse.result = feeHistory SafeFuture.completedFuture(feeHistoryResponse) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImplTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImplTest.kt index 6b697f80..97013295 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImplTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasPriceUpdaterImplTest.kt @@ -34,7 +34,7 @@ class GasPriceUpdaterImplTest { private val requestRetry = RequestRetryConfig( maxRetries = 2u, backoffDelay = 10.milliseconds, - failuresWarningThreshold = 1u + failuresWarningThreshold = 1u, ) private lateinit var wiremock: WireMockServer private lateinit var jsonRpcClientFactory: VertxHttpJsonRpcClientFactory @@ -45,7 +45,7 @@ class GasPriceUpdaterImplTest { "id", 1, "result", - true + true, ) private val expectedGethRequest = JsonObject.of( "jsonrpc", @@ -53,7 +53,7 @@ class GasPriceUpdaterImplTest { "method", "miner_setGasPrice", "params", - listOf("0xa") + listOf("0xa"), ) private val expectedBesuRequest = expectedGethRequest.copy() .put("method", "miner_setMinGasPrice") @@ -61,24 +61,24 @@ class GasPriceUpdaterImplTest { @BeforeEach fun beforeEach(vertx: Vertx) { wiremock = WireMockServer( - WireMockConfiguration.wireMockConfig().dynamicPort() + WireMockConfiguration.wireMockConfig().dynamicPort(), ) wiremock.start() gethRecipients = listOf( URI("http://localhost:${wiremock.port()}/geth-1/").toURL(), URI("http://localhost:${wiremock.port()}/geth-2/").toURL(), - URI("http://localhost:${wiremock.port()}/geth-3/").toURL() + URI("http://localhost:${wiremock.port()}/geth-3/").toURL(), ) besuRecipients = listOf( URI("http://localhost:${wiremock.port()}/besu-1/").toURL(), URI("http://localhost:${wiremock.port()}/besu-2/").toURL(), - URI("http://localhost:${wiremock.port()}/besu-3/").toURL() + URI("http://localhost:${wiremock.port()}/besu-3/").toURL(), ) val meterRegistry = SimpleMeterRegistry() val metricsFacade: MetricsFacade = MicrometerMetricsFacade(registry = meterRegistry, "linea") jsonRpcClientFactory = VertxHttpJsonRpcClientFactory( vertx, - metricsFacade + metricsFacade, ) } @@ -93,7 +93,7 @@ class GasPriceUpdaterImplTest { GasPriceUpdaterImpl.Config( gethEndpoints = emptyList(), besuEndPoints = emptyList(), - retryConfig = requestRetry + retryConfig = requestRetry, ) } @@ -105,20 +105,20 @@ class GasPriceUpdaterImplTest { GasPriceUpdaterImpl.Config( gethEndpoints = listOf(URI("http://localhost:8545").toURL()), besuEndPoints = emptyList(), - retryConfig = requestRetry + retryConfig = requestRetry, ) // works with at least one Besu endpoint GasPriceUpdaterImpl.Config( gethEndpoints = emptyList(), besuEndPoints = listOf(URI("http://localhost:8545").toURL()), - retryConfig = requestRetry + retryConfig = requestRetry, ) } @Test @Timeout(10, timeUnit = TimeUnit.SECONDS) fun gasPriceUpdaterImpl_setsPriceOnGethAndBesu( - testContext: VertxTestContext + testContext: VertxTestContext, ) { testPriceUpdateForEndpoints(testContext, gethRecipients, besuRecipients) } @@ -126,7 +126,7 @@ class GasPriceUpdaterImplTest { @Test @Timeout(10, timeUnit = TimeUnit.SECONDS) fun gasPriceUpdaterImpl_setsPriceOnGethOnly( - testContext: VertxTestContext + testContext: VertxTestContext, ) { testPriceUpdateForEndpoints(testContext, gethRecipients = gethRecipients, besuRecipients = emptyList()) } @@ -134,7 +134,7 @@ class GasPriceUpdaterImplTest { @Test @Timeout(10, timeUnit = TimeUnit.SECONDS) fun gasPriceUpdaterImpl_setsPriceOnBesuOnly( - testContext: VertxTestContext + testContext: VertxTestContext, ) { testPriceUpdateForEndpoints(testContext, gethRecipients = emptyList(), besuRecipients = besuRecipients) } @@ -142,7 +142,7 @@ class GasPriceUpdaterImplTest { private fun testPriceUpdateForEndpoints( testContext: VertxTestContext, gethRecipients: List, - besuRecipients: List + besuRecipients: List, ) { val gasPrice = 10uL gethRecipients.forEach { endpoint -> wiremockStubForPost(wiremock, endpoint, setPriceSuccessResponse) } @@ -154,8 +154,8 @@ class GasPriceUpdaterImplTest { GasPriceUpdaterImpl.Config( gethEndpoints = gethRecipients, besuEndPoints = besuRecipients, - retryConfig = requestRetry - ) + retryConfig = requestRetry, + ), ) l2GasPriceUpdaterImpl.updateMinerGasPrice(gasPrice) @@ -172,26 +172,26 @@ class GasPriceUpdaterImplTest { private fun wiremockStubForPost( wiremock: WireMockServer, requestOriginEndpoint: URL, - response: JsonObject + response: JsonObject, ) { wiremock.stubFor( WireMock.post(requestOriginEndpoint.path) .withHeader( "Content-Type", - WireMock.containing("application/json") + WireMock.containing("application/json"), ) .willReturn( WireMock.ok() .withHeader("Content-type", "application/json") - .withBody(response.toString()) - ) + .withBody(response.toString()), + ), ) } private fun verifyRequest( wiremock: WireMockServer, requestOriginEndpoint: URL, - request: JsonObject + request: JsonObject, ) { wiremock.verify( RequestPatternBuilder.newRequestPattern() @@ -199,15 +199,15 @@ class GasPriceUpdaterImplTest { .withUrl(requestOriginEndpoint.path) .withHeader( "content-type", - EqualToPattern("application/json") + EqualToPattern("application/json"), ) .withRequestBody( EqualToJsonPattern( request.toString(), /*ignoreArrayOrder*/ false, /*ignoreExtraElements*/ - true - ) - ) + true, + ), + ), ) } } diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculatorTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculatorTest.kt index f475b561..fbaf59c0 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/GasUsageRatioWeightedAverageFeesCalculatorTest.kt @@ -10,7 +10,7 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { priorityFeeCoefficient = 1.2, baseFeeBlobCoefficient = 0.1, blobSubmissionExpectedExecutionGas = 120_000, - expectedBlobGas = 131_000 + expectedBlobGas = 131_000, ) private val feesCalculator = GasUsageRatioWeightedAverageFeesCalculator(config) @@ -22,7 +22,7 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { reward = listOf(1000).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.25), baseFeePerBlobGas = listOf(100, 110).map { it.toULong() }, - blobGasUsedRatio = listOf(0.16) + blobGasUsedRatio = listOf(0.16), ) // (100*0.1 + 1000*1.2)*0.25/0.25 = 1210 // ((100*0.1)*0.16)/0.16 * (131000.0 / 120000.0) = 10.9166666 @@ -41,7 +41,7 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { reward = listOf(1000).map { listOf(it.toULong()) }, gasUsedRatio = listOf(0.0), baseFeePerBlobGas = listOf(100, 110).map { it.toULong() }, - blobGasUsedRatio = listOf(0.0) + blobGasUsedRatio = listOf(0.0), ) // (100*0.1 + 1000*1.2) = 1210 // (((100*0.1) * 0.5) / 0.5 ) * (131000.0 / 120000.0) = 10.9166666 @@ -62,15 +62,15 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.25, 0.5, 0.75, - 0.9 + 0.9, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.16, 0.5, 0.66, - 0.83 - ) + 0.83, + ), ) // Weighted Average: @@ -90,15 +90,15 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.5, 0.5, 0.5, - 0.5 + 0.5, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.5, 0.5, 0.5, - 0.5 - ) + 0.5, + ), ) // Simple Average: @@ -118,15 +118,15 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.0, 0.0, 0.0, - 0.0 + 0.0, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.0, 0.0, 0.0, - 0.0 - ) + 0.0, + ), ) // Simple Average: @@ -146,15 +146,15 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.0, 0.0, 0.0, - 0.0 + 0.0, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.0, 0.0, 0.0, - 0.0 - ) + 0.0, + ), ) // Simple Average: @@ -174,10 +174,10 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.25, 0.5, 0.75, - 0.9 + 0.9, ), baseFeePerBlobGas = emptyList(), - blobGasUsedRatio = emptyList() + blobGasUsedRatio = emptyList(), ) // Weighted Average: @@ -198,15 +198,15 @@ class GasUsageRatioWeightedAverageFeesCalculatorTest { 0.75, 0.0, 0.75, - 0.0 + 0.0, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.83, 0.0, 0.83, - 0.0 - ) + 0.0, + ), ) // Weighted Average: diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerServiceTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerServiceTest.kt index feb9a894..6c5aab0d 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerServiceTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/MinMineableFeesPricerServiceTest.kt @@ -35,15 +35,15 @@ class MinMineableFeesPricerServiceTest { 0.25, 0.5, 0.75, - 0.9 + 0.9, ), baseFeePerBlobGas = listOf(100, 110, 120, 130, 140).map { it.toULong() }, blobGasUsedRatio = listOf( 0.25, 0.5, 0.75, - 0.9 - ) + 0.9, + ), ) @Test @@ -66,9 +66,9 @@ class MinMineableFeesPricerServiceTest { BoundableFeeCalculator.Config( gasPriceUpperBound, gasPriceLowerBound, - gasPriceFixedCost + gasPriceFixedCost, ), - mockFeesCalculator + mockFeesCalculator, ) val mockGasPriceUpdater = mock { on { updateMinerGasPrice(anyLong().toULong()) } doAnswer { SafeFuture.completedFuture(Unit) } @@ -79,7 +79,7 @@ class MinMineableFeesPricerServiceTest { vertx = vertx, feesFetcher = mockFeesFetcher, feesCalculator = boundableFeeCalculator, - gasPriceUpdater = mockGasPriceUpdater + gasPriceUpdater = mockGasPriceUpdater, ) monitor.start().thenApply { vertx.setTimer(100) { @@ -114,9 +114,9 @@ class MinMineableFeesPricerServiceTest { BoundableFeeCalculator.Config( gasPriceUpperBound, gasPriceLowerBound, - gasPriceFixedCost + gasPriceFixedCost, ), - mockFeesCalculator + mockFeesCalculator, ) val mockGasPriceUpdater = mock { on { updateMinerGasPrice(anyLong().toULong()) } doAnswer { SafeFuture.completedFuture(Unit) } @@ -128,7 +128,7 @@ class MinMineableFeesPricerServiceTest { vertx = vertx, feesFetcher = mockFeesFetcher, feesCalculator = boundableFeeCalculator, - gasPriceUpdater = mockGasPriceUpdater + gasPriceUpdater = mockGasPriceUpdater, ) monitor.action().get() @@ -154,9 +154,9 @@ class MinMineableFeesPricerServiceTest { BoundableFeeCalculator.Config( gasPriceUpperBound, gasPriceLowerBound, - gasPriceFixedCost + gasPriceFixedCost, ), - mockFeesCalculator + mockFeesCalculator, ) val mockGasPriceUpdater = mock { on { updateMinerGasPrice(anyLong().toULong()) } doAnswer { SafeFuture.completedFuture(Unit) } @@ -168,7 +168,7 @@ class MinMineableFeesPricerServiceTest { vertx = vertx, feesFetcher = mockFeesFetcher, feesCalculator = boundableFeeCalculator, - gasPriceUpdater = mockGasPriceUpdater + gasPriceUpdater = mockGasPriceUpdater, ) monitor.action().get() diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculatorTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculatorTest.kt index 07d5f2af..664034a6 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/TransactionCostCalculatorTest.kt @@ -13,7 +13,7 @@ class TransactionCostCalculatorTest { priorityFeeCoefficient = 0.02, baseFeeBlobCoefficient = 0.02, blobSubmissionExpectedExecutionGas = 69000, - expectedBlobGas = 131_000 + expectedBlobGas = 131_000, ) private val legacyFeesCalculator = GasUsageRatioWeightedAverageFeesCalculator(oldCalculatorConfig) @@ -21,7 +21,7 @@ class TransactionCostCalculatorTest { margin = 1.2, bytesPerDataSubmission = 131_000u, blobSubmissionExpectedExecutionGas = 69000u, - expectedBlobGas = 131_000u + expectedBlobGas = 131_000u, ) private val variableFeesCalculator = VariableFeesCalculator(variableFeesCalculatorConfig) private val transactionCostCalculator = TransactionCostCalculator(variableFeesCalculator, config) @@ -36,7 +36,7 @@ class TransactionCostCalculatorTest { reward = listOf(listOf(1000UL)), // not a big impact gasUsedRatio = listOf(0.25), baseFeePerBlobGas = listOf(100UL), - blobGasUsedRatio = listOf(0.25) + blobGasUsedRatio = listOf(0.25), ) val legacyGasPriceUnderRegularConditions = legacyFeesCalculator.calculateFees(regularL1Fees) diff --git a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculatorTest.kt b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculatorTest.kt index 83fd71d5..d60e0eb1 100644 --- a/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculatorTest.kt +++ b/coordinator/ethereum/gas-pricing/static-cap/src/test/kotlin/net/consensys/linea/ethereum/gaspricing/staticcap/VariableFeesCalculatorTest.kt @@ -13,7 +13,7 @@ class VariableFeesCalculatorTest { margin = 1.1, bytesPerDataSubmission = 200_000u, blobSubmissionExpectedExecutionGas = 120_000u, - expectedBlobGas = 131_000u + expectedBlobGas = 131_000u, ) @Test @@ -37,7 +37,7 @@ class VariableFeesCalculatorTest { config = config, averageWeightedBaseFeesCalculator = mockBaseFeeCalculator, averageWeightedPriorityFeesCalculator = mockPriorityFeeCalculator, - averageWeightedBlobBaseFeesCalculator = mockBlobBaseFeeCalculator + averageWeightedBlobBaseFeesCalculator = mockBlobBaseFeeCalculator, ) assertThat(feesCalculator.calculateFees(mockFeeHistory)) .isEqualTo(expectedVariableFees) diff --git a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringApp.kt b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringApp.kt index 4c6b6914..6c149ab1 100644 --- a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringApp.kt +++ b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringApp.kt @@ -21,7 +21,7 @@ class MessageAnchoringApp( private val vertx: Vertx, private val config: Config, l1EthApiClient: EthApiClient, - private val l2MessageService: L2MessageServiceSmartContractClient + private val l2MessageService: L2MessageServiceSmartContractClient, ) : LongRunningService { data class Config( val l1RequestRetryConfig: RetryConfig, @@ -34,14 +34,14 @@ class MessageAnchoringApp( val l1EventPollingTimeout: Duration = 5.seconds, val l1EventSearchBlockChunk: UInt = 1000u, val messageQueueCapacity: UInt = 10_000u, - val maxMessagesToAnchorPerL2Transaction: UInt = 100u + val maxMessagesToAnchorPerL2Transaction: UInt = 100u, ) private val l1EthLogsSearcher: EthLogsSearcher = EthLogsSearcherImpl( vertx = vertx, ethApiClient = l1EthApiClient, - config = EthLogsSearcherImpl.Config(loopSuccessBackoffDelay = config.l1SuccessBackoffDelay) + config = EthLogsSearcherImpl.Config(loopSuccessBackoffDelay = config.l1SuccessBackoffDelay), ) private val eventsQueue: Deque = LinkedBlockingDeque() @@ -61,7 +61,7 @@ class MessageAnchoringApp( l1MessagesSentFetchTimeout = config.l1EventPollingTimeout, l1BlockSearchChuck = config.l1EventSearchBlockChunk, l1HighestBlock = config.l1HighestBlockTag, - l2HighestBlock = config.l2HighestBlockTag + l2HighestBlock = config.l2HighestBlockTag, ) } private val messageAnchoringService = @@ -73,7 +73,7 @@ class MessageAnchoringApp( eventsQueue = eventsQueue, maxMessagesToAnchorPerL2Transaction = config.maxMessagesToAnchorPerL2Transaction, l2HighestBlockTag = config.l2HighestBlockTag, - anchoringTickInterval = config.anchoringTickInterval + anchoringTickInterval = config.anchoringTickInterval, ) override fun start(): CompletableFuture { @@ -84,7 +84,7 @@ class MessageAnchoringApp( override fun stop(): CompletableFuture { return CompletableFuture.allOf( l1EventsPoller.stop(), - messageAnchoringService.stop() + messageAnchoringService.stop(), ).thenApply { Unit } diff --git a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringService.kt b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringService.kt index 171fc669..399b83c3 100644 --- a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringService.kt +++ b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageAnchoringService.kt @@ -24,11 +24,11 @@ class MessageAnchoringService( private val maxMessagesToAnchorPerL2Transaction: UInt, private val l2HighestBlockTag: BlockParameter, anchoringTickInterval: Duration, - private val log: Logger = LogManager.getLogger(MessageAnchoringService::class.java) + private val log: Logger = LogManager.getLogger(MessageAnchoringService::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = anchoringTickInterval.inWholeMilliseconds, - log = log + log = log, ) { override fun action(): SafeFuture<*> { return l2MessageService @@ -54,7 +54,7 @@ class MessageAnchoringService( private fun anchorMessages(eventsToAnchor: List): SafeFuture { val messagesInterval = CommonDomainFunctions.blockIntervalString( eventsToAnchor.first().messageNumber, - eventsToAnchor.last().messageNumber + eventsToAnchor.last().messageNumber, ) log.debug("sending anchoring tx messagesNumbers={}", messagesInterval) @@ -65,7 +65,7 @@ class MessageAnchoringService( messageHashes = eventsToAnchor.map { it.messageHash }, startingMessageNumber = eventsToAnchor.first().messageNumber, finalMessageNumber = eventsToAnchor.last().messageNumber, - finalRollingHash = rollingHash + finalRollingHash = rollingHash, ) }.thenPeek { txHash -> log.info("sent anchoring tx messagesNumbers={} txHash={}", messagesInterval, txHash) @@ -82,8 +82,8 @@ class MessageAnchoringService( address = l1ContractAddress, topics = listOf( L1RollingHashUpdatedEvent.topic, - messageNumber.toHexStringUInt256() - ) + messageNumber.toHexStringUInt256(), + ), ) .thenApply { rawLogs -> val events = rawLogs.map(L1RollingHashUpdatedEvent::fromEthLog) diff --git a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageNumberAndRollingHash.kt b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageNumberAndRollingHash.kt index 9abe3858..f0dc3a0e 100644 --- a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageNumberAndRollingHash.kt +++ b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/MessageNumberAndRollingHash.kt @@ -4,7 +4,7 @@ import linea.kotlin.encodeHex data class MessageNumberAndRollingHash( val messageNumber: ULong, - val rollingHash: ByteArray + val rollingHash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsFetcher.kt b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsFetcher.kt index b7452784..94cc4694 100644 --- a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsFetcher.kt +++ b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsFetcher.kt @@ -25,25 +25,25 @@ internal class L1MessageSentEventsFetcher( private val l1SmartContractAddress: String, private val l1EventsSearcher: EthLogsSearcher, private val l1HighestBlock: BlockParameter, - private val log: Logger = LogManager.getLogger(L1MessageSentEventsFetcher::class.java) + private val log: Logger = LogManager.getLogger(L1MessageSentEventsFetcher::class.java), ) { private data class LastSearch( val highestL1AlreadySearchedBlockNumber: ULong, - val lastStartingMessageNumber: ULong + val lastStartingMessageNumber: ULong, ) private val lastSearch = AtomicReference( LastSearch( highestL1AlreadySearchedBlockNumber = 0UL, - lastStartingMessageNumber = 0UL - ) + lastStartingMessageNumber = 0UL, + ), ) fun findL1MessageSentEvents( startingMessageNumber: ULong, targetMessagesToFetch: UInt, fetchTimeout: Duration, - blockChunkSize: UInt + blockChunkSize: UInt, ): SafeFuture>> { require(startingMessageNumber >= lastSearch.get().lastStartingMessageNumber) { "startingMessageNumber=$startingMessageNumber must greater than " + @@ -52,7 +52,7 @@ internal class L1MessageSentEventsFetcher( return findL1RollingHashUpdatedEvent( fromBlock = lastSearch.get().highestL1AlreadySearchedBlockNumber, - messageNumber = startingMessageNumber + messageNumber = startingMessageNumber, ).thenCompose { event -> if (event == null) { return@thenCompose SafeFuture.completedFuture(emptyList()) @@ -63,11 +63,11 @@ internal class L1MessageSentEventsFetcher( toBlock = l1HighestBlock, address = l1SmartContractAddress, topics = listOf( - MessageSentEvent.topic + MessageSentEvent.topic, ), chunkSize = blockChunkSize, searchTimeout = fetchTimeout, - stopAfterTargetLogsCount = targetMessagesToFetch + stopAfterTargetLogsCount = targetMessagesToFetch, ).thenApply { result -> lastSearch.set(LastSearch(result.endBlockNumber, startingMessageNumber)) val events = result.logs.map(MessageSentEvent::fromEthLog) @@ -75,9 +75,9 @@ internal class L1MessageSentEventsFetcher( "fetched MessageSent events from L1: messageNumbers={} l1Blocks={}", CommonDomainFunctions.blockIntervalString( events.first().event.messageNumber, - events.last().event.messageNumber + events.last().event.messageNumber, ), - result.intervalString() + result.intervalString(), ) events } @@ -86,7 +86,7 @@ internal class L1MessageSentEventsFetcher( private fun findL1RollingHashUpdatedEvent( fromBlock: ULong, - messageNumber: ULong + messageNumber: ULong, ): SafeFuture?> { return l1EventsSearcher.getLogs( fromBlock = fromBlock.toBlockParameter(), @@ -94,8 +94,8 @@ internal class L1MessageSentEventsFetcher( address = l1SmartContractAddress, topics = listOf( L1RollingHashUpdatedEvent.topic, - messageNumber.toHexStringUInt256() - ) + messageNumber.toHexStringUInt256(), + ), ).thenApply { it.firstOrNull()?.let { log -> L1RollingHashUpdatedEvent.fromEthLog(log) } } diff --git a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsPoller.kt b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsPoller.kt index 59d4b823..971d7c1a 100644 --- a/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsPoller.kt +++ b/coordinator/ethereum/message-anchoring/src/main/kotlin/linea/anchoring/clients/L1MessageSentEventsPoller.kt @@ -25,17 +25,17 @@ class L1MessageSentEventsPoller( private val l1BlockSearchChuck: UInt, private val l1HighestBlock: BlockParameter, private val l2HighestBlock: BlockParameter, - private val log: Logger = LogManager.getLogger(L1MessageSentEventsPoller::class.java) + private val log: Logger = LogManager.getLogger(L1MessageSentEventsPoller::class.java), ) : PeriodicPollingService( vertx, pollingIntervalMs = pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { private val eventsFetcher = L1MessageSentEventsFetcher( l1SmartContractAddress = l1SmartContractAddress, l1EventsSearcher = l1EventsSearcher, l1HighestBlock = l1HighestBlock, - log = log + log = log, ) private fun nextMessageNumberToFetchFromL1(): SafeFuture { @@ -59,7 +59,7 @@ class L1MessageSentEventsPoller( log.debug( "skipping fetching MessageSent events: queueSize={} reached targetCapacity={}", eventsQueue.size, - eventsQueueMaxCapacity + eventsQueueMaxCapacity, ) return SafeFuture.completedFuture(null) } @@ -70,7 +70,7 @@ class L1MessageSentEventsPoller( startingMessageNumber = nextMessageNumberToFetchFromL1, targetMessagesToFetch = l1MessagesSentFetchLimit.coerceAtMost(remainingCapacity.toUInt()), fetchTimeout = l1MessagesSentFetchTimeout, - blockChunkSize = l1BlockSearchChuck + blockChunkSize = l1BlockSearchChuck, ) } .thenApply { events -> diff --git a/coordinator/ethereum/message-anchoring/src/test/kotlin/linea/anchoring/MessageAnchoringAppTest.kt b/coordinator/ethereum/message-anchoring/src/test/kotlin/linea/anchoring/MessageAnchoringAppTest.kt index 19133f71..ec94e9c5 100644 --- a/coordinator/ethereum/message-anchoring/src/test/kotlin/linea/anchoring/MessageAnchoringAppTest.kt +++ b/coordinator/ethereum/message-anchoring/src/test/kotlin/linea/anchoring/MessageAnchoringAppTest.kt @@ -44,14 +44,14 @@ class MessageAnchoringAppTest { topicsTranslation = mapOf( L1RollingHashUpdatedEvent.topic to "L1RollingHashUpdatedEvent", MessageSentEvent.topic to "MessageSentEvent", - L2RollingHashUpdatedEvent.topic to "L2RollingHashUpdatedEvent" + L2RollingHashUpdatedEvent.topic to "L2RollingHashUpdatedEvent", ), - log = LogManager.getLogger("FakeEthApiClient") + log = LogManager.getLogger("FakeEthApiClient"), ) configureLoggers( rootLevel = Level.INFO, - "FakeEthApiClient" to Level.INFO + "FakeEthApiClient" to Level.INFO, ) } @@ -62,7 +62,7 @@ class MessageAnchoringAppTest { l1EventPollingTimeout: Duration = 2.seconds, l1SuccessBackoffDelay: Duration = 1.milliseconds, messageQueueCapacity: UInt = 100u, - maxMessagesToAnchorPerL2Transaction: UInt = 10u + maxMessagesToAnchorPerL2Transaction: UInt = 10u, ): MessageAnchoringApp { return MessageAnchoringApp( vertx = vertx, @@ -77,15 +77,15 @@ class MessageAnchoringAppTest { l1EventPollingTimeout = l1EventPollingTimeout, l1EventSearchBlockChunk = l1EventSearchBlockChunk, messageQueueCapacity = messageQueueCapacity, - maxMessagesToAnchorPerL2Transaction = maxMessagesToAnchorPerL2Transaction + maxMessagesToAnchorPerL2Transaction = maxMessagesToAnchorPerL2Transaction, ), l1EthApiClient = l1Client, - l2MessageService = l2MessageService + l2MessageService = l2MessageService, ) } private fun addLogsToFakeEthClient( - logs: List + logs: List, ) { l1Client.setLogs(logs.map { listOf(it.l1RollingHashUpdated.log, it.messageSent.log) }.flatten()) } @@ -94,14 +94,14 @@ class MessageAnchoringAppTest { fun `should anchor messages from fresh deployment`() { val ethLogs = createL1MessageSentV1Logs( l1BlocksWithMessages = listOf(100UL, 200UL, 300UL, 400UL, 500UL), - numberOfMessagesPerBlock = 1 + numberOfMessagesPerBlock = 1, ) addLogsToFakeEthClient(ethLogs) val l1PollingInterval = 50.milliseconds val anchoringApp = createApp( l1PollingInterval = l1PollingInterval, anchoringTickInterval = 50.milliseconds, - l1EventSearchBlockChunk = 100u + l1EventSearchBlockChunk = 100u, ) anchoringApp.start().get() val lastFinalizedMessageOnL1 = ethLogs[ethLogs.size - 2] @@ -130,15 +130,15 @@ class MessageAnchoringAppTest { fun `should anchor messages resuming from latest anchored message on L2`() { val ethLogs = createL1MessageSentV1Logs( l1BlocksWithMessages = listOf(100UL, 200UL, 300UL, 400UL), - numberOfMessagesPerBlock = 1 + numberOfMessagesPerBlock = 1, ) l2MessageService.setLastAnchoredL1Message( l1MessageNumber = ethLogs.first().l1RollingHashUpdated.event.messageNumber, - rollingHash = ethLogs.first().l1RollingHashUpdated.event.rollingHash + rollingHash = ethLogs.first().l1RollingHashUpdated.event.rollingHash, ) val anchoringApp = createApp( anchoringTickInterval = 100.milliseconds, - l1EventSearchBlockChunk = 100u + l1EventSearchBlockChunk = 100u, ) anchoringApp.start().get() addLogsToFakeEthClient(ethLogs) @@ -163,12 +163,12 @@ class MessageAnchoringAppTest { fun `should anchor messages in chunks when too many messages are waiting on L1`() { val ethLogs = createL1MessageSentV1Logs( l1BlocksWithMessages = (1UL..100UL).map { it }, - numberOfMessagesPerBlock = 1 + numberOfMessagesPerBlock = 1, ) val anchoringApp = createApp( l1EventSearchBlockChunk = 1000u, maxMessagesToAnchorPerL2Transaction = 20u, - anchoringTickInterval = 1.milliseconds + anchoringTickInterval = 1.milliseconds, ) anchoringApp.start().get() @@ -194,7 +194,7 @@ class MessageAnchoringAppTest { // slow timeout 1 val ethLogs = createL1MessageSentV1Logs( l1BlocksWithMessages = (1UL..100_000UL).step(1000).map { it }, - numberOfMessagesPerBlock = 1 + numberOfMessagesPerBlock = 1, ) val anchoringApp = createApp( l1PollingInterval = 1.milliseconds, @@ -204,7 +204,7 @@ class MessageAnchoringAppTest { l1EventPollingTimeout = 1.milliseconds, l1SuccessBackoffDelay = 3.milliseconds, maxMessagesToAnchorPerL2Transaction = 50u, - anchoringTickInterval = 20.milliseconds + anchoringTickInterval = 20.milliseconds, ) addLogsToFakeEthClient(ethLogs) @@ -231,7 +231,7 @@ class MessageAnchoringAppTest { val ethLogs = createL1MessageSentV1Logs( l1BlocksWithMessages = listOf(100UL, 200UL, 201UL), numberOfMessagesPerBlock = 100, - startingMessageNumber = 1UL + startingMessageNumber = 1UL, ) val messageQueueSoftCap = 20u @@ -242,7 +242,7 @@ class MessageAnchoringAppTest { l1EventPollingTimeout = 1.seconds, messageQueueCapacity = messageQueueSoftCap, maxMessagesToAnchorPerL2Transaction = 50u, - anchoringTickInterval = 10.milliseconds + anchoringTickInterval = 10.milliseconds, ) addLogsToFakeEthClient(ethLogs) @@ -282,7 +282,7 @@ class MessageAnchoringAppTest { private fun createL1MessageSentV1Logs( l1BlocksWithMessages: List, numberOfMessagesPerBlock: Int, - startingMessageNumber: ULong = 1UL + startingMessageNumber: ULong = 1UL, ): List { val ethLogs = mutableListOf() var messageNumber = startingMessageNumber @@ -294,8 +294,8 @@ class MessageAnchoringAppTest { contractAddress = L1_CONTRACT_ADDRESS, messageNumber = messageNumber, messageHash = messageNumber.toHexStringUInt256().decodeHex(), - rollingHash = messageNumber.toHexStringUInt256().decodeHex() - ) + rollingHash = messageNumber.toHexStringUInt256().decodeHex(), + ), ) messageNumber++ } diff --git a/coordinator/ethereum/test-utils/src/main/kotlin/linea/testing/CommandRunner.kt b/coordinator/ethereum/test-utils/src/main/kotlin/linea/testing/CommandRunner.kt index f8fe933c..242d1cc9 100644 --- a/coordinator/ethereum/test-utils/src/main/kotlin/linea/testing/CommandRunner.kt +++ b/coordinator/ethereum/test-utils/src/main/kotlin/linea/testing/CommandRunner.kt @@ -14,7 +14,7 @@ import kotlin.time.Duration.Companion.minutes data class CommandResult( val exitCode: Int, val stdOutLines: List, - val stdErrLines: List + val stdErrLines: List, ) { val isSuccess: Boolean = exitCode == 0 val stdOutStr: String @@ -30,7 +30,7 @@ object Runner { envVars: Map = emptyMap(), executionDir: File = getPathTo("Makefile").parent.toFile(), timeout: Duration = 1.minutes, - log: Logger = LogManager.getLogger(Runner::class.java) + log: Logger = LogManager.getLogger(Runner::class.java), ): SafeFuture { val processBuilder = ProcessBuilder("/bin/sh", "-c", command) processBuilder.directory(executionDir) @@ -52,7 +52,7 @@ object Runner { command, envVars, process.pid(), - process.info() + process.info(), ) process.waitFor(timeout.inWholeMilliseconds, java.util.concurrent.TimeUnit.MILLISECONDS) val futureResult = process @@ -67,15 +67,15 @@ object Runner { processResult.exitValue(), envVars, ProcessHandle.current().pid(), - Thread.currentThread().threadId() + Thread.currentThread().threadId(), ) log.debug( "stdout: {}", - stdOutLines.joinToString("\n") + stdOutLines.joinToString("\n"), ) log.debug( "stderr: {}", - stdErrLines.joinToString("\n") + stdErrLines.joinToString("\n"), ) CommandResult(processResult.exitValue(), stdOutLines, stdErrLines) } @@ -88,7 +88,7 @@ object Runner { envVars: Map = emptyMap(), executionDir: File = getPathTo("Makefile").parent.toFile(), timeout: Duration = 1.minutes, - log: Logger = LogManager.getLogger(Runner::class.java) + log: Logger = LogManager.getLogger(Runner::class.java), ): SafeFuture { return executeCommand(command, envVars, executionDir, timeout, log) .thenCompose { execResult -> diff --git a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/AccountManager.kt b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/AccountManager.kt index 6b0269da..0d6c91b8 100644 --- a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/AccountManager.kt +++ b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/AccountManager.kt @@ -27,7 +27,7 @@ import kotlin.time.Duration.Companion.seconds data class Account( private val _privateKey: String, - private val _address: String + private val _address: String, ) { val privateKey: String get() = _privateKey.replace("0x", "") @@ -37,7 +37,7 @@ data class Account( data class AccountTransactionManager( val account: Account, - val txManager: AsyncFriendlyTransactionManager + val txManager: AsyncFriendlyTransactionManager, ) { val address: String get() = account.address @@ -61,7 +61,7 @@ fun readGenesisFileAccounts(genesisJson: Map): List { fun getTransactionManager( web3JClient: Web3j, - privateKey: String + privateKey: String, ): AsyncFriendlyTransactionManager { val credentials = Credentials.create(privateKey.replace("0x", "")) val receiptPoller = PollingTransactionReceiptProcessor(web3JClient, 100, 4000) @@ -69,7 +69,7 @@ fun getTransactionManager( web3JClient, credentials, chainId = -1, - receiptPoller + receiptPoller, ) } @@ -89,7 +89,7 @@ private open class WhaleBasedAccountManager( genesisFile: Path, val clock: Clock = Clock.System, val testWorkerIdProvider: () -> Long = { ProcessHandle.current().pid() }, - val log: Logger = LogManager.getLogger(WhaleBasedAccountManager::class.java) + val log: Logger = LogManager.getLogger(WhaleBasedAccountManager::class.java), ) : AccountManager { private val whaleAccounts: List final override val chainId: Long @@ -131,7 +131,7 @@ private open class WhaleBasedAccountManager( "Generating accounts: chainId={} numberOfAccounts={} whaleAccount={}", chainId, numberOfAccounts, - whaleAccount.address + whaleAccount.address, ) val result = synchronized(whaleTxManager) { @@ -141,11 +141,13 @@ private open class WhaleBasedAccountManager( val transactionHash = try { retry { whaleTxManager.sendTransaction( - /*gasPrice*/ 300_000_000.toBigInteger(), - /*gasLimit*/ 21000.toBigInteger(), + /*gasPrice*/ + 300_000_000.toBigInteger(), + /*gasLimit*/ + 21000.toBigInteger(), newAccount.address, "", - initialBalanceWei + initialBalanceWei, ) } } catch (e: Exception) { @@ -155,7 +157,7 @@ private open class WhaleBasedAccountManager( "Failed to send funds from accAddress=${whaleAccount.address}, " + "accBalance=$accountBalance, " + "accPrivKey=0x...${whaleAccount.privateKey.takeLast(8)}, " + - "error: ${e.message}" + "error: ${e.message}", ) } newAccount to transactionHash @@ -166,19 +168,19 @@ private open class WhaleBasedAccountManager( "Waiting for account funding: newAccount={} txHash={} whaleAccount={}", account.address, transactionHash, - whaleAccount.address + whaleAccount.address, ) web3jClient.waitForTxReceipt( transactionHash, expectedStatus = "0x1", timeout = 40.seconds, - pollingInterval = 500.milliseconds + pollingInterval = 500.milliseconds, ) if (log.isDebugEnabled) { log.debug( "Account funded: newAccount={} balance={}wei", account.address, - web3jClient.ethGetBalance(account.address, DefaultBlockParameterName.LATEST).send().balance + web3jClient.ethGetBalance(account.address, DefaultBlockParameterName.LATEST).send().balance, ) } } @@ -188,7 +190,7 @@ private open class WhaleBasedAccountManager( override fun getTransactionManager(account: Account): AsyncFriendlyTransactionManager { return getTransactionManager( web3jClient, - account.privateKey + account.privateKey, ) } @@ -199,7 +201,7 @@ private open class WhaleBasedAccountManager( name = "wait-account-balance-${account.address}", daemon = true, initialDelay = 0L, - period = 100L + period = 100L, ) { val balance = web3jClient.ethGetBalance(account.address, DefaultBlockParameterName.LATEST) .send() @@ -211,8 +213,8 @@ private open class WhaleBasedAccountManager( this.cancel() futureResult.completeExceptionally( RuntimeException( - "Timed out ${timeout.inWholeSeconds}s waiting for account=${account.address} to have balance" - ) + "Timed out ${timeout.inWholeSeconds}s waiting for account=${account.address} to have balance", + ), ) } } @@ -224,19 +226,19 @@ private open class WhaleBasedAccountManager( object L1AccountManager : AccountManager by WhaleBasedAccountManager( web3jClient = Web3jClientManager.l1Client, genesisFile = getPathTo(System.getProperty("L1_GENESIS", "docker/config/l1-node/el/genesis.json")), - log = LogManager.getLogger(L1AccountManager::class.java) + log = LogManager.getLogger(L1AccountManager::class.java), ) object L2AccountManager : AccountManager by WhaleBasedAccountManager( web3jClient = Web3jClientManager.l2Client, genesisFile = getPathTo(System.getProperty("L2_GENESIS", "docker/config/linea-local-dev-genesis-PoA-besu.json")), - log = LogManager.getLogger(L2AccountManager::class.java) + log = LogManager.getLogger(L2AccountManager::class.java), ) fun > retry( timeout: Duration = 30.seconds, retryInterval: Duration = 1.seconds, - action: () -> T + action: () -> T, ): R { val start = Clock.System.now() var response: T? = null diff --git a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/ContractsManager.kt b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/ContractsManager.kt index aab7c1e0..0da04936 100644 --- a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/ContractsManager.kt +++ b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/ContractsManager.kt @@ -19,7 +19,7 @@ data class LineaRollupDeploymentResult( val contractDeploymentAccount: Account, val contractDeploymentBlockNumber: ULong, val rollupOperators: List, - val rollupOperatorClient: LineaRollupSmartContractClient + val rollupOperatorClient: LineaRollupSmartContractClient, ) { val rollupOperator: AccountTransactionManager get() = rollupOperators.first() @@ -28,12 +28,12 @@ data class LineaRollupDeploymentResult( data class L2MessageServiceDeploymentResult( val contractAddress: String, val contractDeploymentBlockNumber: ULong, - val anchorerOperator: AccountTransactionManager + val anchorerOperator: AccountTransactionManager, ) data class ContactsDeploymentResult( val lineaRollup: LineaRollupDeploymentResult, - val l2MessageService: L2MessageServiceDeploymentResult + val l2MessageService: L2MessageServiceDeploymentResult, ) interface ContractsManager { @@ -43,7 +43,7 @@ interface ContractsManager { */ fun deployLineaRollup( numberOfOperators: Int = 1, - contractVersion: LineaContractVersion + contractVersion: LineaContractVersion, ): SafeFuture fun deployL2MessageService(): SafeFuture @@ -51,7 +51,7 @@ interface ContractsManager { fun deployRollupAndL2MessageService( dataCompressionAndProofAggregationMigrationBlock: ULong = 1000UL, numberOfOperators: Int = 1, - l1ContractVersion: LineaContractVersion = LineaContractVersion.V6 + l1ContractVersion: LineaContractVersion = LineaContractVersion.V6, ): SafeFuture fun connectToLineaRollupContract( @@ -62,9 +62,9 @@ interface ContractsManager { maxFeePerGas = 55UL.gwei, maxPriorityFeePerGas = 50UL.gwei, maxFeePerBlobGas = 1_000UL.gwei, - gasLimit = 1_000_000uL + gasLimit = 1_000_000uL, ), - smartContractErrors: SmartContractErrors? = null + smartContractErrors: SmartContractErrors? = null, ): LineaRollupSmartContractClient companion object { @@ -87,7 +87,7 @@ object MakeFileDelegatedContractsManager : ContractsManager { override fun deployLineaRollup( numberOfOperators: Int, - contractVersion: LineaContractVersion + contractVersion: LineaContractVersion, ): SafeFuture { val newAccounts = L1AccountManager.generateAccounts(numberOfOperators) val contractDeploymentAccount = newAccounts.first() @@ -95,12 +95,12 @@ object MakeFileDelegatedContractsManager : ContractsManager { log.debug( "going deploy LineaRollup: deployerAccount={} rollupOperators={}", contractDeploymentAccount.address, - operatorsAccounts.map { it.address } + operatorsAccounts.map { it.address }, ) val future = makeDeployLineaRollup( deploymentPrivateKey = contractDeploymentAccount.privateKey, operatorsAddresses = operatorsAccounts.map { it.address }, - contractVersion = contractVersion + contractVersion = contractVersion, ) .thenApply { deploymentResult -> log.debug( @@ -109,7 +109,7 @@ object MakeFileDelegatedContractsManager : ContractsManager { deploymentResult.address, deploymentResult.blockNumber, contractDeploymentAccount.address, - operatorsAccounts.map { it.address } + operatorsAccounts.map { it.address }, ) val accountsTxManagers = operatorsAccounts.map { AccountTransactionManager(it, L1AccountManager.getTransactionManager(it)) @@ -118,14 +118,14 @@ object MakeFileDelegatedContractsManager : ContractsManager { val rollupOperatorClient = connectToLineaRollupContract( deploymentResult.address, accountsTxManagers.first().txManager, - smartContractErrors = lineaRollupContractErrors + smartContractErrors = lineaRollupContractErrors, ) LineaRollupDeploymentResult( contractAddress = deploymentResult.address, contractDeploymentAccount = contractDeploymentAccount, contractDeploymentBlockNumber = deploymentResult.blockNumber.toULong(), rollupOperators = accountsTxManagers, - rollupOperatorClient = rollupOperatorClient + rollupOperatorClient = rollupOperatorClient, ) } return future @@ -135,7 +135,7 @@ object MakeFileDelegatedContractsManager : ContractsManager { val (deployerAccount, anchorerAccount) = L2AccountManager.generateAccounts(2) return makeDeployL2MessageService( deploymentPrivateKey = deployerAccount.privateKey, - anchorOperatorAddresses = anchorerAccount.address + anchorOperatorAddresses = anchorerAccount.address, ) .thenApply { L2MessageServiceDeploymentResult( @@ -143,8 +143,8 @@ object MakeFileDelegatedContractsManager : ContractsManager { contractDeploymentBlockNumber = it.blockNumber.toULong(), anchorerOperator = AccountTransactionManager( account = anchorerAccount, - txManager = L2AccountManager.getTransactionManager(anchorerAccount) - ) + txManager = L2AccountManager.getTransactionManager(anchorerAccount), + ), ) } } @@ -152,13 +152,13 @@ object MakeFileDelegatedContractsManager : ContractsManager { override fun deployRollupAndL2MessageService( dataCompressionAndProofAggregationMigrationBlock: ULong, numberOfOperators: Int, - l1ContractVersion: LineaContractVersion + l1ContractVersion: LineaContractVersion, ): SafeFuture { return deployLineaRollup(numberOfOperators, l1ContractVersion) .thenCombine(deployL2MessageService()) { lineaRollupDeploymentResult, l2MessageServiceDeploymentResult -> ContactsDeploymentResult( lineaRollup = lineaRollupDeploymentResult, - l2MessageService = l2MessageServiceDeploymentResult + l2MessageService = l2MessageServiceDeploymentResult, ) } } @@ -167,14 +167,14 @@ object MakeFileDelegatedContractsManager : ContractsManager { contractAddress: String, transactionManager: AsyncFriendlyTransactionManager, gasProvider: ContractEIP1559GasProvider, - smartContractErrors: SmartContractErrors? + smartContractErrors: SmartContractErrors?, ): LineaRollupSmartContractClient { return Web3JLineaRollupSmartContractClient.load( contractAddress, Web3jClientManager.l1Client, transactionManager, gasProvider, - smartContractErrors ?: lineaRollupContractErrors + smartContractErrors ?: lineaRollupContractErrors, ) } } diff --git a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelper.kt b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelper.kt index 68bf41ff..bcb5df91 100644 --- a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelper.kt +++ b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelper.kt @@ -9,20 +9,20 @@ import java.util.regex.Matcher import java.util.regex.Pattern internal val lineaRollupAddressPattern = Pattern.compile( - "^contract=LineaRollup(?:.*)? deployed: address=(0x[0-9a-fA-F]{40}) blockNumber=(\\d+)" + "^contract=LineaRollup(?:.*)? deployed: address=(0x[0-9a-fA-F]{40}) blockNumber=(\\d+)", ) internal val l2MessageServiceAddressPattern = Pattern.compile( - "^contract=L2MessageService(?:.*)? deployed: address=(0x[0-9a-fA-F]{40}) blockNumber=(\\d+)" + "^contract=L2MessageService(?:.*)? deployed: address=(0x[0-9a-fA-F]{40}) blockNumber=(\\d+)", ) data class DeployedContract( val address: String, - val blockNumber: Long + val blockNumber: Long, ) fun getDeployedAddress( commandResult: CommandResult, - addressPattern: Pattern + addressPattern: Pattern, ): DeployedContract { val lines = commandResult.stdOutLines.toList().asReversed() return getDeployedAddress(lines, addressPattern) @@ -30,7 +30,7 @@ fun getDeployedAddress( fun getDeployedAddress( cmdStdoutLines: List, - addressPattern: Pattern + addressPattern: Pattern, ): DeployedContract { val matcher: Matcher? = cmdStdoutLines .firstOrNull { line -> addressPattern.matcher(line).find() } @@ -50,11 +50,11 @@ fun getDeployedAddress( private fun deployContract( command: String, env: Map = emptyMap(), - addressPattern: Pattern + addressPattern: Pattern, ): SafeFuture { return Runner.executeCommand( command = command, - envVars = env + envVars = env, ) .thenApply { result -> if (result.exitCode != 0) { @@ -63,7 +63,7 @@ private fun deployContract( "Command $command failed: " + "\nexitCode=${result.exitCode} " + "\nSTD_OUT: \n${result.stdOutStr}" + - "\nSTD_ERROR: \n${result.stdErrStr}" + "\nSTD_ERROR: \n${result.stdErrStr}", ) } else { runCatching { getDeployedAddress(result, addressPattern) } @@ -76,10 +76,10 @@ private fun deployContract( fun makeDeployLineaRollup( deploymentPrivateKey: String? = null, operatorsAddresses: List, - contractVersion: LineaContractVersion + contractVersion: LineaContractVersion, ): SafeFuture { val env = mutableMapOf( - "LINEA_ROLLUP_OPERATORS" to operatorsAddresses.joinToString(",") + "LINEA_ROLLUP_OPERATORS" to operatorsAddresses.joinToString(","), // "HARDHAT_DISABLE_CACHE" to "true" ) deploymentPrivateKey?.let { env["DEPLOYMENT_PRIVATE_KEY"] = it } @@ -91,23 +91,23 @@ fun makeDeployLineaRollup( return deployContract( command = command, env = env, - addressPattern = lineaRollupAddressPattern + addressPattern = lineaRollupAddressPattern, ) } fun makeDeployL2MessageService( deploymentPrivateKey: String? = null, - anchorOperatorAddresses: String + anchorOperatorAddresses: String, ): SafeFuture { val env = mutableMapOf( - "L2MSGSERVICE_L1L2_MESSAGE_SETTER" to anchorOperatorAddresses + "L2MSGSERVICE_L1L2_MESSAGE_SETTER" to anchorOperatorAddresses, ) deploymentPrivateKey?.let { env["DEPLOYMENT_PRIVATE_KEY"] = it } return deployContract( command = "make deploy-l2messageservice", env = env, - addressPattern = l2MessageServiceAddressPattern + addressPattern = l2MessageServiceAddressPattern, ) } @@ -124,12 +124,12 @@ fun main() { makeDeployLineaRollup( L1AccountManager.generateAccount().privateKey, listOf("03dfa322A95039BB679771346Ee2dBfEa0e2B773"), - LineaContractVersion.V6 + LineaContractVersion.V6, ), makeDeployL2MessageService( L2AccountManager.generateAccount().privateKey, - "03dfa322A95039BB679771346Ee2dBfEa0e2B773" - ) + "03dfa322A95039BB679771346Ee2dBfEa0e2B773", + ), ).thenApply { addresses -> println("LineaRollup address: ${addresses[0]}") println("L2MessageService address: ${addresses[1]}") diff --git a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/Web3jClientManager.kt b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/Web3jClientManager.kt index b602d0fb..b924323a 100644 --- a/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/Web3jClientManager.kt +++ b/coordinator/ethereum/test-utils/src/main/kotlin/net/consensys/zkevm/ethereum/Web3jClientManager.kt @@ -22,7 +22,7 @@ object Web3jClientManager { rpcUrl: String = l1RpcUrl, log: Logger = LogManager.getLogger("test.clients.l1.web3j-default"), requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): Web3j { return buildWeb3Client(rpcUrl, log, requestResponseLogLevel, failuresLogLevel) } @@ -31,7 +31,7 @@ object Web3jClientManager { rpcUrl: String = l2RpcUrl, log: Logger = LogManager.getLogger("test.clients.l2.web3j-default"), requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): Web3j { return buildWeb3Client(rpcUrl, log, requestResponseLogLevel, failuresLogLevel) } @@ -40,7 +40,7 @@ object Web3jClientManager { rpcUrl: String, log: Logger = LogManager.getLogger("test.clients.web3j"), requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): Web3j { return Web3j.build( HttpService( @@ -48,11 +48,11 @@ object Web3jClientManager { okHttpClientBuilder( logger = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel - ).build() + failuresLogLevel = failuresLogLevel, + ).build(), ), 500, - Async.defaultExecutorService() + Async.defaultExecutorService(), ) } } diff --git a/coordinator/ethereum/test-utils/src/test/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelperKtTest.kt b/coordinator/ethereum/test-utils/src/test/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelperKtTest.kt index aa3b1b15..66566d05 100644 --- a/coordinator/ethereum/test-utils/src/test/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelperKtTest.kt +++ b/coordinator/ethereum/test-utils/src/test/kotlin/net/consensys/zkevm/ethereum/MakefileContractDeploymentHelperKtTest.kt @@ -12,12 +12,12 @@ class MakefileContractDeploymentHelperKtTest { listOf( "L2MessageService artifact has been deployed in 1.2659626659999998s ", "contract=L2MessageService deployed: address=0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6 blockNumber=8", - "" + "", ), - l2MessageServiceAddressPattern - ) + l2MessageServiceAddressPattern, + ), ).isEqualTo( - DeployedContract("0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6", 8) + DeployedContract("0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6", 8), ) assertThat( @@ -25,12 +25,12 @@ class MakefileContractDeploymentHelperKtTest { listOf( "L2MessageServiceV1.2.3 artifact has been deployed in 1.2659626659999998s ", "contract=L2MessageServiceV1.2.3 deployed: address=0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6 blockNumber=8", - "" + "", ), - l2MessageServiceAddressPattern - ) + l2MessageServiceAddressPattern, + ), ).isEqualTo( - DeployedContract("0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6", 8) + DeployedContract("0xFE48d65B84AA0E23594Fd585c11cAD831F90AcB6", 8), ) } @@ -41,12 +41,12 @@ class MakefileContractDeploymentHelperKtTest { listOf( "LineaRollup artifact has been deployed in 1.855172125s ", "contract=LineaRollup deployed: address=0x8613180dF1485B8b87DEE3BCf31896659eb1a092 blockNumber=1414", - "" + "", ), - lineaRollupAddressPattern - ) + lineaRollupAddressPattern, + ), ).isEqualTo( - DeployedContract("0x8613180dF1485B8b87DEE3BCf31896659eb1a092", 1414) + DeployedContract("0x8613180dF1485B8b87DEE3BCf31896659eb1a092", 1414), ) assertThat( @@ -54,12 +54,12 @@ class MakefileContractDeploymentHelperKtTest { listOf( "LineaRollup6.2.1 artifact has been deployed in 1.855172125s ", "contract=LineaRollupV6.2.1 deployed: address=0x8613180dF1485B8b87DEE3BCf31896659eb1a092 blockNumber=1414", - "" + "", ), - lineaRollupAddressPattern - ) + lineaRollupAddressPattern, + ), ).isEqualTo( - DeployedContract("0x8613180dF1485B8b87DEE3BCf31896659eb1a092", 1414) + DeployedContract("0x8613180dF1485B8b87DEE3BCf31896659eb1a092", 1414), ) } } diff --git a/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsPostgresDaoTest.kt b/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsPostgresDaoTest.kt index 129c8021..17486c36 100644 --- a/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsPostgresDaoTest.kt +++ b/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsPostgresDaoTest.kt @@ -59,7 +59,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { l1RollingHashMessageNumber = 4, l2MerkleRoots = listOf("mock_l2MerkleRoots".toByteArray()), l2MerkleTreesDepth = 5, - l2MessagingBlocksOffsets = "mock_l2MessagingBlocksOffsets".toByteArray() + l2MessagingBlocksOffsets = "mock_l2MessagingBlocksOffsets".toByteArray(), ) private var fakeClockTime = Instant.parse("2023-12-11T00:00:00.000Z") @@ -74,7 +74,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { aggregationsPostgresDaoImpl = PostgresAggregationsDao(sqlClient, fakeClock) blobsPostgresDaoImpl = BlobsPostgresDao( BlobsPostgresDao.Config(maxBlobReturnLimit), - sqlClient + sqlClient, ) batchesPostgresDaoImpl = BatchesPostgresDao(sqlClient, fakeClock) } @@ -90,7 +90,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = sampleResponse + aggregationProof = sampleResponse, ) val dbContent1 = performInsertTest(aggregation1) @@ -100,7 +100,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 11UL, endBlockNumber = 12UL, batchCount = 51UL, - aggregationProof = sampleResponse + aggregationProof = sampleResponse, ) val dbContent2 = performInsertTest(aggregation2) @@ -113,7 +113,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = sampleResponse + aggregationProof = sampleResponse, ) val dbContent1 = performInsertTest(aggregation) @@ -127,7 +127,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { .isEqualTo( "Aggregation startBlockNumber=${aggregation.startBlockNumber}, " + "endBlockNumber=${aggregation.endBlockNumber} " + - "batchCount=${aggregation.batchCount} is already persisted!" + "batchCount=${aggregation.batchCount} is already persisted!", ) } } @@ -139,14 +139,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { endBlockNumber = blob.endBlockNumber, startBlockTimestamp = blob.startBlockTime, endBlockTimestamp = blob.endBlockTime, - expectedShnarf = blob.expectedShnarf + expectedShnarf = blob.expectedShnarf, ) return BlobAndBatchCounters( blobCounters = blobCounters, executionProofs = BlockIntervals( startingBlockNumber = blob.startBlockNumber, - upperBoundaries = batches.map { it.endBlockNumber } - ) + upperBoundaries = batches.map { it.endBlockNumber }, + ), ) } @@ -164,7 +164,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { SafeFuture.allOf( SafeFuture.collectAll(batches.map { insertBatch(it) }.stream()), - SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()) + SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()), ).get() aggregationsPostgresDaoImpl.findConsecutiveProvenBlobs(fromBlockNumber = 0).get() @@ -176,8 +176,8 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(blobCounters).hasSameElementsAs( listOf( getBlobAndBatchCounters(listOf(batch1, batch2), blob1), - getBlobAndBatchCounters(listOf(batch3, batch4), blob2) - ) + getBlobAndBatchCounters(listOf(batch3, batch4), blob2), + ), ) } } @@ -200,7 +200,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { SafeFuture.allOf( SafeFuture.collectAll(batches.map { insertBatch(it) }.stream()), - SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()) + SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()), ).get() aggregationsPostgresDaoImpl.findConsecutiveProvenBlobs(fromBlockNumber = 1).get() @@ -208,8 +208,8 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(blobCounters).hasSameElementsAs( listOf( getBlobAndBatchCounters(listOf(batch1, batch2), blob1), - getBlobAndBatchCounters(listOf(batch3, batch4), blob2) - ) + getBlobAndBatchCounters(listOf(batch3, batch4), blob2), + ), ) } } @@ -228,15 +228,15 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { SafeFuture.allOf( SafeFuture.collectAll(batches.map { insertBatch(it) }.stream()), - SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()) + SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()), ).get() aggregationsPostgresDaoImpl.findConsecutiveProvenBlobs(1).get().also { blobCounters -> assertThat(blobCounters).hasSameElementsAs( listOf( getBlobAndBatchCounters(listOf(batch1), blob1), - getBlobAndBatchCounters(listOf(batch2, batch3), blob2) - ) + getBlobAndBatchCounters(listOf(batch2, batch3), blob2), + ), ) } } @@ -266,7 +266,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { SafeFuture.allOf( SafeFuture.collectAll(batches.map { insertBatch(it) }.stream()), - SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()) + SafeFuture.collectAll(blobs.map { insertBlob(it) }.stream()), ).get() aggregationsPostgresDaoImpl.findConsecutiveProvenBlobs(fromBlockNumber = 1).get() @@ -274,8 +274,8 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(blobCounters).hasSameElementsAs( listOf( getBlobAndBatchCounters(listOf(batch1, batch2), blob1), - getBlobAndBatchCounters(listOf(batch3, batch4), blob2) - ) + getBlobAndBatchCounters(listOf(batch3, batch4), blob2), + ), ) } } @@ -287,14 +287,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 10, parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(0), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) val aggregation1 = Aggregation( startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) performInsertTest(aggregation1) @@ -303,21 +303,21 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 20, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:00:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) val aggregation2 = Aggregation( startBlockNumber = 11UL, endBlockNumber = 20UL, batchCount = 5UL, - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) performInsertTest(aggregation2) aggregationsPostgresDaoImpl.getProofsToFinalize( 1L, aggregationProof1.finalTimestamp, - 1 + 1, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(listOf(aggregationProof1)) @@ -325,7 +325,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { aggregationsPostgresDaoImpl.getProofsToFinalize( 11L, aggregationProof2.finalTimestamp, - 1 + 1, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(listOf(aggregationProof2)) @@ -333,7 +333,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { aggregationsPostgresDaoImpl.getProofsToFinalize( 1L, aggregationProof1.finalTimestamp, - 2 + 2, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(listOf(aggregationProof1, aggregationProof2)) @@ -347,14 +347,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 10, parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(0), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) val aggregation1 = Aggregation( startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) performInsertTest(aggregation1) @@ -363,14 +363,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 20, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:00:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:01:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:01:00Z"), ) val aggregation2 = Aggregation( startBlockNumber = 11UL, endBlockNumber = 20UL, batchCount = 5UL, - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) performInsertTest(aggregation2) @@ -379,14 +379,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 39, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:01:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:02:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:02:00Z"), ) val aggregation3 = Aggregation( startBlockNumber = 31UL, endBlockNumber = 39UL, batchCount = 5UL, - aggregationProof = aggregationProof3 + aggregationProof = aggregationProof3, ) performInsertTest(aggregation3) @@ -395,21 +395,21 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 50, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:01:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:02:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:02:00Z"), ) val aggregation4 = Aggregation( startBlockNumber = 40UL, endBlockNumber = 50UL, batchCount = 5UL, - aggregationProof = aggregationProof4 + aggregationProof = aggregationProof4, ) performInsertTest(aggregation4) aggregationsPostgresDaoImpl.getProofsToFinalize( 1L, aggregationProof4.finalTimestamp, - 5 + 5, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(listOf(aggregationProof1, aggregationProof2)) @@ -418,7 +418,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { aggregationsPostgresDaoImpl.getProofsToFinalize( 31L, aggregationProof4.finalTimestamp, - 5 + 5, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(listOf(aggregationProof3, aggregationProof4)) @@ -432,14 +432,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 20, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:00:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:01:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:01:00Z"), ) val aggregation1 = Aggregation( startBlockNumber = 11UL, endBlockNumber = 20UL, batchCount = 5UL, - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) performInsertTest(aggregation1) @@ -448,21 +448,21 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 30, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:01:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:02:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:02:00Z"), ) val aggregation2 = Aggregation( startBlockNumber = 21UL, endBlockNumber = 30UL, batchCount = 5UL, - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) performInsertTest(aggregation2) aggregationsPostgresDaoImpl.getProofsToFinalize( 1L, aggregationProof2.finalTimestamp, - 3 + 3, ).get().also { aggregation -> assertThat(aggregation).isNotNull assertThat(aggregation).isEqualTo(emptyList()) @@ -476,7 +476,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 1UL, endBlockNumber = 20UL, batchCount = 10UL, - aggregationProof = null // proof can be omitted here as not the focus of the test + aggregationProof = null, // proof can be omitted here as not the focus of the test ) aggregationsPostgresDaoImpl.saveNewAggregation(aggregation1).get() @@ -486,7 +486,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 31UL, endBlockNumber = 39UL, batchCount = 5UL, - aggregationProof = null // proof can be omitted here as not the focus of the test + aggregationProof = null, // proof can be omitted here as not the focus of the test ) aggregationsPostgresDaoImpl.saveNewAggregation(aggregation2).get() @@ -495,34 +495,34 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { startBlockNumber = 40UL, endBlockNumber = 50UL, batchCount = 5UL, - aggregationProof = null // proof can be omitted here as not the focus of the test + aggregationProof = null, // proof can be omitted here as not the focus of the test ) aggregationsPostgresDaoImpl.saveNewAggregation(aggregation3).get() // should return 20L as aggregation of blocks 1..20 exists in db aggregationsPostgresDaoImpl.findHighestConsecutiveEndBlockNumber( - 1L + 1L, ).get().also { highestEndBlockNumber -> assertThat(highestEndBlockNumber).isEqualTo(20L) } // should return null as there is no aggregation with start block number as 21L aggregationsPostgresDaoImpl.findHighestConsecutiveEndBlockNumber( - 21L + 21L, ).get().also { highestEndBlockNumber -> assertThat(highestEndBlockNumber).isNull() } // should return 50L as aggregations of blocks 31..39 and blocks 40..50 exist in db aggregationsPostgresDaoImpl.findHighestConsecutiveEndBlockNumber( - 31L + 31L, ).get().also { highestEndBlockNumber -> assertThat(highestEndBlockNumber).isEqualTo(50L) } // should return 50L as aggregation of blocks 40..50 exists in db aggregationsPostgresDaoImpl.findHighestConsecutiveEndBlockNumber( - 40L + 40L, ).get().also { highestEndBlockNumber -> assertThat(highestEndBlockNumber).isEqualTo(50L) } @@ -535,14 +535,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 10, parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(0L), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) val aggregation1 = Aggregation( startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) performInsertTest(aggregation1) @@ -551,14 +551,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 20, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:00:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:01:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:01:00Z"), ) val aggregation2 = Aggregation( startBlockNumber = 11UL, endBlockNumber = 20UL, batchCount = 5UL, - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) performInsertTest(aggregation2) @@ -567,14 +567,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 30, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:01:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:02:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:02:00Z"), ) val aggregation3 = Aggregation( startBlockNumber = 21UL, endBlockNumber = 30UL, batchCount = 5UL, - aggregationProof = aggregationProof3 + aggregationProof = aggregationProof3, ) performInsertTest(aggregation3) @@ -595,14 +595,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 10, parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(0L), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) val aggregation1 = Aggregation( startBlockNumber = 1UL, endBlockNumber = 10UL, batchCount = 5UL, - aggregationProof = aggregationProof1 + aggregationProof = aggregationProof1, ) performInsertTest(aggregation1) @@ -611,14 +611,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 20, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:00:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:01:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:01:00Z"), ) val aggregation2 = Aggregation( startBlockNumber = 11UL, endBlockNumber = 20UL, batchCount = 5UL, - aggregationProof = aggregationProof2 + aggregationProof = aggregationProof2, ) performInsertTest(aggregation2) @@ -627,14 +627,14 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { finalBlockNumber = 30, parentAggregationLastBlockTimestamp = Instant.parse("2024-04-28T15:01:00Z"), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:02:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:02:00Z"), ) val aggregation3 = Aggregation( startBlockNumber = 21UL, endBlockNumber = 30UL, batchCount = 5UL, - aggregationProof = aggregationProof3 + aggregationProof = aggregationProof3, ) performInsertTest(aggregation3) @@ -652,15 +652,15 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { fun `findAggregationProofByEndBlockNumber when multiple aggregations found throws error`() { val aggregation1 = createAggregation( startBlockNumber = 1, - endBlockNumber = 10 + endBlockNumber = 10, ) val aggregation2 = createAggregation( startBlockNumber = 5, - endBlockNumber = 10 + endBlockNumber = 10, ) SafeFuture.collectAll( aggregationsPostgresDaoImpl.saveNewAggregation(aggregation1), - aggregationsPostgresDaoImpl.saveNewAggregation(aggregation2) + aggregationsPostgresDaoImpl.saveNewAggregation(aggregation2), ).get() assertThat(aggregationsPostgresDaoImpl.findAggregationProofByEndBlockNumber(10)) @@ -674,15 +674,15 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { fun `findAggregationProofByEndBlockNumber when single aggregation found returns it`() { val aggregation1 = createAggregation( startBlockNumber = 1, - endBlockNumber = 4 + endBlockNumber = 4, ) val aggregation2 = createAggregation( endBlockNumber = 10, - parentAggregation = aggregation1 + parentAggregation = aggregation1, ) SafeFuture.collectAll( aggregationsPostgresDaoImpl.saveNewAggregation(aggregation1), - aggregationsPostgresDaoImpl.saveNewAggregation(aggregation2) + aggregationsPostgresDaoImpl.saveNewAggregation(aggregation2), ).get() assertThat(aggregationsPostgresDaoImpl.findAggregationProofByEndBlockNumber(10)) @@ -694,7 +694,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { fun `findAggregationProofByEndBlockNumber when no aggregation is found returns null`() { val aggregation1 = createAggregation( startBlockNumber = 1, - endBlockNumber = 4 + endBlockNumber = 4, ) aggregationsPostgresDaoImpl.saveNewAggregation(aggregation1).get() @@ -704,7 +704,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { } private fun performInsertTest( - aggregation: Aggregation + aggregation: Aggregation, ): RowSet? { aggregationsPostgresDaoImpl.saveNewAggregation(aggregation).get() val dbContent = DbQueries.getTableContent(sqlClient, DbQueries.aggregationsTable).execute().get() @@ -726,7 +726,7 @@ class AggregationsPostgresDaoTest : CleanDbTestSuiteParallel() { } private fun insertBatch( - batch: Batch + batch: Batch, ): SafeFuture { return batchesPostgresDaoImpl.saveNewBatch(batch) } diff --git a/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandlerTest.kt b/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandlerTest.kt index ece48bdd..cea9b16f 100644 --- a/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandlerTest.kt +++ b/coordinator/persistence/aggregation/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandlerTest.kt @@ -47,27 +47,27 @@ class RecordsCleanupFinalizationHandlerTest : CleanDbTestSuiteParallel() { batchesRepository = PostgresBatchesRepository( BatchesPostgresDao( connection = sqlClient, - clock = fakeClock - ) + clock = fakeClock, + ), ) blobsRepository = BlobsRepositoryImpl( BlobsPostgresDao( config = BlobsPostgresDao.Config(maxBlobsToReturn = 10u), connection = sqlClient, - clock = fakeClock - ) + clock = fakeClock, + ), ) aggregationsRepository = AggregationsRepositoryImpl( PostgresAggregationsDao( connection = sqlClient, - clock = fakeClock - ) + clock = fakeClock, + ), ) recordsCleanupFinalizationHandler = RecordsCleanupFinalizationHandler( batchesRepository, blobsRepository, - aggregationsRepository + aggregationsRepository, ) } @@ -96,18 +96,18 @@ class RecordsCleanupFinalizationHandlerTest : CleanDbTestSuiteParallel() { val aggregation1 = createAggregation( startBlockNumber = blob1.startBlockNumber.toLong(), endBlockNumber = blob1.endBlockNumber.toLong(), - batchCount = blob1.batchesCount.toLong() + batchCount = blob1.batchesCount.toLong(), ) val aggregation2 = createAggregation( startBlockNumber = blob2.startBlockNumber.toLong(), endBlockNumber = blob2.endBlockNumber.toLong(), - batchCount = blob2.batchesCount.toLong() + batchCount = blob2.batchesCount.toLong(), ) val aggregation3 = createAggregation( startBlockNumber = blob3.startBlockNumber.toLong(), endBlockNumber = blob3.endBlockNumber.toLong(), - batchCount = blob3.batchesCount.toLong() + batchCount = blob3.batchesCount.toLong(), ) val aggregations = listOf(aggregation1, aggregation2, aggregation3) @@ -125,7 +125,7 @@ class RecordsCleanupFinalizationHandlerTest : CleanDbTestSuiteParallel() { aggregationsRepository.saveNewAggregation(aggregation1), aggregationsRepository.saveNewAggregation(aggregation2), - aggregationsRepository.saveNewAggregation(aggregation3) + aggregationsRepository.saveNewAggregation(aggregation3), ).get() } @@ -135,7 +135,7 @@ class RecordsCleanupFinalizationHandlerTest : CleanDbTestSuiteParallel() { val update = FinalizationMonitor.FinalizationUpdate( blockNumber = 21u, blockHash = Bytes32.random(), - zkStateRootHash = Bytes32.random() + zkStateRootHash = Bytes32.random(), ) val batchesBeforeCleanup = batchesContentQuery().execute().get() @@ -160,7 +160,7 @@ class RecordsCleanupFinalizationHandlerTest : CleanDbTestSuiteParallel() { val aggregationsAfterCleanup = aggregationsContentQuery().execute().get() Assertions.assertThat(aggregationsAfterCleanup.size()).isEqualTo(1) Assertions.assertThat( - aggregationsRepository.findAggregationProofByEndBlockNumber(aggregation3.endBlockNumber.toLong()).get() + aggregationsRepository.findAggregationProofByEndBlockNumber(aggregation3.endBlockNumber.toLong()).get(), ) .isNotNull() } diff --git a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsDao.kt b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsDao.kt index 4f23c6c9..4bab478c 100644 --- a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsDao.kt +++ b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsDao.kt @@ -36,11 +36,11 @@ interface AggregationsDao { fun getProofsToFinalize( fromBlockNumber: Long, finalEndBlockCreatedBefore: Instant, - maximumNumberOfProofs: Int + maximumNumberOfProofs: Int, ): SafeFuture> fun findHighestConsecutiveEndBlockNumber( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findAggregationProofByEndBlockNumber(endBlockNumber: Long): SafeFuture diff --git a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsRepositoryImpl.kt b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsRepositoryImpl.kt index dae28338..b115969c 100644 --- a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsRepositoryImpl.kt +++ b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/AggregationsRepositoryImpl.kt @@ -9,10 +9,10 @@ import net.consensys.zkevm.persistence.db.DuplicatedRecordException import tech.pegasys.teku.infrastructure.async.SafeFuture class AggregationsRepositoryImpl( - private val aggregationsPostgresDao: AggregationsDao + private val aggregationsPostgresDao: AggregationsDao, ) : AggregationsRepository { override fun findConsecutiveProvenBlobs( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture> { return aggregationsPostgresDao.findConsecutiveProvenBlobs(fromBlockNumber) } @@ -31,17 +31,17 @@ class AggregationsRepositoryImpl( override fun getProofsToFinalize( fromBlockNumber: Long, finalEndBlockCreatedBefore: Instant, - maximumNumberOfProofs: Int + maximumNumberOfProofs: Int, ): SafeFuture> { return aggregationsPostgresDao.getProofsToFinalize( fromBlockNumber, finalEndBlockCreatedBefore, - maximumNumberOfProofs + maximumNumberOfProofs, ) } override fun findHighestConsecutiveEndBlockNumber( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return aggregationsPostgresDao.findHighestConsecutiveEndBlockNumber(fromBlockNumber) } diff --git a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/PostgresAggregationsDao.kt b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/PostgresAggregationsDao.kt index 8f343859..10d32c5b 100644 --- a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/PostgresAggregationsDao.kt +++ b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/PostgresAggregationsDao.kt @@ -24,7 +24,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class PostgresAggregationsDao( connection: SqlClient, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : AggregationsDao { private val log = LogManager.getLogger(this.javaClass.name) private val queryLog = SQLQueryLogger(log) @@ -114,7 +114,7 @@ class PostgresAggregationsDao( ORDER BY bl.start_block_number ASC ) select * from final_blobs - """.trimIndent() + """.trimIndent(), ) private val insertQuery = @@ -123,7 +123,7 @@ class PostgresAggregationsDao( insert into $aggregationsTable (start_block_number, end_block_number, status, start_block_timestamp, batch_count, aggregation_proof) VALUES ($1, $2, $3, $4, $5, CAST($6::text as jsonb)) - """.trimIndent() + """.trimIndent(), ) private val selectAggregations = @@ -144,7 +144,7 @@ class PostgresAggregationsDao( and (previous_ends.previous_end_block_number = previous_ends.start_block_number - 1 or previous_ends.start_block_number = $1) and ((select count(1) from first_gapped_aggregation) = 0 or previous_ends.start_block_number < (select * from first_gapped_aggregation)) limit $3 - """.trimIndent() + """.trimIndent(), ) private val findAggregationByEndBlockNumber = @@ -153,7 +153,7 @@ class PostgresAggregationsDao( select * from $aggregationsTable where end_block_number = $1 LIMIT 2 - """.trimIndent() + """.trimIndent(), ) private val deleteUptoQuery = @@ -161,7 +161,7 @@ class PostgresAggregationsDao( """ delete from $aggregationsTable where end_block_number <= $1 - """.trimIndent() + """.trimIndent(), ) private val deleteAfterQuery = @@ -169,7 +169,7 @@ class PostgresAggregationsDao( """ delete from $aggregationsTable where start_block_number >= $1 - """.trimIndent() + """.trimIndent(), ) private fun parseBatchAnbBlobRecord(record: Row): BatchRecordWithBlobInfo { @@ -181,7 +181,7 @@ class PostgresAggregationsDao( blobExpectedShnarf = record.getString("blob_expected_shnarf").decodeHex(), batchesCount = record.getLong("batches_count").toUInt(), batchStartBlockNumber = record.getLong("start_block_number").toULong(), - batchEndBlockNumber = record.getLong("end_block_number").toULong() + batchEndBlockNumber = record.getLong("end_block_number").toULong(), ) } @@ -193,11 +193,11 @@ class PostgresAggregationsDao( val blobExpectedShnarf: ByteArray, val batchesCount: UInt, val batchStartBlockNumber: ULong, - val batchEndBlockNumber: ULong + val batchEndBlockNumber: ULong, ) override fun findConsecutiveProvenBlobs( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture> { return selectBatchesAndBlobsForAggregation .execute(Tuple.of(fromBlockNumber)) @@ -214,14 +214,14 @@ class PostgresAggregationsDao( endBlockNumber = firstBatch.blobEndBlockNumber, startBlockTimestamp = firstBatch.blobStartBlockTimestamp, endBlockTimestamp = firstBatch.blobEndBlockTimestamp, - expectedShnarf = firstBatch.blobExpectedShnarf + expectedShnarf = firstBatch.blobExpectedShnarf, ) BlobAndBatchCounters( blobCounters = blobCounters, executionProofs = BlockIntervals( startingBlockNumber = batches.first().batchStartBlockNumber, - upperBoundaries = batches.map { it.batchEndBlockNumber } - ) + upperBoundaries = batches.map { it.batchEndBlockNumber }, + ), ) } .filter { @@ -250,7 +250,7 @@ class PostgresAggregationsDao( status, clock.now().toEpochMilliseconds(), batchCount, - aggregationProof + aggregationProof, ) queryLog.log(Level.TRACE, insertQuery.toString(), params) return insertQuery.execute(Tuple.tuple(params)) @@ -263,8 +263,8 @@ class PostgresAggregationsDao( DuplicatedRecordException( "Aggregation startBlockNumber=$startBlockNumber, endBlockNumber=$endBlockNumber " + "batchCount=$batchCount is already persisted!", - th - ) + th, + ), ) } else { Future.failedFuture(th) @@ -276,15 +276,15 @@ class PostgresAggregationsDao( override fun getProofsToFinalize( fromBlockNumber: Long, finalEndBlockCreatedBefore: Instant, - maximumNumberOfProofs: Int + maximumNumberOfProofs: Int, ): SafeFuture> { return selectAggregations .execute( Tuple.of( fromBlockNumber, aggregationStatusToDbValue(Aggregation.Status.Proven), - maximumNumberOfProofs - ) + maximumNumberOfProofs, + ), ) .toSafeFuture() .thenApply { rowSet -> @@ -295,15 +295,15 @@ class PostgresAggregationsDao( } override fun findHighestConsecutiveEndBlockNumber( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return selectAggregations .execute( Tuple.of( fromBlockNumber, aggregationStatusToDbValue(Aggregation.Status.Proven), - Int.MAX_VALUE - ) + Int.MAX_VALUE, + ), ) .toSafeFuture() .thenApply { rowSet -> @@ -314,7 +314,7 @@ class PostgresAggregationsDao( override fun findAggregationProofByEndBlockNumber(endBlockNumber: Long): SafeFuture { return findAggregationByEndBlockNumber .execute( - Tuple.of(endBlockNumber) + Tuple.of(endBlockNumber), ) .toSafeFuture() .thenApply { rowSet -> @@ -324,7 +324,7 @@ class PostgresAggregationsDao( // if this happens, a conflation invariant was broken throw IllegalStateException( "Multiple aggregations found for endBlockNumber=$endBlockNumber " + - "aggregations=${aggregationProofs.toBlockIntervalsString()}" + "aggregations=${aggregationProofs.toBlockIntervalsString()}", ) } else { aggregationProofs.firstOrNull() diff --git a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandler.kt b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandler.kt index 893116f5..a1910bad 100644 --- a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandler.kt +++ b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RecordsCleanupFinalizationHandler.kt @@ -10,7 +10,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RecordsCleanupFinalizationHandler( private val batchesRepository: BatchesRepository, private val blobsRepository: BlobsRepository, - private val aggregationsRepository: AggregationsRepository + private val aggregationsRepository: AggregationsRepository, ) : FinalizationHandler { override fun handleUpdate(update: FinalizationMonitor.FinalizationUpdate): SafeFuture<*> { // We do not need to keep batches, blobs and aggregation objects in the DB that are not needed after finalization. @@ -41,7 +41,7 @@ class RecordsCleanupFinalizationHandler( val batchesCleanup = batchesRepository.deleteBatchesUpToEndBlockNumber(update.blockNumber.toLong()) val blobsCleanup = blobsRepository.deleteBlobsUpToEndBlockNumber( - endBlockNumberInclusive = update.blockNumber - 1u + endBlockNumberInclusive = update.blockNumber - 1u, ) val aggregationsCleanup = aggregationsRepository .deleteAggregationsUpToEndBlockNumber(endBlockNumberInclusive = update.blockNumber.toLong() - 1L) diff --git a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDao.kt b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDao.kt index a8a71d84..dd1178e3 100644 --- a/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDao.kt +++ b/coordinator/persistence/aggregation/src/main/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDao.kt @@ -9,11 +9,11 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RetryingPostgresAggregationsDao( private val delegate: PostgresAggregationsDao, - private val persistenceRetryer: PersistenceRetryer + private val persistenceRetryer: PersistenceRetryer, ) : AggregationsDao { override fun findConsecutiveProvenBlobs(fromBlockNumber: Long): SafeFuture> { return persistenceRetryer.retryQuery( - { delegate.findConsecutiveProvenBlobs(fromBlockNumber) } + { delegate.findConsecutiveProvenBlobs(fromBlockNumber) }, ) } @@ -24,26 +24,26 @@ class RetryingPostgresAggregationsDao( override fun getProofsToFinalize( fromBlockNumber: Long, finalEndBlockCreatedBefore: Instant, - maximumNumberOfProofs: Int + maximumNumberOfProofs: Int, ): SafeFuture> { return persistenceRetryer.retryQuery( { delegate.getProofsToFinalize( fromBlockNumber, finalEndBlockCreatedBefore, - maximumNumberOfProofs + maximumNumberOfProofs, ) - } + }, ) } override fun findHighestConsecutiveEndBlockNumber( - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return persistenceRetryer.retryQuery( { delegate.findHighestConsecutiveEndBlockNumber(fromBlockNumber) - } + }, ) } diff --git a/coordinator/persistence/aggregation/src/test/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDaoTest.kt b/coordinator/persistence/aggregation/src/test/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDaoTest.kt index 19728d33..f9c9f5ab 100644 --- a/coordinator/persistence/aggregation/src/test/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDaoTest.kt +++ b/coordinator/persistence/aggregation/src/test/kotlin/net/consensys/zkevm/persistence/dao/aggregation/RetryingPostgresAggregationsDaoTest.kt @@ -29,7 +29,7 @@ class RetryingPostgresAggregationsDaoTest { private val createdBeforeInstant = fakeClock.now() private val aggregation = createAggregation( startBlockNumber = 1, - endBlockNumber = 10 + endBlockNumber = 10, ) @BeforeEach @@ -39,15 +39,15 @@ class RetryingPostgresAggregationsDaoTest { PersistenceRetryer( vertx = vertx, PersistenceRetryer.Config( - backoffDelay = 1.milliseconds - ) - ) + backoffDelay = 1.milliseconds, + ), + ), ) val baseBlobCounters = blobCounters(startBlockNumber = 1uL, endBlockNumber = 10uL) val baseBlobAndBatchCounters = BlobAndBatchCounters( blobCounters = baseBlobCounters, - executionProofs = BlockIntervals(1UL, listOf(2UL, 3UL)) + executionProofs = BlockIntervals(1UL, listOf(2UL, 3UL)), ) val aggregationProof = createProofToFinalize( @@ -55,7 +55,7 @@ class RetryingPostgresAggregationsDaoTest { finalBlockNumber = 10, parentAggregationLastBlockTimestamp = Instant.fromEpochSeconds(0), startBlockTime = Instant.fromEpochSeconds(0), - finalTimestamp = Instant.parse("2024-04-28T15:00:00Z") + finalTimestamp = Instant.parse("2024-04-28T15:00:00Z"), ) whenever(delegateAggregationsDao.findConsecutiveProvenBlobs(eq(0L))) @@ -68,15 +68,15 @@ class RetryingPostgresAggregationsDaoTest { delegateAggregationsDao.getProofsToFinalize( eq(0L), eq(createdBeforeInstant), - eq(1) - ) + eq(1), + ), ) .thenReturn(SafeFuture.completedFuture(listOf(aggregationProof))) whenever( delegateAggregationsDao.findHighestConsecutiveEndBlockNumber( - eq(0L) - ) + eq(0L), + ), ) .thenReturn(SafeFuture.completedFuture(10L)) @@ -101,12 +101,12 @@ class RetryingPostgresAggregationsDaoTest { retryingAggregationsPostgresDao.getProofsToFinalize( fromBlockNumber = 0L, finalEndBlockCreatedBefore = createdBeforeInstant, - maximumNumberOfProofs = 1 + maximumNumberOfProofs = 1, ) verify(delegateAggregationsDao, times(1)).getProofsToFinalize( eq(0L), eq(createdBeforeInstant), - eq(1) + eq(1), ) retryingAggregationsPostgresDao.findHighestConsecutiveEndBlockNumber(0L) diff --git a/coordinator/persistence/batch/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDaoTest.kt b/coordinator/persistence/batch/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDaoTest.kt index c3f8c8d8..f8a97dfc 100644 --- a/coordinator/persistence/batch/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDaoTest.kt +++ b/coordinator/persistence/batch/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDaoTest.kt @@ -42,7 +42,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { batchesDao = BatchesPostgresDao( sqlClient, - fakeClock + fakeClock, ) } @@ -58,7 +58,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { val batch1 = Batch( expectedStartBlock1, - expectedEndBlock1 + expectedEndBlock1, ) val dbContent1 = @@ -69,7 +69,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { val expectedEndBlock2 = 9UL val batch2 = Batch( expectedStartBlock2, - expectedEndBlock2 + expectedEndBlock2, ) fakeClock.advanceBy(1.seconds) @@ -79,7 +79,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { } private fun performInsertTest( - batch: Batch + batch: Batch, ): RowSet? { batchesDao.saveNewBatch(batch).get() val dbContent = batchesContentQuery().execute().get() @@ -102,7 +102,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { val batch1 = Batch( expectedStartBlock1, - expectedEndBlock1 + expectedEndBlock1, ) val dbContent1 = @@ -115,7 +115,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(executionException.cause).isInstanceOf(DuplicatedRecordException::class.java) assertThat(executionException.cause!!.message) .isEqualTo( - "Batch startBlockNumber=1, endBlockNumber=1 is already persisted!" + "Batch startBlockNumber=1, endBlockNumber=1 is already persisted!", ) } } @@ -125,13 +125,13 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(1L) - .get() + .get(), ).isEqualTo(null) assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(1L) - .get() + .get(), ).isEqualTo(null) } @@ -145,14 +145,14 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { // Gap, query does not care about gaps createBatch(31, 32), // Gap, query does not care about gaps - createBatch(40, 42) + createBatch(40, 42), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(20L) - .get() + .get(), ) .isEqualTo(batches[2].endBlockNumber.toLong()) } @@ -164,14 +164,14 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { createBatch(1, 3), createBatch(4, 5), createBatch(6, 7), - createBatch(8, 10) + createBatch(8, 10), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(1L) - .get() + .get(), ) .isEqualTo(batches[3].endBlockNumber.toLong()) } @@ -181,14 +181,14 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { val batches = listOf( createBatch(1, 3), - createBatch(4, 5) + createBatch(4, 5), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(1L) - .get() + .get(), ) .isEqualTo(batches[1].endBlockNumber.toLong()) } @@ -198,14 +198,14 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { val batches = listOf( createBatch(1, 3), - createBatch(4, 5) + createBatch(4, 5), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .findHighestConsecutiveEndBlockNumberFromBlockNumber(5L) - .get() + .get(), ) .isNull() } @@ -217,7 +217,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { createBatch(1, 3), createBatch(4, 5), createBatch(6, 7), - createBatch(10, 11) + createBatch(10, 11), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() @@ -229,9 +229,9 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat( batchesDao .deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive = 6L + endBlockNumberInclusive = 6L, ) - .get() + .get(), ) .isEqualTo(2) @@ -245,16 +245,16 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { listOf( createBatch(1, 3), createBatch(4, 5), - createBatch(6, 7) + createBatch(6, 7), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive = 1L + endBlockNumberInclusive = 1L, ) - .get() + .get(), ) .isEqualTo(0) @@ -269,7 +269,7 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { createBatch(1, 3), createBatch(4, 5), createBatch(6, 7), - createBatch(10, 11) + createBatch(10, 11), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() @@ -281,9 +281,9 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat( batchesDao .deleteBatchesAfterBlockNumber( - startingBlockNumberInclusive = 6L + startingBlockNumberInclusive = 6L, ) - .get() + .get(), ) .isEqualTo(2) @@ -300,16 +300,16 @@ class BatchesPostgresDaoTest : CleanDbTestSuiteParallel() { listOf( createBatch(1, 3), createBatch(4, 5), - createBatch(6, 7) + createBatch(6, 7), ) SafeFuture.collectAll(batches.map { batchesDao.saveNewBatch(it) }.stream()).get() assertThat( batchesDao .deleteBatchesAfterBlockNumber( - startingBlockNumberInclusive = 7L + startingBlockNumberInclusive = 7L, ) - .get() + .get(), ) .isEqualTo(0) diff --git a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchProofHandlerImpl.kt b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchProofHandlerImpl.kt index 176cb665..b55ecfac 100644 --- a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchProofHandlerImpl.kt +++ b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchProofHandlerImpl.kt @@ -8,7 +8,7 @@ import org.apache.logging.log4j.LogManager import tech.pegasys.teku.infrastructure.async.SafeFuture class BatchProofHandlerImpl( - private val batchesRepository: BatchesRepository + private val batchesRepository: BatchesRepository, ) : BatchProofHandler { private val log = LogManager.getLogger(this::class.java) override fun acceptNewBatch(batch: Batch): SafeFuture { @@ -18,7 +18,7 @@ class BatchProofHandlerImpl( log.debug( "Ignoring Batch already persisted error. batch={} errorMessage={}", batch.intervalString(), - th.message + th.message, ) SafeFuture.completedFuture(Unit) } else { diff --git a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesDao.kt b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesDao.kt index 3e05e8fc..a299debb 100644 --- a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesDao.kt +++ b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesDao.kt @@ -7,14 +7,14 @@ interface BatchesDao { fun saveNewBatch(batch: Batch): SafeFuture fun findHighestConsecutiveEndBlockNumberFromBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture fun deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive: Long + endBlockNumberInclusive: Long, ): SafeFuture fun deleteBatchesAfterBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture } diff --git a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDao.kt b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDao.kt index 5d271f26..db1eb0d8 100644 --- a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDao.kt +++ b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/BatchesPostgresDao.kt @@ -15,7 +15,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class BatchesPostgresDao( connection: SqlClient, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : BatchesDao { private val log = LogManager.getLogger(this.javaClass.name) private val queryLog = SQLQueryLogger(log) @@ -84,7 +84,7 @@ class BatchesPostgresDao( .trimIndent() private val findHighestConsecutiveEndBlockNumberQuery = connection.preparedQuery( - findHighestConsecutiveEndBlockNumberSql + findHighestConsecutiveEndBlockNumberSql, ) private val insertQuery = connection.preparedQuery(insertSql) private val deleteUptoQuery = connection.preparedQuery(deleteUptoSql) @@ -98,7 +98,7 @@ class BatchesPostgresDao( clock.now().toEpochMilliseconds(), startBlockNumber, endBlockNumber, - batchStatusToDbValue(Batch.Status.Proven) + batchStatusToDbValue(Batch.Status.Proven), ) queryLog.log(Level.TRACE, insertSql, params) return insertQuery.execute(Tuple.tuple(params)) @@ -109,8 +109,8 @@ class BatchesPostgresDao( DuplicatedRecordException( "Batch startBlockNumber=$startBlockNumber, endBlockNumber=$endBlockNumber " + "is already persisted!", - th - ) + th, + ), ) } else { Future.failedFuture(th) @@ -120,7 +120,7 @@ class BatchesPostgresDao( } override fun findHighestConsecutiveEndBlockNumberFromBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture { val params = listOf(startingBlockNumberInclusive) queryLog.log(Level.TRACE, findHighestConsecutiveEndBlockNumberSql, params) @@ -133,13 +133,13 @@ class BatchesPostgresDao( } override fun deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive: Long + endBlockNumberInclusive: Long, ): SafeFuture { return deleteUptoQuery .execute( Tuple.of( - endBlockNumberInclusive - ) + endBlockNumberInclusive, + ), ) .map { rowSet -> rowSet.rowCount() } .toSafeFuture() @@ -149,8 +149,8 @@ class BatchesPostgresDao( return deleteAfterQuery .execute( Tuple.of( - startingBlockNumberInclusive - ) + startingBlockNumberInclusive, + ), ) .map { rowSet -> rowSet.rowCount() } .toSafeFuture() diff --git a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/PostgresBatchesRepository.kt b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/PostgresBatchesRepository.kt index a152c984..86e9dbdd 100644 --- a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/PostgresBatchesRepository.kt +++ b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/PostgresBatchesRepository.kt @@ -5,26 +5,26 @@ import net.consensys.zkevm.persistence.BatchesRepository import tech.pegasys.teku.infrastructure.async.SafeFuture class PostgresBatchesRepository( - private val batchesDao: BatchesDao + private val batchesDao: BatchesDao, ) : BatchesRepository { override fun saveNewBatch(batch: Batch): SafeFuture { return batchesDao.saveNewBatch(batch) } override fun findHighestConsecutiveEndBlockNumberFromBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture { return batchesDao.findHighestConsecutiveEndBlockNumberFromBlockNumber(startingBlockNumberInclusive) } override fun deleteBatchesUpToEndBlockNumber( - endBlockNumberInclusive: Long + endBlockNumberInclusive: Long, ): SafeFuture { return batchesDao.deleteBatchesUpToEndBlockNumber(endBlockNumberInclusive) } override fun deleteBatchesAfterBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture { return batchesDao.deleteBatchesAfterBlockNumber(startingBlockNumberInclusive) } diff --git a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDao.kt b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDao.kt index 75cf2180..408d204b 100644 --- a/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDao.kt +++ b/coordinator/persistence/batch/src/main/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDao.kt @@ -6,17 +6,17 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RetryingBatchesPostgresDao( private val delegate: BatchesPostgresDao, - private val persistenceRetryer: PersistenceRetryer + private val persistenceRetryer: PersistenceRetryer, ) : BatchesDao { override fun saveNewBatch(batch: Batch): SafeFuture { return persistenceRetryer.retryQuery({ delegate.saveNewBatch(batch) }) } override fun findHighestConsecutiveEndBlockNumberFromBlockNumber( - startingBlockNumberInclusive: Long + startingBlockNumberInclusive: Long, ): SafeFuture { return persistenceRetryer.retryQuery( - { delegate.findHighestConsecutiveEndBlockNumberFromBlockNumber(startingBlockNumberInclusive) } + { delegate.findHighestConsecutiveEndBlockNumberFromBlockNumber(startingBlockNumberInclusive) }, ) } diff --git a/coordinator/persistence/batch/src/test/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDaoTest.kt b/coordinator/persistence/batch/src/test/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDaoTest.kt index 81f57064..ac30873d 100644 --- a/coordinator/persistence/batch/src/test/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDaoTest.kt +++ b/coordinator/persistence/batch/src/test/kotlin/net/consensys/zkevm/persistence/dao/batch/persistence/RetryingBatchesPostgresDaoTest.kt @@ -21,7 +21,7 @@ class RetryingBatchesPostgresDaoTest { private val delegateBatchesDao = mock() private val batch = createBatch( startBlockNumber = 0L, - endBlockNumber = 10L + endBlockNumber = 10L, ) @BeforeEach @@ -31,9 +31,9 @@ class RetryingBatchesPostgresDaoTest { PersistenceRetryer( vertx = vertx, PersistenceRetryer.Config( - backoffDelay = 1.milliseconds - ) - ) + backoffDelay = 1.milliseconds, + ), + ), ) whenever(delegateBatchesDao.saveNewBatch(eq(batch))) @@ -52,7 +52,7 @@ class RetryingBatchesPostgresDaoTest { @Test fun `retrying batches dao should delegate all queries to standard dao`() { retryingBatchesPostgresDao.saveNewBatch( - batch + batch, ) verify(delegateBatchesDao, times(1)).saveNewBatch(batch) diff --git a/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinatorIntTest.kt b/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinatorIntTest.kt index 63d25c77..9b797b3e 100644 --- a/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinatorIntTest.kt +++ b/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/ethereum/coordination/blob/BlobCompressionProofCoordinatorIntTest.kt @@ -53,7 +53,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { } override val databaseName = DbHelper.generateUniqueDbName( - "blob-compression-proof-coordinator" + "blob-compression-proof-coordinator", ) private val maxBlobsToReturn = 30u private var timeToReturn: Instant = Clock.System.now() @@ -71,7 +71,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { private val blobHandlerPollingInterval = 50.milliseconds private val expectedStartBlockTime = Instant.fromEpochMilliseconds(fixedClock.now().toEpochMilliseconds()) private val expectedEndBlockTime = Instant.fromEpochMilliseconds( - fixedClock.now().plus(1200.seconds).toEpochMilliseconds() + fixedClock.now().plus(1200.seconds).toEpochMilliseconds(), ) private var expectedBlobCompressionProofResponse: BlobCompressionProof? = null @@ -91,10 +91,10 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { blobsPostgresDao = BlobsPostgresDao( config = BlobsPostgresDao.Config( - maxBlobsToReturn + maxBlobsToReturn, ), connection = sqlClient, - clock = fixedClock + clock = fixedClock, ) whenever(zkStateClientMock.rollupGetStateMerkleProof(any())) .thenAnswer { @@ -104,9 +104,9 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { zkStateManagerVersion = zkStateManagerVersion, zkStateMerkleProof = zkStateMerkleProof, zkParentStateRootHash = ByteArrayExt.random32(), - zkEndStateRootHash = ByteArrayExt.random32() - ) - ) + zkEndStateRootHash = ByteArrayExt.random32(), + ), + ), ) } whenever(blobZkStateProvider.getBlobZKState(any())) @@ -114,9 +114,9 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { SafeFuture.completedFuture( BlobZkState( parentStateRootHash = Bytes32.random().toArray(), - finalStateRootHash = Bytes32.random().toArray() - ) - ) + finalStateRootHash = Bytes32.random().toArray(), + ), + ), ) whenever(blobCompressionProverClientMock.requestProof(any())) .thenAnswer { invocationMock -> @@ -125,7 +125,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { compressedData = proofReq.compressedData, conflationOrder = BlockIntervals( startingBlockNumber = proofReq.startBlockNumber, - upperBoundaries = proofReq.conflations.map { it.endBlockNumber } + upperBoundaries = proofReq.conflations.map { it.endBlockNumber }, ), prevShnarf = proofReq.prevShnarf, parentStateRootHash = proofReq.parentStateRootHash, @@ -141,7 +141,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { verifierID = 6789, commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSidecar = Random.nextBytes(48) + kzgProofSidecar = Random.nextBytes(48), ) SafeFuture.completedFuture(expectedBlobCompressionProofResponse) } @@ -149,14 +149,14 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { mockShnarfCalculator = spy(FakeBlobShnarfCalculator()) blobsRepositorySpy = spy( BlobsRepositoryImpl( - blobsPostgresDao - ) + blobsPostgresDao, + ), ) val rollingBlobShnarfCalculator = RollingBlobShnarfCalculator( blobShnarfCalculator = mockShnarfCalculator, blobsRepository = blobsRepositorySpy, - genesisShnarf = ByteArray(32) + genesisShnarf = ByteArray(32), ) blobCompressionProofCoordinator = BlobCompressionProofCoordinator( @@ -166,10 +166,10 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { rollingBlobShnarfCalculator = rollingBlobShnarfCalculator, blobZkStateProvider = blobZkStateProvider, config = BlobCompressionProofCoordinator.Config( - pollingInterval = blobHandlerPollingInterval + pollingInterval = blobHandlerPollingInterval, ), blobCompressionProofHandler = { _ -> SafeFuture.completedFuture(Unit) }, - metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) + metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), ) blobCompressionProofCoordinator.start() } @@ -178,7 +178,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { numberOfBlobs: Int, conflationStep: ULong = 10UL, startBlockNumber: ULong, - startBlockTime: Instant + startBlockTime: Instant, ): List { var currentBlockNumber = startBlockNumber var currentBlockTime = startBlockTime @@ -191,12 +191,12 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { startBlockNumber = currentBlockNumber, endBlockNumber = endBlockNumber, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = currentBlockTime, - endBlockTime = endBlockTime + endBlockTime = endBlockTime, ) currentBlockNumber = endBlockNumber + 1UL currentBlockTime = endBlockTime.plus(12.seconds) @@ -206,12 +206,12 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { @Test fun `handle blob event and update blob record with blob compression proof`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val prevBlobRecord = createBlobRecord( startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) timeToReturn = Clock.System.now() blobsPostgresDao.saveNewBlob(prevBlobRecord).get() @@ -224,24 +224,24 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { startBlockNumber = blobEventStartBlock, endBlockNumber = blobEventEndBlock, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ), ConflationCalculationResult( startBlockNumber = blobEventEndBlock + 1UL, endBlockNumber = blobEventEndBlock + 200UL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, ), ConflationCalculationResult( startBlockNumber = blobEventEndBlock + 201UL, endBlockNumber = blobEventEndBlock + 300UL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = prevBlobRecord.endBlockTime.plus(12.seconds), - endBlockTime = prevBlobRecord.endBlockTime.plus(3600.seconds) + endBlockTime = prevBlobRecord.endBlockTime.plus(3600.seconds), ) timeToReturn = Clock.System.now() @@ -252,7 +252,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { .untilAsserted { val actualBlobs = blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( expectedStartBlock, - blobEvent.endBlockTime.plus(1.seconds) + blobEvent.endBlockTime.plus(1.seconds), ).get() assertThat(actualBlobs).size().isEqualTo(2) @@ -274,7 +274,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { @Test fun `handle blob event and update blob record with blob compression proof when prev blob record not found`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val blobEventStartBlock = expectedEndBlock + 1UL val blobEventEndBlock = expectedEndBlock + 100UL @@ -284,12 +284,12 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { startBlockNumber = blobEventStartBlock, endBlockNumber = blobEventEndBlock, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = expectedEndBlockTime.plus(12.seconds), - endBlockTime = expectedEndBlockTime.plus(1200.seconds) + endBlockTime = expectedEndBlockTime.plus(1200.seconds), ) timeToReturn = Clock.System.now() @@ -300,7 +300,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { .untilAsserted { val actualBlobs = blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( blobEventStartBlock, - blobEvent.endBlockTime.plus(1.seconds) + blobEvent.endBlockTime.plus(1.seconds), ).get() assertThat(actualBlobs).size().isEqualTo(0) @@ -310,12 +310,12 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { @Test fun `handle blob events and update blob record with blob compression proof with correct parent blob data`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val prevBlobRecord = createBlobRecord( startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) timeToReturn = Clock.System.now() blobsPostgresDao.saveNewBlob(prevBlobRecord).get() @@ -323,14 +323,14 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { val blobs = createConsecutiveBlobs( numberOfBlobs = maxBlobsToReturn.toInt() - 1, startBlockNumber = expectedEndBlock + 1UL, - startBlockTime = prevBlobRecord.endBlockTime.plus(12.seconds) + startBlockTime = prevBlobRecord.endBlockTime.plus(12.seconds), ) timeToReturn = Clock.System.now() SafeFuture.allOf( blobs.map { blobCompressionProofCoordinator.handleBlob(it) - }.stream() + }.stream(), ).get() waitAtMost(10.seconds.toJavaDuration()) @@ -338,7 +338,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { .untilAsserted { val actualBlobs = blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( expectedStartBlock, - blobs.last().endBlockTime.plus(1.seconds) + blobs.last().endBlockTime.plus(1.seconds), ).get() assertThat(actualBlobs).size().isEqualTo(blobs.size + 1) @@ -360,12 +360,12 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { @Test fun `test blob handle failures re-queue's the blob`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val prevBlobRecord = createBlobRecord( startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) timeToReturn = Clock.System.now() blobsPostgresDao.saveNewBlob(prevBlobRecord).get() @@ -373,7 +373,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { val blobs = createConsecutiveBlobs( numberOfBlobs = maxBlobsToReturn.toInt() - 1, startBlockNumber = expectedEndBlock + 1UL, - startBlockTime = prevBlobRecord.endBlockTime.plus(12.seconds) + startBlockTime = prevBlobRecord.endBlockTime.plus(12.seconds), ) val maxMockedBlobZkStateFailures = 10 var blobZkStateFailures = 0 @@ -389,8 +389,8 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { SafeFuture.completedFuture( BlobZkState( parentStateRootHash = Bytes32.random().toArray(), - finalStateRootHash = Bytes32.random().toArray() - ) + finalStateRootHash = Bytes32.random().toArray(), + ), ) } } @@ -399,7 +399,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { SafeFuture.allOf( blobs.map { blobCompressionProofCoordinator.handleBlob(it) - }.stream() + }.stream(), ).get() waitAtMost(100.seconds.toJavaDuration()) @@ -407,7 +407,7 @@ class BlobCompressionProofCoordinatorIntTest : CleanDbTestSuiteParallel() { .untilAsserted { val actualBlobs = blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( expectedStartBlock, - blobs.last().endBlockTime.plus(1.seconds) + blobs.last().endBlockTime.plus(1.seconds), ).get() assertThat(actualBlobs).size().isEqualTo(blobs.size + 1) diff --git a/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDaoTest.kt b/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDaoTest.kt index 73b94d0a..76c1e11e 100644 --- a/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDaoTest.kt +++ b/coordinator/persistence/blob/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDaoTest.kt @@ -50,15 +50,15 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { blobsPostgresDao = BlobsPostgresDao( config = BlobsPostgresDao.Config( - maxBlobsToReturn + maxBlobsToReturn, ), connection = sqlClient, - clock = fakeClock + clock = fakeClock, ) } private fun performInsertTest( - blobRecord: BlobRecord + blobRecord: BlobRecord, ): RowSet? { blobsPostgresDao.saveNewBlob(blobRecord).get() val dbContent = blobsContentQuery().execute().get() @@ -71,7 +71,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(newlyInsertedRow.getLong("end_block_number")) .isEqualTo(blobRecord.endBlockNumber.toLong()) assertThat(newlyInsertedRow.getInteger("status")).isEqualTo( - BlobsPostgresDao.blobStatusToDbValue(BlobStatus.COMPRESSION_PROVEN) + BlobsPostgresDao.blobStatusToDbValue(BlobStatus.COMPRESSION_PROVEN), ) return dbContent @@ -82,7 +82,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) fakeClock.setTimeTo(Clock.System.now()) @@ -92,7 +92,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord2 = createBlobRecord( startBlockNumber = expectedEndBlock + 1UL, endBlockNumber = expectedEndBlock + 100UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) fakeClock.advanceBy(1.seconds) @@ -105,7 +105,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val dbContent1 = @@ -118,7 +118,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(executionException.cause).isInstanceOf(DuplicatedRecordException::class.java) assertThat(executionException.cause!!.message) .isEqualTo( - "Blob [1..100]100 is already persisted!" + "Blob [1..100]100 is already persisted!", ) } } @@ -130,7 +130,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val expectedBlob = createBlobRecord( expectedStartBlock1, expectedEndBlock1, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) blobsPostgresDao.saveNewBlob(expectedBlob).get() @@ -138,7 +138,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val actualBlobs = blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( expectedStartBlock1, - expectedEndBlockTime.plus(12.seconds) + expectedEndBlockTime.plus(12.seconds), ).get() assertThat(actualBlobs).hasSameElementsAs(listOf(expectedBlob)) } @@ -148,28 +148,28 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( expectedStartBlock, expectedEndBlock, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord2 = createBlobRecord( startBlockNumber = expectedEndBlock + 1UL, endBlockNumber = expectedEndBlock + 100UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord3 = createBlobRecord( startBlockNumber = expectedEndBlock + 101UL, endBlockNumber = expectedEndBlock + 200UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) SafeFuture.collectAll( blobsPostgresDao.saveNewBlob(blobRecord1), blobsPostgresDao.saveNewBlob(blobRecord2), - blobsPostgresDao.saveNewBlob(blobRecord3) + blobsPostgresDao.saveNewBlob(blobRecord3), ).get() blobsPostgresDao.getConsecutiveBlobsFromBlockNumber( expectedStartBlock + 1UL, - blobRecord3.endBlockTime.plus(1.seconds) + blobRecord3.endBlockTime.plus(1.seconds), ).get().also { blobs -> assertThat(blobs).isEmpty() } @@ -180,48 +180,48 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( startBlockNumber = 1UL, endBlockNumber = 40UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord2 = createBlobRecord( startBlockNumber = 41UL, endBlockNumber = 60UL, - startBlockTime = blobRecord1.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord1.endBlockTime.plus(3.seconds), ) val blobRecord3 = createBlobRecord( startBlockNumber = 61UL, endBlockNumber = 100UL, - startBlockTime = blobRecord2.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord2.endBlockTime.plus(3.seconds), ) val blobRecord4 = createBlobRecord( startBlockNumber = 101UL, endBlockNumber = 111UL, - startBlockTime = blobRecord3.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord3.endBlockTime.plus(3.seconds), ) val blobRecord5 = createBlobRecord( startBlockNumber = 112UL, endBlockNumber = 132UL, - startBlockTime = blobRecord4.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord4.endBlockTime.plus(3.seconds), ) val blobRecord6 = createBlobRecord( startBlockNumber = 134UL, endBlockNumber = 156UL, - startBlockTime = blobRecord5.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord5.endBlockTime.plus(3.seconds), ) val blobRecord7 = createBlobRecord( startBlockNumber = 157UL, endBlockNumber = 189UL, - startBlockTime = blobRecord5.endBlockTime.plus(3.seconds) + startBlockTime = blobRecord5.endBlockTime.plus(3.seconds), ) val expectedBlobs = listOf( blobRecord3, blobRecord4, - blobRecord5 + blobRecord5, ) val otherBlobs = listOf( blobRecord1, blobRecord2, blobRecord6, - blobRecord7 + blobRecord7, ) saveBlobs(expectedBlobs + otherBlobs) @@ -232,7 +232,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { blobsPostgresDao .getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive = expectedBlobs.first().startBlockNumber, - endBlockCreatedBefore = expectedBlobs.last().endBlockTime.plus(1.seconds) + endBlockCreatedBefore = expectedBlobs.last().endBlockTime.plus(1.seconds), ).get() assertThat(actualBlobs).hasSameElementsAs(expectedBlobs) } @@ -242,7 +242,7 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val expectedBlob = createBlobRecord( startBlockNumber = 1UL, endBlockNumber = 90UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) blobsPostgresDao.saveNewBlob(expectedBlob).get() @@ -269,55 +269,55 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( startBlockNumber = 1UL, endBlockNumber = 40UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord2 = createBlobRecord( startBlockNumber = 41UL, endBlockNumber = 60UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord3 = createBlobRecord( startBlockNumber = 61UL, endBlockNumber = 100UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord4 = createBlobRecord( startBlockNumber = 101UL, endBlockNumber = 111UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord5 = createBlobRecord( startBlockNumber = 112UL, endBlockNumber = 132UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord6 = createBlobRecord( startBlockNumber = 133UL, endBlockNumber = 156UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord7 = createBlobRecord( startBlockNumber = 157UL, endBlockNumber = 189UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val expectedBlobs = listOf( blobRecord4, blobRecord5, blobRecord6, - blobRecord7 + blobRecord7, ) val deletedBlobs = listOf( blobRecord1, blobRecord2, - blobRecord3 + blobRecord3, ) expectedBlobs.forEach { blobsPostgresDao.saveNewBlob(it).get() } deletedBlobs.forEach { blobsPostgresDao.saveNewBlob(it).get() } blobsPostgresDao.deleteBlobsUpToEndBlockNumber( - blobRecord3.endBlockNumber + blobRecord3.endBlockNumber, ).get() val existedBlobRecords = blobsContentQuery().execute() @@ -334,55 +334,55 @@ class BlobsPostgresDaoTest : CleanDbTestSuiteParallel() { val blobRecord1 = createBlobRecord( startBlockNumber = 1UL, endBlockNumber = 40UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord2 = createBlobRecord( startBlockNumber = 41UL, endBlockNumber = 60UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord3 = createBlobRecord( startBlockNumber = 61UL, endBlockNumber = 100UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord4 = createBlobRecord( startBlockNumber = 101UL, endBlockNumber = 111UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord5 = createBlobRecord( startBlockNumber = 112UL, endBlockNumber = 132UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord6 = createBlobRecord( startBlockNumber = 133UL, endBlockNumber = 156UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val blobRecord7 = createBlobRecord( startBlockNumber = 157UL, endBlockNumber = 189UL, - startBlockTime = expectedStartBlockTime + startBlockTime = expectedStartBlockTime, ) val deletedBlobs = listOf( blobRecord4, blobRecord5, blobRecord6, - blobRecord7 + blobRecord7, ) val expectedBlobs = listOf( blobRecord1, blobRecord2, - blobRecord3 + blobRecord3, ) expectedBlobs.forEach { blobsPostgresDao.saveNewBlob(it).get() } deletedBlobs.forEach { blobsPostgresDao.saveNewBlob(it).get() } blobsPostgresDao.deleteBlobsAfterBlockNumber( - blobRecord3.endBlockNumber + blobRecord3.endBlockNumber, ).get() val existedBlobRecords = blobsContentQuery().execute() diff --git a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsDao.kt b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsDao.kt index aeb6d3ff..b0f1ff7d 100644 --- a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsDao.kt +++ b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsDao.kt @@ -9,22 +9,22 @@ interface BlobsDao { fun getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive: ULong, - endBlockCreatedBefore: Instant + endBlockCreatedBefore: Instant, ): SafeFuture> fun findBlobByStartBlockNumber( - startBlockNumber: ULong + startBlockNumber: ULong, ): SafeFuture fun findBlobByEndBlockNumber( - endBlockNumber: ULong + endBlockNumber: ULong, ): SafeFuture fun deleteBlobsUpToEndBlockNumber( - endBlockNumberInclusive: ULong + endBlockNumberInclusive: ULong, ): SafeFuture fun deleteBlobsAfterBlockNumber( - startingBlockNumberInclusive: ULong + startingBlockNumberInclusive: ULong, ): SafeFuture } diff --git a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDao.kt b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDao.kt index 2e2fd08e..f5bc02a6 100644 --- a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDao.kt +++ b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsPostgresDao.kt @@ -25,7 +25,7 @@ class BlobsPostgresDao( config: Config, connection: SqlClient, log: Logger = LogManager.getLogger(BlobsPostgresDao::class.java), - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : BlobsDao { private val queryLog = SQLQueryLogger(log) data class Config(val maxBlobsToReturn: UInt) @@ -47,7 +47,7 @@ class BlobsPostgresDao( endBlockTime = Instant.fromEpochMilliseconds(record.getLong("end_block_timestamp")), batchesCount = record.getInteger("batches_count").toUInt(), expectedShnarf = record.getString("expected_shnarf").decodeHex(), - blobCompressionProof = blobCompressionProof + blobCompressionProof = blobCompressionProof, ) } @@ -151,7 +151,7 @@ class BlobsPostgresDao( blobRecord.endBlockTime.toEpochMilliseconds(), blobRecord.batchesCount.toInt(), blobRecord.expectedShnarf.encodeHex(), - blobRecord.blobCompressionProof.toJsonString() + blobRecord.blobCompressionProof.toJsonString(), ) queryLog.log(Level.TRACE, insertSql, params) @@ -160,7 +160,7 @@ class BlobsPostgresDao( .recover { th -> if (isDuplicateKeyException(th)) { Future.failedFuture( - DuplicatedRecordException("Blob ${blobRecord.intervalString()} is already persisted!", th) + DuplicatedRecordException("Blob ${blobRecord.intervalString()} is already persisted!", th), ) } else { Future.failedFuture(th) @@ -170,14 +170,14 @@ class BlobsPostgresDao( } private fun getConsecutiveBlobsFromBlockNumber( - startingBlockNumberInclusive: ULong + startingBlockNumberInclusive: ULong, ): SafeFuture> { return selectQuery .execute( Tuple.of( startingBlockNumberInclusive.toLong(), - blobStatusToDbValue(BlobStatus.COMPRESSION_PROVEN) - ) + blobStatusToDbValue(BlobStatus.COMPRESSION_PROVEN), + ), ) .toSafeFuture() .thenApply { rowSet -> @@ -187,7 +187,7 @@ class BlobsPostgresDao( override fun getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive: ULong, - endBlockCreatedBefore: Instant + endBlockCreatedBefore: Instant, ): SafeFuture> { return getConsecutiveBlobsFromBlockNumber(startingBlockNumberInclusive) .thenApply { blobs -> @@ -206,7 +206,7 @@ class BlobsPostgresDao( } override fun findBlobByEndBlockNumber( - endBlockNumber: ULong + endBlockNumber: ULong, ): SafeFuture { return selectBlobByEndBlockNumberQuery .execute(Tuple.of(endBlockNumber.toLong())) @@ -216,7 +216,7 @@ class BlobsPostgresDao( } override fun deleteBlobsUpToEndBlockNumber( - endBlockNumberInclusive: ULong + endBlockNumberInclusive: ULong, ): SafeFuture { return deleteUptoQuery .execute(Tuple.of(endBlockNumberInclusive.toLong())) diff --git a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsRepositoryImpl.kt b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsRepositoryImpl.kt index 8cda710e..f27f1505 100644 --- a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsRepositoryImpl.kt +++ b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/BlobsRepositoryImpl.kt @@ -7,7 +7,7 @@ import net.consensys.zkevm.persistence.db.DuplicatedRecordException import tech.pegasys.teku.infrastructure.async.SafeFuture class BlobsRepositoryImpl( - private val blobsDao: BlobsDao + private val blobsDao: BlobsDao, ) : BlobsRepository { override fun saveNewBlob(blobRecord: BlobRecord): SafeFuture { return blobsDao.saveNewBlob(blobRecord) @@ -22,11 +22,11 @@ class BlobsRepositoryImpl( override fun getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive: Long, - endBlockCreatedBefore: Instant + endBlockCreatedBefore: Instant, ): SafeFuture> { return blobsDao.getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive.toULong(), - endBlockCreatedBefore + endBlockCreatedBefore, ) } @@ -39,7 +39,7 @@ class BlobsRepositoryImpl( } override fun deleteBlobsUpToEndBlockNumber( - endBlockNumberInclusive: ULong + endBlockNumberInclusive: ULong, ): SafeFuture { return blobsDao.deleteBlobsUpToEndBlockNumber(endBlockNumberInclusive) } diff --git a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDao.kt b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDao.kt index b4768ba7..96395a6f 100644 --- a/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDao.kt +++ b/coordinator/persistence/blob/src/main/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDao.kt @@ -7,7 +7,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RetryingBlobsPostgresDao( private val delegate: BlobsPostgresDao, - private val persistenceRetryer: PersistenceRetryer + private val persistenceRetryer: PersistenceRetryer, ) : BlobsDao { override fun saveNewBlob(blobRecord: BlobRecord): SafeFuture { return persistenceRetryer.retryQuery({ delegate.saveNewBlob(blobRecord) }) @@ -15,12 +15,12 @@ class RetryingBlobsPostgresDao( override fun getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive: ULong, - endBlockCreatedBefore: Instant + endBlockCreatedBefore: Instant, ): SafeFuture> { return persistenceRetryer.retryQuery({ delegate.getConsecutiveBlobsFromBlockNumber( startingBlockNumberInclusive, - endBlockCreatedBefore + endBlockCreatedBefore, ) }) } diff --git a/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/ethereum/coordinator/blob/BlobCompressionProofCoordinatorTest.kt b/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/ethereum/coordinator/blob/BlobCompressionProofCoordinatorTest.kt index 0be7f04f..fb0f7820 100644 --- a/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/ethereum/coordinator/blob/BlobCompressionProofCoordinatorTest.kt +++ b/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/ethereum/coordinator/blob/BlobCompressionProofCoordinatorTest.kt @@ -52,7 +52,7 @@ class BlobCompressionProofCoordinatorTest { startingBlockNumber = expectedStartBlock, upperBoundaries = - listOf(expectedEndBlock) + listOf(expectedEndBlock), ), prevShnarf = Random.nextBytes(32), parentStateRootHash = Random.nextBytes(32), @@ -68,7 +68,7 @@ class BlobCompressionProofCoordinatorTest { verifierID = 6789, commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSidecar = Random.nextBytes(48) + kzgProofSidecar = Random.nextBytes(48), ) whenever(it.requestProof(any())) @@ -86,10 +86,10 @@ class BlobCompressionProofCoordinatorTest { rollingBlobShnarfCalculator = rollingBlobShnarfCalculator, blobZkStateProvider = blobZkStateProvider, config = BlobCompressionProofCoordinator.Config( - pollingInterval = blobHandlerPollingInterval + pollingInterval = blobHandlerPollingInterval, ), blobCompressionProofHandler = { _ -> SafeFuture.completedFuture(Unit) }, - metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) + metricsFacade = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS), ) blobCompressionProofCoordinator.start() } @@ -108,12 +108,12 @@ class BlobCompressionProofCoordinatorTest { startBlockNumber = expectedStartBlock, endBlockNumber = expectedEndBlock, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = startBlockTime, - endBlockTime = fixedClock.now().plus((12 * (expectedEndBlock - expectedStartBlock).toInt()).seconds) + endBlockTime = fixedClock.now().plus((12 * (expectedEndBlock - expectedStartBlock).toInt()).seconds), ) whenever(blobZkStateProvider.getBlobZKState(any())) @@ -121,9 +121,9 @@ class BlobCompressionProofCoordinatorTest { SafeFuture.completedFuture( BlobZkState( parentStateRootHash = parentStateRootHash, - finalStateRootHash = finalStateRootHash - ) - ) + finalStateRootHash = finalStateRootHash, + ), + ), ) val shnarfResult = ShnarfResult( @@ -134,7 +134,7 @@ class BlobCompressionProofCoordinatorTest { expectedShnarf = Random.nextBytes(32), commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSideCar = Random.nextBytes(48) + kzgProofSideCar = Random.nextBytes(48), ) whenever(rollingBlobShnarfCalculator.calculateShnarf(any(), any(), any(), any())) @@ -143,8 +143,8 @@ class BlobCompressionProofCoordinatorTest { RollingBlobShnarfResult( shnarfResult = shnarfResult, parentBlobHash = expectedParentDataHash, - parentBlobShnarf = expectedPrevShnarf - ) + parentBlobShnarf = expectedPrevShnarf, + ), ) } @@ -164,8 +164,8 @@ class BlobCompressionProofCoordinatorTest { expectedShnarfResult = shnarfResult, commitment = shnarfResult.commitment, kzgProofContract = shnarfResult.kzgProofContract, - kzgProofSideCar = shnarfResult.kzgProofSideCar - ) + kzgProofSideCar = shnarfResult.kzgProofSideCar, + ), ) } } @@ -184,12 +184,12 @@ class BlobCompressionProofCoordinatorTest { startBlockNumber = 1uL, endBlockNumber = 10uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = startBlockTime, - endBlockTime = fixedClock.now().plus((12 * (10 - 1)).seconds) + endBlockTime = fixedClock.now().plus((12 * (10 - 1)).seconds), ) val blob2 = Blob( @@ -198,12 +198,12 @@ class BlobCompressionProofCoordinatorTest { startBlockNumber = 11uL, endBlockNumber = 20uL, conflationTrigger = ConflationTrigger.TRACES_LIMIT, - tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT - ) + tracesCounters = TracesCountersV2.EMPTY_TRACES_COUNT, + ), ), compressedData = Random.nextBytes(128), startBlockTime = startBlockTime, - endBlockTime = fixedClock.now().plus((12 * (20 - 11)).seconds) + endBlockTime = fixedClock.now().plus((12 * (20 - 11)).seconds), ) whenever(blobZkStateProvider.getBlobZKState(any())) @@ -212,15 +212,15 @@ class BlobCompressionProofCoordinatorTest { SafeFuture.completedFuture( BlobZkState( parentStateRootHash = parentStateRootHash, - finalStateRootHash = finalStateRootHash - ) + finalStateRootHash = finalStateRootHash, + ), ), SafeFuture.completedFuture( BlobZkState( parentStateRootHash = parentStateRootHash, - finalStateRootHash = finalStateRootHash - ) - ) + finalStateRootHash = finalStateRootHash, + ), + ), ) val shnarfResult = ShnarfResult( @@ -231,7 +231,7 @@ class BlobCompressionProofCoordinatorTest { expectedShnarf = Random.nextBytes(32), commitment = Random.nextBytes(48), kzgProofContract = Random.nextBytes(48), - kzgProofSideCar = Random.nextBytes(48) + kzgProofSideCar = Random.nextBytes(48), ) whenever(rollingBlobShnarfCalculator.calculateShnarf(any(), any(), any(), any())) @@ -240,8 +240,8 @@ class BlobCompressionProofCoordinatorTest { RollingBlobShnarfResult( shnarfResult = shnarfResult, parentBlobHash = expectedParentDataHash, - parentBlobShnarf = expectedPrevShnarf - ) + parentBlobShnarf = expectedPrevShnarf, + ), ) } @@ -262,8 +262,8 @@ class BlobCompressionProofCoordinatorTest { expectedShnarfResult = shnarfResult, commitment = shnarfResult.commitment, kzgProofContract = shnarfResult.kzgProofContract, - kzgProofSideCar = shnarfResult.kzgProofSideCar - ) + kzgProofSideCar = shnarfResult.kzgProofSideCar, + ), ) verify(blobCompressionProverClient, times(1)) .requestProof( @@ -277,8 +277,8 @@ class BlobCompressionProofCoordinatorTest { expectedShnarfResult = shnarfResult, commitment = shnarfResult.commitment, kzgProofContract = shnarfResult.kzgProofContract, - kzgProofSideCar = shnarfResult.kzgProofSideCar - ) + kzgProofSideCar = shnarfResult.kzgProofSideCar, + ), ) } } diff --git a/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDaoTest.kt b/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDaoTest.kt index 401b6247..e02e8021 100644 --- a/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDaoTest.kt +++ b/coordinator/persistence/blob/src/test/kotlin/net/consensys/zkevm/persistence/dao/blob/RetryingBlobsPostgresDaoTest.kt @@ -32,7 +32,7 @@ class RetryingBlobsPostgresDaoTest { private val blobRecord = createBlobRecord( startBlockNumber = 0U, endBlockNumber = 10U, - startBlockTime = now + startBlockTime = now, ) private val blobCompressionProof = BlobCompressionProof( compressedData = Random.nextBytes(32).setFirstByteToZero(), @@ -51,7 +51,7 @@ class RetryingBlobsPostgresDaoTest { verifierID = 6789, commitment = ByteArray(0), kzgProofContract = ByteArray(0), - kzgProofSidecar = ByteArray(0) + kzgProofSidecar = ByteArray(0), ) @BeforeEach @@ -61,9 +61,9 @@ class RetryingBlobsPostgresDaoTest { PersistenceRetryer( vertx = vertx, PersistenceRetryer.Config( - backoffDelay = 1.milliseconds - ) - ) + backoffDelay = 1.milliseconds, + ), + ), ) whenever(delegateBlobsDao.saveNewBlob(eq(blobRecord))) diff --git a/coordinator/persistence/db-common/src/integrationTest/kotlin/net/consensys/zkevm/persistence/db/test/DbSchemaUpdatesIntTest.kt b/coordinator/persistence/db-common/src/integrationTest/kotlin/net/consensys/zkevm/persistence/db/test/DbSchemaUpdatesIntTest.kt index cc69a253..78811d7c 100644 --- a/coordinator/persistence/db-common/src/integrationTest/kotlin/net/consensys/zkevm/persistence/db/test/DbSchemaUpdatesIntTest.kt +++ b/coordinator/persistence/db-common/src/integrationTest/kotlin/net/consensys/zkevm/persistence/db/test/DbSchemaUpdatesIntTest.kt @@ -76,7 +76,7 @@ class DbSchemaUpdatesIntTest { DbHelper.dropAllTables(dataSource) Db.applyDbMigrations( dataSource = dataSource, - target = schemaTarget + target = schemaTarget, ) val paramsV1 = listOf( @@ -84,7 +84,7 @@ class DbSchemaUpdatesIntTest { 0L, 1L, "0.1.0", - 1 + 1, ) val paramsV2 = listOf( @@ -93,7 +93,7 @@ class DbSchemaUpdatesIntTest { 1L, "0.1.0", "0.1.0", - 1 + 1, ) DbQueries.insertBatch(sqlClient, DbQueries.insertBatchQueryV1, paramsV1).get() @@ -112,7 +112,7 @@ class DbSchemaUpdatesIntTest { DbHelper.dropAllTables(dataSource) Db.applyDbMigrations( dataSource = dataSource, - target = schemaTarget + target = schemaTarget, ) val batchParamsV2 = listOf( @@ -121,7 +121,7 @@ class DbSchemaUpdatesIntTest { 1L, "0.1.0", "0.1.0", - 1 + 1, ) DbQueries.insertBatch(sqlClient, DbQueries.insertBatchQueryV2, batchParamsV2).get() @@ -140,7 +140,7 @@ class DbSchemaUpdatesIntTest { Clock.System.now().toEpochMilliseconds(), 3, ByteArray(32).encodeHex(), - "{}" + "{}", ) DbQueries.insertBlob(sqlClient, DbQueries.insertBlobQuery, blobParams).get() diff --git a/coordinator/persistence/db-common/src/testFixtures/kotlin/net/consensys/zkevm/persistence/db/test/DbQueries.kt b/coordinator/persistence/db-common/src/testFixtures/kotlin/net/consensys/zkevm/persistence/db/test/DbQueries.kt index 9c3e32c7..28463c9d 100644 --- a/coordinator/persistence/db-common/src/testFixtures/kotlin/net/consensys/zkevm/persistence/db/test/DbQueries.kt +++ b/coordinator/persistence/db-common/src/testFixtures/kotlin/net/consensys/zkevm/persistence/db/test/DbQueries.kt @@ -24,7 +24,7 @@ object DbQueries { 2 -> Batch.Status.Proven else -> throw IllegalStateException( - "Value '$value' does not map to any ${Batch.Status::class.simpleName}" + "Value '$value' does not map to any ${Batch.Status::class.simpleName}", ) } } @@ -34,7 +34,7 @@ object DbQueries { record -> Batch( startBlockNumber = record.getLong("start_block_number").toULong(), - endBlockNumber = record.getLong("end_block_number").toULong() + endBlockNumber = record.getLong("end_block_number").toULong(), ) } } diff --git a/coordinator/persistence/feehistory/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDaoTest.kt b/coordinator/persistence/feehistory/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDaoTest.kt index e01275f1..d8db4979 100644 --- a/coordinator/persistence/feehistory/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDaoTest.kt +++ b/coordinator/persistence/feehistory/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDaoTest.kt @@ -29,7 +29,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { initialBaseFeePerBlobGas: ULong, initialBlobGasUsedRatio: UInt, feeHistoryBlockCount: UInt, - rewardPercentilesCount: Int + rewardPercentilesCount: Int, ): FeeHistory { return FeeHistory( oldestBlock = oldestBlockNumber, @@ -41,7 +41,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { baseFeePerBlobGas = (initialBaseFeePerBlobGas until initialBaseFeePerBlobGas + feeHistoryBlockCount + 1u) .toList(), blobGasUsedRatio = (initialBlobGasUsedRatio until initialBlobGasUsedRatio + feeHistoryBlockCount) - .map { (it.toDouble() / 100.0) } + .map { (it.toDouble() / 100.0) }, ) } @@ -62,7 +62,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { initialBaseFeePerBlobGas = 1000UL, initialBlobGasUsedRatio = 60U, feeHistoryBlockCount = 5U, - rewardPercentilesCount = rewardPercentiles.size + rewardPercentilesCount = rewardPercentiles.size, ) // fee history of block 100, 101, 102, 103, 104 @BeforeEach @@ -71,13 +71,13 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { feeHistoriesPostgresDao = FeeHistoriesPostgresDao( sqlClient, - fakeClock + fakeClock, ) } private fun performInsertTest( feeHistory: FeeHistory, - rewardPercentiles: List + rewardPercentiles: List, ): RowSet? { feeHistoriesPostgresDao.saveNewFeeHistory(feeHistory, rewardPercentiles).get() val dbContent = feeHistoriesContentQuery().execute().get() @@ -109,7 +109,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) } @@ -119,7 +119,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { var dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) @@ -132,13 +132,13 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { initialBaseFeePerBlobGas = 2000UL, initialBlobGasUsedRatio = 10U, feeHistoryBlockCount = 5U, - rewardPercentilesCount = rewardPercentiles.size + rewardPercentilesCount = rewardPercentiles.size, ) fakeClock.setTimeTo(Clock.System.now()) performInsertTest( overlappedFeeHistory, - rewardPercentiles + rewardPercentiles, ) dbContent = feeHistoriesContentQuery().execute().get() @@ -150,31 +150,31 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val p10BaseFeePerGas = feeHistoriesPostgresDao.findBaseFeePerGasAtPercentile( percentile = 10.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p10BaseFeePerGas).isEqualTo(10000uL) val p50BaseFeePerGas = feeHistoriesPostgresDao.findBaseFeePerGasAtPercentile( percentile = 50.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p50BaseFeePerGas).isEqualTo(10002uL) val p75BaseFeePerGas = feeHistoriesPostgresDao.findBaseFeePerGasAtPercentile( percentile = 75.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p75BaseFeePerGas).isEqualTo(10003uL) val p100BaseFeePerGas = feeHistoriesPostgresDao.findBaseFeePerGasAtPercentile( percentile = 100.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p100BaseFeePerGas).isEqualTo(10004uL) } @@ -184,31 +184,31 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val p10BaseFeePerBlobGas = feeHistoriesPostgresDao.findBaseFeePerBlobGasAtPercentile( percentile = 10.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p10BaseFeePerBlobGas).isEqualTo(1000uL) val p50BaseFeePerBlobGas = feeHistoriesPostgresDao.findBaseFeePerBlobGasAtPercentile( percentile = 50.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p50BaseFeePerBlobGas).isEqualTo(1002uL) val p75BaseFeePerBlobGas = feeHistoriesPostgresDao.findBaseFeePerBlobGasAtPercentile( percentile = 75.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p75BaseFeePerBlobGas).isEqualTo(1003uL) val p100BaseFeePerBlobGas = feeHistoriesPostgresDao.findBaseFeePerBlobGasAtPercentile( percentile = 100.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p100BaseFeePerBlobGas).isEqualTo(1004uL) } @@ -218,31 +218,31 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val avgP10Reward = feeHistoriesPostgresDao.findAverageRewardAtPercentile( rewardPercentile = 10.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(avgP10Reward).isEqualTo(1002uL) val avgP20Reward = feeHistoriesPostgresDao.findAverageRewardAtPercentile( rewardPercentile = 20.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(avgP20Reward).isEqualTo(2004uL) val avgP70Reward = feeHistoriesPostgresDao.findAverageRewardAtPercentile( rewardPercentile = 70.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(avgP70Reward).isEqualTo(7014uL) val avgP100Reward = feeHistoriesPostgresDao.findAverageRewardAtPercentile( rewardPercentile = 100.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(avgP100Reward).isEqualTo(10020uL) } @@ -252,13 +252,13 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val avgP15Reward = feeHistoriesPostgresDao.findAverageRewardAtPercentile( rewardPercentile = 15.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(avgP15Reward).isNull() } @@ -268,7 +268,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { var dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) @@ -281,34 +281,34 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { initialBaseFeePerBlobGas = 1000UL, initialBlobGasUsedRatio = 60U, feeHistoryBlockCount = 5U, - rewardPercentilesCount = rewardPercentile90.size + rewardPercentilesCount = rewardPercentile90.size, ) fakeClock.setTimeTo(Clock.System.now()) dbContent = performInsertTest( feeHistory, - rewardPercentile90 + rewardPercentile90, ) assertThat(dbContent).size().isEqualTo(10) val p10HighestBlockNumber = feeHistoriesPostgresDao.findHighestBlockNumberWithPercentile( - rewardPercentile = 10.0 + rewardPercentile = 10.0, ).get() assertThat(p10HighestBlockNumber).isEqualTo(104L) val p20HighestBlockNumber = feeHistoriesPostgresDao.findHighestBlockNumberWithPercentile( - rewardPercentile = 20.0 + rewardPercentile = 20.0, ).get() assertThat(p20HighestBlockNumber).isEqualTo(104L) val p100HighestBlockNumber = feeHistoriesPostgresDao.findHighestBlockNumberWithPercentile( - rewardPercentile = 100.0 + rewardPercentile = 100.0, ).get() assertThat(p100HighestBlockNumber).isEqualTo(104L) val p90HighestBlockNumber = feeHistoriesPostgresDao.findHighestBlockNumberWithPercentile( - rewardPercentile = 90.0 + rewardPercentile = 90.0, ).get() assertThat(p90HighestBlockNumber).isEqualTo(109L) } @@ -318,12 +318,12 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val p25HighestBlockNumber = feeHistoriesPostgresDao.findHighestBlockNumberWithPercentile( - rewardPercentile = 25.0 + rewardPercentile = 25.0, ).get() assertThat(p25HighestBlockNumber).isNull() } @@ -333,33 +333,33 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { val dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) val p10NumOfRecords = feeHistoriesPostgresDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile = 10.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p10NumOfRecords).isEqualTo(5) val p50NumOfRecords = feeHistoriesPostgresDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile = 50.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p50NumOfRecords).isEqualTo(5) // unfound reward percentile val p75NumOfRecords = feeHistoriesPostgresDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile = 75.0, - fromBlockNumber = 100L + fromBlockNumber = 100L, ).get() assertThat(p75NumOfRecords).isEqualTo(0) // out of block range val p20NumOfRecordsOutOfRange = feeHistoriesPostgresDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile = 20.0, - fromBlockNumber = 110L + fromBlockNumber = 110L, ).get() assertThat(p20NumOfRecordsOutOfRange).isEqualTo(0) } @@ -369,12 +369,12 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { var dbContent = performInsertTest( feeHistory, - rewardPercentiles + rewardPercentiles, ) assertThat(dbContent).size().isEqualTo(5) var deletedNum = feeHistoriesPostgresDao.deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive = 102L + blockNumberInclusive = 102L, ).get() assertThat(deletedNum).isEqualTo(3) @@ -382,7 +382,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(dbContent).size().isEqualTo(2) deletedNum = feeHistoriesPostgresDao.deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive = 102L + blockNumberInclusive = 102L, ).get() assertThat(deletedNum).isEqualTo(0) @@ -390,7 +390,7 @@ class FeeHistoriesPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(dbContent).size().isEqualTo(2) deletedNum = feeHistoriesPostgresDao.deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive = 110L + blockNumberInclusive = 110L, ).get() assertThat(deletedNum).isEqualTo(2) diff --git a/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDao.kt b/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDao.kt index 8242e732..aa4f9892 100644 --- a/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDao.kt +++ b/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesPostgresDao.kt @@ -14,39 +14,39 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface FeeHistoriesDao { fun saveNewFeeHistory( feeHistory: FeeHistory, - rewardPercentiles: List + rewardPercentiles: List, ): SafeFuture fun findBaseFeePerGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findBaseFeePerBlobGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findAverageRewardAtPercentile( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun findHighestBlockNumberWithPercentile(rewardPercentile: Double): SafeFuture fun getNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture fun deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive: Long + blockNumberInclusive: Long, ): SafeFuture } class FeeHistoriesPostgresDao( connection: SqlClient, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : FeeHistoriesDao { private val log = LogManager.getLogger(this.javaClass.name) private val queryLog = SQLQueryLogger(log) @@ -121,7 +121,7 @@ class FeeHistoriesPostgresDao( private val selectHighestBlockNumberQuery = connection.preparedQuery(selectHighestBlockNumberSql) private val getNthPercentileOfBaseFeePerGasQuery = connection.preparedQuery(getNthPercentileOfBaseFeePerGasSql) private val getNthPercentileOfBaseFeePerBlobGasQuery = connection.preparedQuery( - getNthPercentileOfBaseFeePerBlobGasSql + getNthPercentileOfBaseFeePerBlobGasSql, ) private val getAvgNthPercentileRewardQuery = connection.preparedQuery(getAvgNthPercentileRewardSql) private val countFeeHistoriesFromBlockNumberQuery = connection.preparedQuery(countFeeHistoriesFromBlockNumberSql) @@ -137,7 +137,7 @@ class FeeHistoriesPostgresDao( feeHistory.gasUsedRatio[i].toFloat(), feeHistory.blobGasUsedRatio.getOrElse(i) { 0.0 }.toFloat(), reward.map { it.toLong() }.toTypedArray(), - rewardPercentiles.map { it.toFloat() }.toTypedArray() + rewardPercentiles.map { it.toFloat() }.toTypedArray(), ) queryLog.log(Level.TRACE, upsertSql, params) Tuple.tuple(params) @@ -152,11 +152,11 @@ class FeeHistoriesPostgresDao( override fun findBaseFeePerGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { val params = listOf( percentile.div(100).toFloat(), - fromBlockNumber + fromBlockNumber, ) queryLog.log(Level.TRACE, getNthPercentileOfBaseFeePerGasSql, params) return getNthPercentileOfBaseFeePerGasQuery @@ -169,11 +169,11 @@ class FeeHistoriesPostgresDao( override fun findBaseFeePerBlobGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { val params = listOf( percentile.div(100).toFloat(), - fromBlockNumber + fromBlockNumber, ) queryLog.log(Level.TRACE, getNthPercentileOfBaseFeePerBlobGasSql, params) return getNthPercentileOfBaseFeePerBlobGasQuery @@ -186,11 +186,11 @@ class FeeHistoriesPostgresDao( override fun findAverageRewardAtPercentile( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { val params = listOf( rewardPercentile.toFloat(), - fromBlockNumber + fromBlockNumber, ) queryLog.log(Level.TRACE, getAvgNthPercentileRewardSql, params) return getAvgNthPercentileRewardQuery @@ -214,11 +214,11 @@ class FeeHistoriesPostgresDao( override fun getNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { val params = listOf( rewardPercentile.toFloat(), - fromBlockNumber + fromBlockNumber, ) queryLog.log(Level.TRACE, countFeeHistoriesFromBlockNumberSql, params) return countFeeHistoriesFromBlockNumberQuery @@ -230,7 +230,7 @@ class FeeHistoriesPostgresDao( } override fun deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive: Long + blockNumberInclusive: Long, ): SafeFuture { return deleteQuery .execute(Tuple.of(blockNumberInclusive)) diff --git a/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesRepositoryImpl.kt b/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesRepositoryImpl.kt index a5e558fe..97fdd9dd 100644 --- a/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesRepositoryImpl.kt +++ b/coordinator/persistence/feehistory/src/main/kotlin/net/consensys/zkevm/persistence/dao/feehistory/FeeHistoriesRepositoryImpl.kt @@ -10,12 +10,12 @@ import java.util.concurrent.atomic.AtomicReference class FeeHistoriesRepositoryImpl( private val config: Config, - private val feeHistoriesDao: FeeHistoriesDao + private val feeHistoriesDao: FeeHistoriesDao, ) : FeeHistoriesRepositoryWithCache { data class Config( val rewardPercentiles: List, val minBaseFeePerBlobGasToCache: ULong? = null, - val fixedAverageRewardToCache: ULong? = null + val fixedAverageRewardToCache: ULong? = null, ) { init { require(rewardPercentiles.isNotEmpty()) { @@ -37,14 +37,14 @@ class FeeHistoriesRepositoryImpl( PercentileGasFees( percentileBaseFeePerGas = 0uL, percentileBaseFeePerBlobGas = 0uL, - percentileAvgReward = 0uL - ) + percentileAvgReward = 0uL, + ), ) override fun saveNewFeeHistory(feeHistory: FeeHistory): SafeFuture { return feeHistoriesDao.saveNewFeeHistory( feeHistory, - config.rewardPercentiles + config.rewardPercentiles, ) .exceptionallyCompose { error -> if (error is DuplicatedRecordException) { @@ -57,31 +57,31 @@ class FeeHistoriesRepositoryImpl( override fun findBaseFeePerGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return feeHistoriesDao.findBaseFeePerGasAtPercentile( percentile, - fromBlockNumber + fromBlockNumber, ) } override fun findBaseFeePerBlobGasAtPercentile( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return feeHistoriesDao.findBaseFeePerBlobGasAtPercentile( percentile, - fromBlockNumber + fromBlockNumber, ) } override fun findAverageRewardAtPercentile( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return feeHistoriesDao.findAverageRewardAtPercentile( rewardPercentile, - fromBlockNumber + fromBlockNumber, ) } @@ -91,11 +91,11 @@ class FeeHistoriesRepositoryImpl( override fun getNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return feeHistoriesDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile, - fromBlockNumber + fromBlockNumber, ) } @@ -105,11 +105,11 @@ class FeeHistoriesRepositoryImpl( override fun cacheNumOfFeeHistoriesFromBlockNumber( rewardPercentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return feeHistoriesDao.getNumOfFeeHistoriesFromBlockNumber( rewardPercentile, - fromBlockNumber + fromBlockNumber, ).thenPeek { lastNumOfFeeHistoriesFromBlockNumber.set(it) } @@ -121,15 +121,15 @@ class FeeHistoriesRepositoryImpl( override fun cachePercentileGasFees( percentile: Double, - fromBlockNumber: Long + fromBlockNumber: Long, ): SafeFuture { return findBaseFeePerGasAtPercentile( percentile, - fromBlockNumber + fromBlockNumber, ).thenCompose { percentileBaseFeePerGas -> findBaseFeePerBlobGasAtPercentile( percentile, - fromBlockNumber + fromBlockNumber, ).thenCompose { percentileBaseFeePerBlobGas -> ( if (config.fixedAverageRewardToCache != null) { @@ -143,8 +143,8 @@ class FeeHistoriesRepositoryImpl( percentileBaseFeePerGas!!, percentileBaseFeePerBlobGas!! .coerceAtLeast(config.minBaseFeePerBlobGasToCache ?: percentileBaseFeePerBlobGas), - percentileAvgReward!! - ) + percentileAvgReward!!, + ), ) } } @@ -152,7 +152,7 @@ class FeeHistoriesRepositoryImpl( } override fun deleteFeeHistoriesUpToBlockNumber( - blockNumberInclusive: Long + blockNumberInclusive: Long, ): SafeFuture { return feeHistoriesDao.deleteFeeHistoriesUpToBlockNumber(blockNumberInclusive) } diff --git a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/DirectoryCleaner.kt b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/DirectoryCleaner.kt index e50d1655..ca672a40 100644 --- a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/DirectoryCleaner.kt +++ b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/DirectoryCleaner.kt @@ -12,7 +12,7 @@ import kotlin.io.path.isDirectory class DirectoryCleaner( val vertx: Vertx, val directories: List, - val fileFilters: List + val fileFilters: List, ) { private val log = LogManager.getLogger(this::class.java) diff --git a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileMonitor.kt b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileMonitor.kt index 593ece4b..2432ebf3 100644 --- a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileMonitor.kt +++ b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileMonitor.kt @@ -13,22 +13,22 @@ import kotlin.time.Duration class FileMonitor( private val vertx: Vertx, - config: Config + config: Config, ) { private val asyncRetryer = AsyncRetryer.retryer>( vertx = vertx, backoffDelay = config.pollingInterval, - timeout = config.timeout + timeout = config.timeout, ) data class Config( val pollingInterval: Duration, - val timeout: Duration + val timeout: Duration, ) enum class ErrorType { - TIMED_OUT + TIMED_OUT, } /** @@ -70,7 +70,7 @@ class FileMonitor( .fileSystem() .readDir( directory.toString(), - pattern + pattern, ) .map { files -> files.firstOrNull() } .toSafeFuture() diff --git a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileReader.kt b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileReader.kt index 4e6c9b44..47f99dd8 100644 --- a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileReader.kt +++ b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileReader.kt @@ -16,11 +16,11 @@ import java.util.concurrent.Callable class FileReader ( private val vertx: Vertx, private val mapper: ObjectMapper, - private val classOfT: Class + private val classOfT: Class, ) { enum class ErrorType { - PARSING_ERROR + PARSING_ERROR, } fun read(filePath: Path): SafeFuture>> { @@ -39,7 +39,7 @@ class FileReader ( } } }, - false + false, ) .toSafeFuture() } diff --git a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileWriter.kt b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileWriter.kt index 04c6035f..dbb3a1ea 100644 --- a/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileWriter.kt +++ b/coordinator/utilities/src/main/kotlin/net/consensys/zkevm/fileio/FileWriter.kt @@ -15,7 +15,7 @@ fun inProgressFilePattern(fileName: String, inProgressSuffix: String): String { class FileWriter( private val vertx: Vertx, - private val mapper: ObjectMapper + private val mapper: ObjectMapper, ) { fun write(data: Any, filePath: Path, inProgressSuffix: String?): SafeFuture { return vertx @@ -30,7 +30,7 @@ class FileWriter( tmpFile.renameTo(filePath.toFile()) filePath }, - false + false, ).toSafeFuture() } @@ -39,7 +39,7 @@ class FileWriter( Callable { filePath.exists() || inProgressFilePath(filePath, inProgressSuffix).exists() }, - false + false, ).toSafeFuture() } private fun inProgressFilePath(filePath: Path, inProgressSuffix: String): Path { diff --git a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/DirectoryCleanerTest.kt b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/DirectoryCleanerTest.kt index 65ac9e22..2601f308 100644 --- a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/DirectoryCleanerTest.kt +++ b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/DirectoryCleanerTest.kt @@ -23,7 +23,7 @@ class DirectoryCleanerTest { @Test fun test_tmp_directory_cleanup(vertx: Vertx) { val tmpDirectory = Files.createTempDirectory( - DirectoryCleanerTest::class.simpleName + "-test_tmp_directory_cleanup" + DirectoryCleanerTest::class.simpleName + "-test_tmp_directory_cleanup", ) for (i in 1..9) { val fileExtension = (i % 3).run { @@ -36,7 +36,7 @@ class DirectoryCleanerTest { Files.createTempFile( tmpDirectory, "directory_cleaner_test-request-$i", - fileExtension + fileExtension, ) } assertThat(vertx.fileSystem().readDir(tmpDirectory.absolutePathString()).get().size).isEqualTo(9) @@ -44,7 +44,7 @@ class DirectoryCleanerTest { vertx, listOf(tmpDirectory), DirectoryCleaner.getSuffixFileFilters(listOf(".inprogress_coordinator_writing")) + - DirectoryCleaner.JSON_FILE_FILTER + DirectoryCleaner.JSON_FILE_FILTER, ) directoryCleaner.cleanup().get() var remainingFiles = 0 @@ -61,24 +61,24 @@ class DirectoryCleanerTest { @Test fun test_deletion_of_absent_file_does_not_throw_exception(vertx: Vertx) { val tmpDirectory = Files.createTempDirectory( - DirectoryCleanerTest::class.simpleName + "-test_deletion_of_absent_file_throws_exception" + DirectoryCleanerTest::class.simpleName + "-test_deletion_of_absent_file_throws_exception", ) val fileToBeMovedDuringCleanup = Files.createTempFile( tmpDirectory, "absent_file", - ".json" + ".json", ) Files.createTempFile( tmpDirectory, "directory_cleaner_test-request-1", - ".json" + ".json", ) val inProgressFile = Files.createTempFile( tmpDirectory, "directory_cleaner_test-request-2", - ".json.inprogress" + ".json.inprogress", ) val mockFileFilter = mock {} @@ -105,7 +105,7 @@ class DirectoryCleanerTest { assertThat(DirectoryCleaner.JSON_FILE_FILTER.accept(File("11-27-getZkAggregatedProof.Json"))).isTrue() assertThat(DirectoryCleaner.JSON_FILE_FILTER.accept(File("11-27-getZkAggregatedProof.JSON"))).isTrue() assertThat( - DirectoryCleaner.JSON_FILE_FILTER.accept(File("11-27-getZkAggregatedProof.json.inprogress")) + DirectoryCleaner.JSON_FILE_FILTER.accept(File("11-27-getZkAggregatedProof.json.inprogress")), ).isFalse() } @@ -113,13 +113,13 @@ class DirectoryCleanerTest { fun test_extension_file_filter() { val extensionFileFilter = DirectoryCleaner.getSuffixFileFilters(listOf(".inprogress_coordinator_writing")).first() assertThat( - extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inprogress_coordinator_writing")) + extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inprogress_coordinator_writing")), ).isTrue() assertThat( - extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inProgress_cooRdinator_Writing")) + extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inProgress_cooRdinator_Writing")), ).isFalse() assertThat( - extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inprogress")) + extensionFileFilter.accept(File("11-27-getZkAggregatedProof.json.inprogress")), ).isFalse() } } diff --git a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileMonitorTest.kt b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileMonitorTest.kt index 500e5258..d6cd608e 100644 --- a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileMonitorTest.kt +++ b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileMonitorTest.kt @@ -36,7 +36,7 @@ class FileMonitorTest { fun test_fileExists_exists(vertx: Vertx) { val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) @@ -49,7 +49,7 @@ class FileMonitorTest { fun test_fileExists_doesNotExist(vertx: Vertx) { val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) val testFilePath = tmpDirectory.resolve("test_fileExists_doesNotExist") @@ -60,7 +60,7 @@ class FileMonitorTest { fun test_fileExists_patternExists(vertx: Vertx) { val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) val testFile = tmpDirectory.resolve("file-monitor-test-1").toFile() @@ -72,7 +72,7 @@ class FileMonitorTest { fun test_fileExists_patternDoesNotExists(vertx: Vertx) { val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) Assertions.assertFalse(fileMonitor.fileExists(tmpDirectory, "file-monitor-test-.*").get()) @@ -84,14 +84,14 @@ class FileMonitorTest { testFile.createNewFile() val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) val result = fileMonitor.monitor(testFile.toPath()).get() Assertions.assertTrue(result is Ok) Assertions.assertEquals( testFile.toPath(), - result.component1() + result.component1(), ) } @@ -99,7 +99,7 @@ class FileMonitorTest { fun test_monitor_timeOut(vertx: Vertx) { val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) val testFilePath = tmpDirectory.resolve("test_monitor_timeOut") @@ -107,7 +107,7 @@ class FileMonitorTest { Assertions.assertTrue(result is Err) Assertions.assertEquals( FileMonitor.ErrorType.TIMED_OUT, - result.component2() + result.component2(), ) } @@ -116,7 +116,7 @@ class FileMonitorTest { val tempFilePath = tmpDirectory.resolve("test_monitor_fileCreatedInTime") val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) Assertions.assertFalse(fileMonitor.fileExists(tempFilePath).get()) @@ -127,7 +127,7 @@ class FileMonitorTest { Assertions.assertTrue(result is Ok) Assertions.assertEquals( tempFilePath, - result.component1() + result.component1(), ) } @@ -137,7 +137,7 @@ class FileMonitorTest { val tempFilePath2 = tmpDirectory.resolve("test_monitor_fileCreatedInTime2") val config = FileMonitor.Config( pollingInterval = 50.toDuration(DurationUnit.MILLISECONDS), - timeout = 1.toDuration(DurationUnit.SECONDS) + timeout = 1.toDuration(DurationUnit.SECONDS), ) val fileMonitor = FileMonitor(vertx, config) Assertions.assertFalse(fileMonitor.fileExists(tempFilePath1).get()) @@ -150,7 +150,7 @@ class FileMonitorTest { Assertions.assertTrue(result is Ok) Assertions.assertEquals( tempFilePath2, - result.component1() + result.component1(), ) } } diff --git a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileReaderTest.kt b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileReaderTest.kt index cd08052f..2d405155 100644 --- a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileReaderTest.kt +++ b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileReaderTest.kt @@ -28,7 +28,7 @@ class FileReaderTest { mapper.writeValue(tempFile, data) Assertions.assertEquals( data, - fileReader.read(tempFile.toPath()).get().component1() + fileReader.read(tempFile.toPath()).get().component1(), ) } @@ -40,7 +40,7 @@ class FileReaderTest { mapper.writeValue(tempFile, data) Assertions.assertEquals( FileReader.ErrorType.PARSING_ERROR, - fileReader.read(tempFile.toPath()).get().component2()?.type + fileReader.read(tempFile.toPath()).get().component2()?.type, ) } } diff --git a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileWriterTest.kt b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileWriterTest.kt index 742e2702..d9d78c93 100644 --- a/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileWriterTest.kt +++ b/coordinator/utilities/src/test/kotlin/net/consensys/zkevm/fileio/FileWriterTest.kt @@ -29,7 +29,7 @@ class FileWriterTest { val text = mapper.readValue(result.toFile(), String::class.java) Assertions.assertEquals( data, - text + text, ) } @@ -42,7 +42,7 @@ class FileWriterTest { val text = mapper.readValue(result.toFile(), String::class.java) Assertions.assertEquals( data, - text + text, ) } } diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 8143ce4d..5b18ed43 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -2,7 +2,7 @@ docker = { id = "com.avast.gradle.docker-compose", version = "0.17.7" } web3j = { id = "org.web3j", version.ref = "web3j" } web3jSolidity = { id = "org.web3j.solidity", version = "0.5.0" } -spotless = { id = "com.diffplug.spotless", version = "6.16.0" } # TODO in later ticket - Update to >=6.25.0, which breaks the CI +spotless = { id = "com.diffplug.spotless", version = "6.25.0" } jreleaser = {id = "org.jreleaser", version = "1.15.0"} dependencyLicenseReport = { id = "com.github.jk1.dependency-license-report", version = "2.9" } lombok = { id = "io.freefair.lombok", version = "8.6" } @@ -38,7 +38,7 @@ jackson = "2.19.0" jna = "5.14.0" kotlinResult = "1.1.16" kotlinxDatetime = "0.6.2" -ktlint = "0.47.0" +ktlint = "0.50.0" lineaKotlin = "0.1.0" log4j = "2.24.1" micrometer = "1.8.4" diff --git a/jvm-libs/generic/errors/src/main/kotlin/net/consensys/linea/errors/ErrorResponse.kt b/jvm-libs/generic/errors/src/main/kotlin/net/consensys/linea/errors/ErrorResponse.kt index b1d3f6bb..729df2c1 100644 --- a/jvm-libs/generic/errors/src/main/kotlin/net/consensys/linea/errors/ErrorResponse.kt +++ b/jvm-libs/generic/errors/src/main/kotlin/net/consensys/linea/errors/ErrorResponse.kt @@ -3,6 +3,6 @@ package net.consensys.linea.errors data class ErrorResponse(val type: E, val message: String) { fun asException(messagePrefix: String? = null, messageSuffix: String? = null) = Exception( - "${messagePrefix?.let { "$it: " } ?: ""}${this.type} ${this.message}.${messageSuffix?.let { " $it" } ?: ""}" + "${messagePrefix?.let { "$it: " } ?: ""}${this.type} ${this.message}.${messageSuffix?.let { " $it" } ?: ""}", ) } diff --git a/jvm-libs/generic/extensions/futures/src/main/kotlin/net/consensys/linea/async/AsyncRetryer.kt b/jvm-libs/generic/extensions/futures/src/main/kotlin/net/consensys/linea/async/AsyncRetryer.kt index d84eff68..33a8fe92 100644 --- a/jvm-libs/generic/extensions/futures/src/main/kotlin/net/consensys/linea/async/AsyncRetryer.kt +++ b/jvm-libs/generic/extensions/futures/src/main/kotlin/net/consensys/linea/async/AsyncRetryer.kt @@ -18,7 +18,7 @@ interface AsyncRetryer { stopRetriesPredicate: (T) -> Boolean = ::alwaysTruePredicate, stopRetriesOnErrorPredicate: (Throwable) -> Boolean = ::alwaysFalsePredicate, exceptionConsumer: Consumer? = null, - action: () -> SafeFuture + action: () -> SafeFuture, ): SafeFuture companion object { @@ -27,14 +27,14 @@ interface AsyncRetryer { backoffDelay: Duration, maxRetries: Int? = null, timeout: Duration? = null, - initialDelay: Duration? = null + initialDelay: Duration? = null, ): AsyncRetryer { return SequentialAsyncRetryerFactory( vertx = vertx, backoffDelay = backoffDelay, maxRetries = maxRetries, initialDelay = initialDelay, - timeout = timeout + timeout = timeout, ) } @@ -47,14 +47,14 @@ interface AsyncRetryer { stopRetriesPredicate: (T) -> Boolean = ::alwaysTruePredicate, stopRetriesOnErrorPredicate: (Throwable) -> Boolean = ::alwaysFalsePredicate, exceptionConsumer: Consumer? = null, - action: () -> SafeFuture + action: () -> SafeFuture, ): SafeFuture { return SequentialAsyncRetryerFactory( vertx = vertx, backoffDelay = backoffDelay, maxRetries = maxRetries, timeout = timeout, - initialDelay = initialDelay + initialDelay = initialDelay, ).retry(stopRetriesPredicate, stopRetriesOnErrorPredicate, exceptionConsumer, action) } } @@ -72,7 +72,7 @@ internal class SequentialAsyncActionRetryer( val stopRetriesPredicate: (T) -> Boolean = ::alwaysTruePredicate, val stopRetriesOnErrorPredicate: (Throwable) -> Boolean = ::alwaysFalsePredicate, val exceptionConsumer: Consumer? = null, - val action: () -> SafeFuture + val action: () -> SafeFuture, ) { init { require(backoffDelay >= 1.milliseconds) { "backoffDelay must be >= 1ms. value=$backoffDelay" } @@ -171,7 +171,7 @@ private class SequentialAsyncRetryerFactory( val backoffDelay: Duration, val maxRetries: Int? = null, val timeout: Duration? = null, - val initialDelay: Duration? = null + val initialDelay: Duration? = null, ) : AsyncRetryer { override fun retry(action: () -> SafeFuture): SafeFuture { return SequentialAsyncActionRetryer( @@ -182,7 +182,7 @@ private class SequentialAsyncRetryerFactory( initialDelay = initialDelay, stopRetriesPredicate = ::alwaysTruePredicate, exceptionConsumer = null, - action = action + action = action, ).retry() } @@ -190,7 +190,7 @@ private class SequentialAsyncRetryerFactory( stopRetriesPredicate: (T) -> Boolean, stopRetriesOnErrorPredicate: (Throwable) -> Boolean, exceptionConsumer: Consumer?, - action: () -> SafeFuture + action: () -> SafeFuture, ): SafeFuture { return SequentialAsyncActionRetryer( vertx = vertx, @@ -201,7 +201,7 @@ private class SequentialAsyncRetryerFactory( stopRetriesPredicate = stopRetriesPredicate, stopRetriesOnErrorPredicate = stopRetriesOnErrorPredicate, exceptionConsumer = exceptionConsumer, - action = action + action = action, ).retry() } } diff --git a/jvm-libs/generic/extensions/futures/src/test/kotlin/net/consensys/linea/async/AsyncRetryerTest.kt b/jvm-libs/generic/extensions/futures/src/test/kotlin/net/consensys/linea/async/AsyncRetryerTest.kt index ddbd7222..4222bc73 100644 --- a/jvm-libs/generic/extensions/futures/src/test/kotlin/net/consensys/linea/async/AsyncRetryerTest.kt +++ b/jvm-libs/generic/extensions/futures/src/test/kotlin/net/consensys/linea/async/AsyncRetryerTest.kt @@ -29,7 +29,7 @@ class AsyncRetryerTest { maxRetries = -1, initialDelay = 5.milliseconds, timeout = 2.seconds, - stopRetriesPredicate = { result -> result == "20" } + stopRetriesPredicate = { result -> result == "20" }, ) { callCount++ SafeFuture.completedFuture("true") @@ -49,7 +49,7 @@ class AsyncRetryerTest { maxRetries = 3, initialDelay = 5.milliseconds, timeout = 0.seconds, - stopRetriesPredicate = { result -> result == "20" } + stopRetriesPredicate = { result -> result == "20" }, ) { callCount++ SafeFuture.completedFuture("true") @@ -61,7 +61,7 @@ class AsyncRetryerTest { @Test fun `Retryer should retry endlessly until predicate is met when both timeout and maxRetries are null`( - vertx: Vertx + vertx: Vertx, ) { val callCount = AtomicInteger(0) val expectedResult = "6" @@ -69,7 +69,7 @@ class AsyncRetryerTest { AsyncRetryer.retry( vertx = vertx, backoffDelay = 5.milliseconds, - stopRetriesPredicate = { result -> result == expectedResult } + stopRetriesPredicate = { result -> result == expectedResult }, ) { SafeFuture.completedFuture("${callCount.incrementAndGet()}") }.get() @@ -80,14 +80,14 @@ class AsyncRetryerTest { @Test fun `Retryer should retry endlessly until stopRetriesOnErrorPredicate returns true`( - vertx: Vertx + vertx: Vertx, ) { val callCount = AtomicInteger(0) val future = AsyncRetryer.retry( vertx = vertx, backoffDelay = 5.milliseconds, - stopRetriesOnErrorPredicate = { error -> error.message == "stop now" } + stopRetriesOnErrorPredicate = { error -> error.message == "stop now" }, ) { if (callCount.incrementAndGet() < 3) { SafeFuture.failedFuture(RuntimeException("${callCount.get()}")) @@ -116,7 +116,7 @@ class AsyncRetryerTest { @Test fun `Retryer should retry endlessly if predicate is never met when both timeout and maxRetries are null`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { val callCount = AtomicInteger(0) val everPendingFuture = @@ -143,7 +143,7 @@ class AsyncRetryerTest { maxRetries = 3, initialDelay = 5.milliseconds, timeout = 2.seconds, - stopRetriesPredicate = { result -> result == "20" } + stopRetriesPredicate = { result -> result == "20" }, ) { callCount++ SafeFuture.completedFuture("true") @@ -163,7 +163,7 @@ class AsyncRetryerTest { maxRetries = 3, initialDelay = 50.nanoseconds, timeout = 2.seconds, - stopRetriesPredicate = { result -> result == "20" } + stopRetriesPredicate = { result -> result == "20" }, ) { callCount++ SafeFuture.completedFuture("true") @@ -267,7 +267,7 @@ class AsyncRetryerTest { vertx, backoffDelay = 5.milliseconds, timeout = 60.milliseconds, - stopRetriesPredicate = { false } // stop condition will never be met + stopRetriesPredicate = { false }, // stop condition will never be met ) { SafeFuture.completedFuture("${callCount.incrementAndGet()}") } diff --git a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/jvm/ResourcesUtil.kt b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/jvm/ResourcesUtil.kt index 163b6432..6a57cd10 100644 --- a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/jvm/ResourcesUtil.kt +++ b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/jvm/ResourcesUtil.kt @@ -17,18 +17,18 @@ object ResourcesUtil { fun copyResourceToTmpDir( resourcePath: String, classLoader: ClassLoader, - tmpDirPrefix: String = "linea-resources-" + tmpDirPrefix: String = "linea-resources-", ): Path { val fileDestination = File( Files.createTempDirectory(tmpDirPrefix) .resolve(Path.of(resourcePath).fileName) - .toString() + .toString(), ) val resourceInputStream = classLoader.getResourceAsStream(resourcePath) ?: throw IllegalStateException("Resource not found: $resourcePath") Files.copy( resourceInputStream, - fileDestination.toPath() + fileDestination.toPath(), ) return fileDestination.toPath() } diff --git a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/ByteArrayExtensions.kt b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/ByteArrayExtensions.kt index 772a0fa2..55c9d851 100644 --- a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/ByteArrayExtensions.kt +++ b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/ByteArrayExtensions.kt @@ -30,7 +30,7 @@ fun ByteArray.padLeft(targetSize: Int, padding: Byte = 0x0): ByteArray { fun ByteArray.sliceOf( sliceSize: Int, sliceNumber: Int, - allowIncompleteLastSlice: Boolean = false + allowIncompleteLastSlice: Boolean = false, ): ByteArray { assert(sliceSize > 0) { "sliceSize=$sliceSize should be greater than 0" diff --git a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/RangeExtensions.kt b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/RangeExtensions.kt index edeaf875..1d3326b0 100644 --- a/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/RangeExtensions.kt +++ b/jvm-libs/generic/extensions/kotlin/src/main/kotlin/linea/kotlin/RangeExtensions.kt @@ -6,9 +6,9 @@ internal fun > isRangeWithin(outer: ClosedRange, inner: Clo fun > ClosedRange.contains(inner: ClosedRange): Boolean = isRangeWithin( outer = this, - inner = inner + inner = inner, ) fun > ClosedRange.isWithin(outer: ClosedRange): Boolean = isRangeWithin( outer = outer, - inner = this + inner = this, ) diff --git a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/jvm/ResourcesUtilTest.kt b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/jvm/ResourcesUtilTest.kt index 1db623c8..8d407905 100644 --- a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/jvm/ResourcesUtilTest.kt +++ b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/jvm/ResourcesUtilTest.kt @@ -14,7 +14,7 @@ class ResourcesUtilTest { val file = copyResourceToTmpDir( resourcePath = "root-resource.txt", classLoader = classLoader, - tmpDirPrefix = "testing-resources-" + tmpDirPrefix = "testing-resources-", ) assertThat(Files.readString(file).trim()).isEqualTo("root resource 1") } @@ -25,13 +25,13 @@ class ResourcesUtilTest { copyResourceToTmpDir( resourcePath = "test/folder/nested-resource.txt", classLoader = classLoader, - tmpDirPrefix = "testing-resources-" + tmpDirPrefix = "testing-resources-", ) val file2Path = copyResourceToTmpDir( resourcePath = "test/folder2/nested-resource.txt", classLoader = classLoader, - tmpDirPrefix = "testing-resources-" + tmpDirPrefix = "testing-resources-", ) // make sure files with same name in different directories are not overwritten inside the same tmp directory @@ -45,7 +45,7 @@ class ResourcesUtilTest { copyResourceToTmpDir( resourcePath = "not-present-resource.txt", classLoader = classLoader, - tmpDirPrefix = "testing-resources-" + tmpDirPrefix = "testing-resources-", ) }.hasMessageContaining("Resource not found: not-present-resource.txt") } diff --git a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/StringExtensionsTest.kt b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/StringExtensionsTest.kt index d239794d..cc5dc556 100644 --- a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/StringExtensionsTest.kt +++ b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/StringExtensionsTest.kt @@ -19,7 +19,7 @@ class StringExtensionsTest { fun `String#containsAny`() { val stringList = listOf( "This is a TEST", - "lorem ipsum" + "lorem ipsum", ) assertThat("this is a test string ignoring cases".containsAny(stringList, ignoreCase = true)).isTrue() diff --git a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/ULongExtensionsTest.kt b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/ULongExtensionsTest.kt index 4be0573f..c6123469 100644 --- a/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/ULongExtensionsTest.kt +++ b/jvm-libs/generic/extensions/kotlin/src/test/kotlin/linea/kotlin/ULongExtensionsTest.kt @@ -9,7 +9,7 @@ class ULongExtensionsTest { 0.toULong() to "0x0", 1.toULong() to "0x1", 0xABC_DEF_123_456u to "0xabcdef123456", - ULong.MAX_VALUE to "0xffffffffffffffff" + ULong.MAX_VALUE to "0xffffffffffffffff", ) @Test diff --git a/jvm-libs/generic/extensions/kotlin/src/testFixtures/kotlin/net/consensys/FakeFixedClock.kt b/jvm-libs/generic/extensions/kotlin/src/testFixtures/kotlin/net/consensys/FakeFixedClock.kt index 11fc41c9..b61ddc05 100644 --- a/jvm-libs/generic/extensions/kotlin/src/testFixtures/kotlin/net/consensys/FakeFixedClock.kt +++ b/jvm-libs/generic/extensions/kotlin/src/testFixtures/kotlin/net/consensys/FakeFixedClock.kt @@ -8,7 +8,7 @@ import kotlinx.datetime.Instant */ class FakeFixedClock( - private var time: Instant = Clock.System.now() + private var time: Instant = Clock.System.now(), ) : Clock { @Synchronized diff --git a/jvm-libs/generic/extensions/tuweni/src/main/kotlin/build/linea/tuweni/Bytes32.kt b/jvm-libs/generic/extensions/tuweni/src/main/kotlin/build/linea/tuweni/Bytes32.kt index 3dc54adc..0d51927c 100644 --- a/jvm-libs/generic/extensions/tuweni/src/main/kotlin/build/linea/tuweni/Bytes32.kt +++ b/jvm-libs/generic/extensions/tuweni/src/main/kotlin/build/linea/tuweni/Bytes32.kt @@ -5,5 +5,5 @@ import org.apache.tuweni.bytes.Bytes32 import java.math.BigInteger fun ByteArray.toBytes32(): Bytes32 = Bytes32.wrap(this) -fun ByteArray.sliceAsBytes32(sliceIndex: Int): Bytes32 = Bytes32.wrap(this, /*offset*/sliceIndex * 32) +fun ByteArray.sliceAsBytes32(sliceIndex: Int): Bytes32 = Bytes32.wrap(this, sliceIndex * 32) fun Bytes32.toULong(): ULong = BigInteger(this.toArray()).toULong() diff --git a/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/HttpRestClient.kt b/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/HttpRestClient.kt index 5dc3ad9f..5e7af492 100644 --- a/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/HttpRestClient.kt +++ b/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/HttpRestClient.kt @@ -13,7 +13,8 @@ enum class RestErrorType(val code: Int?, val message: String?) { INTERNAL_SERVER_ERROR(500, "Internal server error"), BAD_GATEWAY(502, "Bad Gateway"), SERVICE_UNAVAILABLE(503, "Service Unavailable"), - UNKNOWN(null, null); + UNKNOWN(null, null), + ; companion object { fun fromStatusCode(code: Int?): RestErrorType { @@ -29,12 +30,12 @@ interface HttpRestClient { fun get( path: String, params: List> = emptyList(), - resultMapper: (Any?) -> Any? = ::identityMapper + resultMapper: (Any?) -> Any? = ::identityMapper, ): SafeFuture>> fun post( path: String, buffer: Buffer, - resultMapper: (Any?) -> Any? = ::identityMapper + resultMapper: (Any?) -> Any? = ::identityMapper, ): SafeFuture>> } diff --git a/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/VertxHttpRestClient.kt b/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/VertxHttpRestClient.kt index eac7416a..2ceea65b 100644 --- a/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/VertxHttpRestClient.kt +++ b/jvm-libs/generic/http-rest/src/main/kotlin/net/consensys/linea/httprest/client/VertxHttpRestClient.kt @@ -18,7 +18,7 @@ import java.net.URI class VertxHttpRestClient( private val webClientOptions: WebClientOptions, - private val vertx: Vertx + private val vertx: Vertx, ) : HttpRestClient { private var webClient = WebClient.create(vertx, webClientOptions) private val log: Logger = LogManager.getLogger(this.javaClass) @@ -26,7 +26,7 @@ class VertxHttpRestClient( override fun get( path: String, params: List>, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): SafeFuture>> { return webClient .get(webClientOptions.defaultPort, webClientOptions.defaultHost, path) @@ -50,9 +50,9 @@ class VertxHttpRestClient( webClientOptions.defaultPort, path, null, - null + null, ).toURL()}, " + - "statusMessage=${response.statusMessage()}" + "statusMessage=${response.statusMessage()}", ) val errorType = RestErrorType.fromStatusCode(response.statusCode()) Future.succeededFuture(Err(ErrorResponse(errorType, response.statusMessage()))) @@ -67,7 +67,7 @@ class VertxHttpRestClient( override fun post( path: String, buffer: Buffer, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): SafeFuture>> { return webClient .post(webClientOptions.defaultPort, webClientOptions.defaultHost, path) @@ -87,9 +87,9 @@ class VertxHttpRestClient( webClientOptions.defaultPort, path, null, - null + null, ).toURL()}, " + - "statusMessage=${httpResponse.statusMessage()}" + "statusMessage=${httpResponse.statusMessage()}", ) val errorType = RestErrorType.fromStatusCode(httpResponse.statusCode()) Future.succeededFuture(Err(ErrorResponse(errorType, httpResponse.statusMessage()))) diff --git a/jvm-libs/generic/http-rest/src/test/kotlin/VertxHttpRestClientTest.kt b/jvm-libs/generic/http-rest/src/test/kotlin/VertxHttpRestClientTest.kt index b6bb6947..49b59e47 100644 --- a/jvm-libs/generic/http-rest/src/test/kotlin/VertxHttpRestClientTest.kt +++ b/jvm-libs/generic/http-rest/src/test/kotlin/VertxHttpRestClientTest.kt @@ -61,8 +61,8 @@ class VertxHttpRestClientTest { post("$path/text") .withHeader("Content-Type", WireMock.containing("application/json")) .willReturn( - ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("hello") - ) + ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("hello"), + ), ) val response = @@ -79,7 +79,7 @@ class VertxHttpRestClientTest { node.put("status", "correct") wiremock.stubFor( get("$path/json") - .willReturn(ok().withHeader("Content-type", "application/json").withJsonBody(node)) + .willReturn(ok().withHeader("Content-type", "application/json").withJsonBody(node)), ) val response = @@ -95,8 +95,8 @@ class VertxHttpRestClientTest { wiremock.stubFor( get("$path/text") .willReturn( - ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("text") - ) + ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("text"), + ), ) val response = @@ -113,8 +113,8 @@ class VertxHttpRestClientTest { wiremock.stubFor( get("$path/text?1=one&2=two&3=three&4=four") .willReturn( - ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("text") - ) + ok().withHeader("Content-type", "text/plain; charset=utf-8\n").withBody("text"), + ), ) val response = @@ -129,7 +129,7 @@ class VertxHttpRestClientTest { fun get_serverErrorResponse() { wiremock.stubFor( get("$path/serverError") - .willReturn(serverError().withHeader("Content-type", "text/plain; charset=utf-8\n")) + .willReturn(serverError().withHeader("Content-type", "text/plain; charset=utf-8\n")), ) val response = client.get("$path/serverError").get() @@ -141,7 +141,7 @@ class VertxHttpRestClientTest { fun post_notFound() { wiremock.stubFor( post("$path/notFound") - .willReturn(notFound().withHeader("Content-type", "text/plain; charset=utf-8\n")) + .willReturn(notFound().withHeader("Content-type", "text/plain; charset=utf-8\n")), ) val response = client.post("$path/notFound", Buffer.buffer("")).get() @@ -155,8 +155,8 @@ class VertxHttpRestClientTest { .willReturn( notFound() .withHeader("Content-type", "text/plain; charset=utf-8\n") - .withStatusMessage("Param not found") - ) + .withStatusMessage("Param not found"), + ), ) val response = client.post("$path/notFound", Buffer.buffer("")).get() diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessor.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessor.kt index c05bff95..247e33b3 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessor.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessor.kt @@ -34,14 +34,15 @@ typealias JsonRpcRequestParser = typealias JsonRpcRequestHandler = (user: User?, jsonRpcRequest: JsonRpcRequest, requestJson: JsonObject) -> Future< - Result> + Result, + > fun Result<*, *>.isSuccess(): Boolean = this is Ok private data class RequestContext( val id: Any, val method: String, - val result: Result + val result: Result, ) /** @@ -54,7 +55,7 @@ class JsonRpcMessageProcessor( private val requestParser: JsonRpcRequestParser = Companion::parseRequest, private val log: Logger = LogManager.getLogger(JsonRpcMessageProcessor::class.java), private val responseResultObjectMapper: ObjectMapper = jacksonObjectMapper().registerModules(VertxModule()), - private val rpcEnvelopeObjectMapper: ObjectMapper = jacksonObjectMapper() + private val rpcEnvelopeObjectMapper: ObjectMapper = jacksonObjectMapper(), ) : JsonRpcMessageHandler { init { DatabindCodec.mapper().registerKotlinModule() @@ -65,27 +66,27 @@ class JsonRpcMessageProcessor( private fun handleAndMeasureRequestProcessing( user: User?, - requestJsonStr: String + requestJsonStr: String, ): Future { return Future.fromCompletionStage( metricsFacade.createDynamicTagTimer>( name = "jsonrpc.processing.whole", description = "Processing of JSON-RPC message: Deserialization + Business Logic + Serialization", tagKey = "method", - tagValueExtractorOnError = { "METHOD_PROCESSING_ERROR" } + tagValueExtractorOnError = { "METHOD_PROCESSING_ERROR" }, ) { it.first!! } .captureTime( handleMessage( user = user, - requestJsonStr = requestJsonStr - ).toCompletionStage().toCompletableFuture() + requestJsonStr = requestJsonStr, + ).toCompletionStage().toCompletableFuture(), ) .thenApply { logResponse(it.third, it.second, requestJsonStr) it.second - } + }, ) } @@ -122,14 +123,14 @@ class JsonRpcMessageProcessor( return handleMessageRequests( user = user, parsingResults = requestParsingResults, - methodTag = methodTag + methodTag = methodTag, ) } private fun handleMessageRequests( user: User?, parsingResults: List, JsonRpcErrorResponse>>, - methodTag: String + methodTag: String, ): Future> { var allSuccessful = true val executionFutures: List> = @@ -143,14 +144,14 @@ class JsonRpcMessageProcessor( "Failed processing JSON-RPC request. error: {}", // NullPointerException have null message, at least log the class name error.message ?: error::class.java, - error + error, ) Future.succeededFuture( RequestContext( rpc.id, rpc.method, - Err(JsonRpcErrorResponse.internalError(rpc.id, null)) - ) + Err(JsonRpcErrorResponse.internalError(rpc.id, null)), + ), ) } } @@ -175,7 +176,7 @@ class JsonRpcMessageProcessor( } else { metricsFacade.createSimpleTimer( name = "jsonrpc.serialization.response.bulk", - description = "Time of bulk json response serialization" + description = "Time of bulk json response serialization", ).captureTime { responses.joinToString(",", "[", "]") } } Future.succeededFuture(Triple(methodTag, finalResponseJsonStr, allSuccessful)) @@ -183,13 +184,13 @@ class JsonRpcMessageProcessor( } private fun measureRequestParsing( - json: Any + json: Any, ): Result, JsonRpcErrorResponse> { return metricsFacade.createDynamicTagTimer( name = "jsonrpc.serialization.request", description = "json-rpc method parsing", tagKey = "method", - tagValueExtractorOnError = { "METHOD_PARSE_ERROR" } + tagValueExtractorOnError = { "METHOD_PARSE_ERROR" }, ) { parsingResult: Result, JsonRpcErrorResponse> -> parsingResult.map { it.first.method }.recover { "METHOD_PARSE_ERROR" }.value @@ -200,7 +201,7 @@ class JsonRpcMessageProcessor( val timerCapture = metricsFacade.createSimpleTimer( name = "jsonrpc.serialization.response", description = "Time of json response serialization", - tags = listOf(Tag("method", requestContext.method)) + tags = listOf(Tag("method", requestContext.method)), ) return timerCapture.captureTime { @@ -215,12 +216,12 @@ class JsonRpcMessageProcessor( private fun handleAndMeasureRequestHandling( user: User?, jsonRpcRequest: JsonRpcRequest, - requestJson: JsonObject + requestJson: JsonObject, ): Future> { return metricsFacade.createSimpleTimer>>( name = "jsonrpc.processing.logic", description = "Processing of a particular JRPC method's logic without SerDes", - tags = listOf(Tag("method", jsonRpcRequest.method)) + tags = listOf(Tag("method", jsonRpcRequest.method)), ) .captureTime { callRequestHandlerAndCatchError(user, jsonRpcRequest, requestJson) } .onComplete { result: AsyncResult> -> @@ -230,8 +231,8 @@ class JsonRpcMessageProcessor( description = "Counting the JSON rpc request with result and method", tags = listOf( Tag("success", success.toString()), - Tag("method", jsonRpcRequest.method) - ) + Tag("method", jsonRpcRequest.method), + ), ).increment() } } @@ -239,7 +240,7 @@ class JsonRpcMessageProcessor( private fun callRequestHandlerAndCatchError( user: User?, jsonRpcRequest: JsonRpcRequest, - requestJson: JsonObject + requestJson: JsonObject, ): Future> { val promise = Promise.promise>() diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequest.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequest.kt index 1ac494b2..5b49cd83 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequest.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequest.kt @@ -23,14 +23,14 @@ internal data class JsonRpcRequestData( override val jsonrpc: String, override val id: Any, override val method: String, - override val params: Any + override val params: Any, ) : JsonRpcRequest data class JsonRpcRequestListParams( override val jsonrpc: String, override val id: Any, override val method: String, - override val params: List + override val params: List, ) : JsonRpcRequest { override fun toString(): String { return StringJoiner(", ", JsonRpcRequestListParams::class.java.simpleName + "[", "]") @@ -46,7 +46,7 @@ data class JsonRpcRequestMapParams( override val jsonrpc: String, override val id: Any, override val method: String, - override val params: Map + override val params: Map, ) : JsonRpcRequest { override fun toString(): String { return StringJoiner(", ", JsonRpcRequestMapParams::class.java.simpleName + "[", "]") diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequestRouter.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequestRouter.kt index 9caaa86a..b39c89d9 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequestRouter.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcRequestRouter.kt @@ -11,12 +11,12 @@ class JsonRpcRequestRouter(private val methodHandlers: Map> { val handler = methodHandlers[jsonRpcRequest.method] ?: return Future.succeededFuture( - Err(JsonRpcErrorResponse.methodNotFound(jsonRpcRequest.id, jsonRpcRequest.method)) + Err(JsonRpcErrorResponse.methodNotFound(jsonRpcRequest.id, jsonRpcRequest.method)), ) return handler.invoke(user, jsonRpcRequest, requestJson) diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcResponse.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcResponse.kt index b244bf50..bfdbd0e8 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcResponse.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/JsonRpcResponse.kt @@ -10,7 +10,8 @@ enum class JsonRpcErrorCode(val code: Int, val message: String) { METHOD_NOT_FOUND(-32601, "Method not found"), INVALID_PARAMS(-32602, "Invalid params"), INTERNAL_ERROR(-32603, "Internal error"), - UNAUTHORIZED(-40100, "Unauthorized"); + UNAUTHORIZED(-40100, "Unauthorized"), + ; fun toErrorObject(data: Any? = null): JsonRpcError { return JsonRpcError(this.code, this.message, data) @@ -29,7 +30,7 @@ abstract class JsonRpcResponse(open val jsonrpc: String = "2.0", open val id: An data class JsonRpcSuccessResponse( override val jsonrpc: String, override val id: Any, - val result: Any? + val result: Any?, ) : JsonRpcResponse(jsonrpc, id) { constructor(id: Any, result: Any?) : this("2.0", id, result) constructor(request: JsonRpcRequest, result: Any?) : this(request.jsonrpc, id = request.id, result) @@ -39,7 +40,7 @@ data class JsonRpcSuccessResponse( @JsonInclude(JsonInclude.Include.NON_NULL) data class JsonRpcErrorResponse( @JsonProperty("id") override val id: Any?, - @JsonProperty("error") val error: JsonRpcError + @JsonProperty("error") val error: JsonRpcError, ) : JsonRpcResponse(id = id) { companion object { @@ -74,7 +75,7 @@ data class JsonRpcErrorResponse( data class JsonRpcError( @JsonProperty("code") val code: Int, @JsonProperty("message") val message: String, - @JsonProperty("data") val data: Any? = null + @JsonProperty("data") val data: Any? = null, ) { // inlining for better stacktrace @Suppress("NOTHING_TO_INLINE") @@ -85,7 +86,7 @@ data class JsonRpcError( fun invalidMethodParameter(message: String?): JsonRpcError = JsonRpcError( JsonRpcErrorCode.INVALID_PARAMS.code, - message ?: JsonRpcErrorCode.INVALID_PARAMS.message + message ?: JsonRpcErrorCode.INVALID_PARAMS.message, ) @JvmStatic @@ -106,13 +107,13 @@ data class JsonRpcError( class JsonRpcErrorException( override val message: String?, - val httpStatusCode: Int? = null + val httpStatusCode: Int? = null, ) : RuntimeException(message) class JsonRpcErrorResponseException( val rpcErrorCode: Int, val rpcErrorMessage: String, - val rpcErrorData: Any? = null + val rpcErrorData: Any? = null, ) : RuntimeException("code=$rpcErrorCode message=$rpcErrorMessage errorData=$rpcErrorData") { fun asJsonRpcError(): JsonRpcError = JsonRpcError(rpcErrorCode, rpcErrorMessage, rpcErrorData) } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/argument/ArgumentGetter.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/argument/ArgumentGetter.kt index 66152ff5..dd0e0ce0 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/argument/ArgumentGetter.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/argument/ArgumentGetter.kt @@ -6,7 +6,7 @@ fun getArgument( clazz: KClass, arguments: List<*>, argPosition: Int, - argumentName: String + argumentName: String, ): T { return getArgument(clazz, arguments, argPosition, argumentName, nullable = false)!! } @@ -15,7 +15,7 @@ fun getOptionalArgument( clazz: KClass, arguments: List<*>, argPosition: Int, - argumentName: String + argumentName: String, ): T? { return getArgument(clazz, arguments, argPosition, argumentName, nullable = true) } @@ -25,7 +25,7 @@ internal fun getArgument( arguments: List<*>, argPosition: Int, argumentName: String, - nullable: Boolean = false + nullable: Boolean = false, ): T? { require(arguments.size > argPosition) { "Argument $argumentName not provided in arguments list at position $argPosition. Total arguments ${arguments.size}" @@ -35,7 +35,7 @@ internal fun getArgument( arguments[argPosition] ?: if (!nullable) { throw IllegalArgumentException( - "Required argument $argumentName at position $argPosition is null." + "Required argument $argumentName at position $argPosition is null.", ) } else { return null diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcClient.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcClient.kt index 3cfcddaf..24022815 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcClient.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcClient.kt @@ -41,7 +41,7 @@ fun toPrimitiveOrVertxJson(value: Any?): Any? { interface JsonRpcClient { fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? = ::toPrimitiveOrVertxJson // to keep backward compatibility + resultMapper: (Any?) -> Any? = ::toPrimitiveOrVertxJson, // to keep backward compatibility ): Future> } @@ -51,6 +51,6 @@ interface JsonRpcClientWithRetries : JsonRpcClient { fun makeRequest( request: JsonRpcRequest, resultMapper: (Any?) -> Any? = ::toPrimitiveOrVertxJson, // to keep backward compatibility - stopRetriesPredicate: (result: Result) -> Boolean = ::isResultOk + stopRetriesPredicate: (result: Result) -> Boolean = ::isResultOk, ): Future> } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOut.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOut.kt index 589205ad..9a495e96 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOut.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOut.kt @@ -10,7 +10,7 @@ import net.consensys.linea.jsonrpc.JsonRpcRequest import net.consensys.linea.jsonrpc.JsonRpcSuccessResponse class JsonRpcRequestFanOut( - private val targets: List + private val targets: List, ) : JsonRpcClient { init { require(targets.isNotEmpty()) { "Must have at least one target to fan out the requests" } @@ -24,7 +24,7 @@ class JsonRpcRequestFanOut( */ override fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { return this.fanoutRequest(request, resultMapper).map { results -> val errors = results.filterIsInstance>() @@ -39,7 +39,7 @@ class JsonRpcRequestFanOut( fun fanoutRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? = ::toPrimitiveOrVertxJson + resultMapper: (Any?) -> Any? = ::toPrimitiveOrVertxJson, ): Future>> { return Future .all(targets.map { it.makeRequest(request, resultMapper) }) diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryer.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryer.kt index 0bb63782..2c006132 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryer.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryer.kt @@ -25,7 +25,7 @@ data class RequestRetryConfig( val maxRetries: UInt? = null, val timeout: Duration? = null, val backoffDelay: Duration, - val failuresWarningThreshold: UInt = 0u + val failuresWarningThreshold: UInt = 0u, ) { init { maxRetries?.also { @@ -47,24 +47,24 @@ class JsonRpcRequestRetryer( private val config: Config, private val requestObjectMapper: ObjectMapper = objectMapper, private val log: Logger = LogManager.getLogger(JsonRpcRequestRetryer::class.java), - private val failuresLogLevel: Level = Level.WARN + private val failuresLogLevel: Level = Level.WARN, ) : JsonRpcClientWithRetries { data class Config( val methodsToRetry: Set, - val requestRetry: RequestRetryConfig + val requestRetry: RequestRetryConfig, ) private val retryer: AsyncRetryer> = AsyncRetryer.retryer( vertx = this.vertx, backoffDelay = config.requestRetry.backoffDelay, maxRetries = config.requestRetry.maxRetries?.toInt(), - timeout = config.requestRetry.timeout + timeout = config.requestRetry.timeout, ) override fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { return makeRequest(request, resultMapper, ::isResultOk) } @@ -72,7 +72,7 @@ class JsonRpcRequestRetryer( override fun makeRequest( request: JsonRpcRequest, resultMapper: (Any?) -> Any?, - stopRetriesPredicate: (result: Result) -> Boolean + stopRetriesPredicate: (result: Result) -> Boolean, ): Future> { if (request.method in config.methodsToRetry) { return makeRequestWithRetryer(request, resultMapper, stopRetriesPredicate) @@ -84,7 +84,7 @@ class JsonRpcRequestRetryer( private fun makeRequestWithRetryer( request: JsonRpcRequest, resultMapper: (Any?) -> Any?, - stopRetriesPredicate: (result: Result) -> Boolean + stopRetriesPredicate: (result: Result) -> Boolean, ): Future> { val lastResult = AtomicReference>() val lastException = AtomicReference() @@ -94,7 +94,7 @@ class JsonRpcRequestRetryer( stopRetriesPredicate = { result: Result -> lastResult.set(result) stopRetriesPredicate.invoke(result) - } + }, ) { if (config.requestRetry.failuresWarningThreshold > 0u && retriesCount.get() > 0 && @@ -105,7 +105,7 @@ class JsonRpcRequestRetryer( "Request '{}' already retried {} times. lastError={}", requestObjectMapper.writeValueAsString(request), retriesCount.get(), - lastException.get() + lastException.get(), ) } retriesCount.incrementAndGet() diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerV2.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerV2.kt index 1ceb0f42..63787260 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerV2.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerV2.kt @@ -29,12 +29,12 @@ class JsonRpcRequestRetryerV2( private val requestObjectMapper: ObjectMapper = objectMapper, private val shallRetryRequestsClientBasePredicate: Predicate>, private val log: Logger = LogManager.getLogger(JsonRpcRequestRetryer::class.java), - private val failuresLogLevel: Level = Level.WARN + private val failuresLogLevel: Level = Level.WARN, ) { fun makeRequest( request: JsonRpcRequest, shallRetryRequestPredicate: Predicate>, - resultMapper: (Any?) -> T + resultMapper: (Any?) -> T, ): SafeFuture { return makeRequestWithRetryer(request, resultMapper, shallRetryRequestPredicate) } @@ -48,7 +48,7 @@ class JsonRpcRequestRetryerV2( private fun makeRequestWithRetryer( request: JsonRpcRequest, resultMapper: (Any?) -> T, - shallRetryRequestPredicate: Predicate> + shallRetryRequestPredicate: Predicate>, ): SafeFuture { val lastException = AtomicReference() val retriesCount = AtomicInteger(0) @@ -64,7 +64,7 @@ class JsonRpcRequestRetryerV2( stopRetriesPredicate = { result: Result -> result.onFailure(lastException::set) !requestPredicate.test(result) - } + }, ) { if (shallWarnFailureRetries(retriesCount.get())) { log.log( @@ -72,7 +72,7 @@ class JsonRpcRequestRetryerV2( "Request '{}' already retried {} times. lastError={}", requestObjectMapper.writeValueAsString(request), retriesCount.get(), - lastException.get() + lastException.get(), ) } retriesCount.incrementAndGet() @@ -97,7 +97,7 @@ class JsonRpcRequestRetryerV2( companion object { fun unfoldResultValueOrException( - response: Result + response: Result, ): Result { @Suppress("UNCHECKED_CAST") return response diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2Client.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2Client.kt index 20fef844..e63338e9 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2Client.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2Client.kt @@ -29,6 +29,6 @@ interface JsonRpcV2Client { method: String, params: Any, // List, Map, Pojo shallRetryRequestPredicate: Predicate> = Predicate { false }, - resultMapper: (Any?) -> T + resultMapper: (Any?) -> T, ): SafeFuture } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImpl.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImpl.kt index ac73bc1c..8da7fbd2 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImpl.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImpl.kt @@ -8,21 +8,21 @@ import java.util.function.Supplier internal class JsonRpcV2ClientImpl( private val delegate: JsonRpcRequestRetryerV2, - private val idSupplier: Supplier + private val idSupplier: Supplier, ) : JsonRpcV2Client { override fun makeRequest( method: String, params: Any, shallRetryRequestPredicate: Predicate>, - resultMapper: (Any?) -> T + resultMapper: (Any?) -> T, ): SafeFuture { val request = JsonRpcRequestData(jsonrpc = "2.0", id = idSupplier.get(), method, params) return delegate.makeRequest( request = request, shallRetryRequestPredicate = shallRetryRequestPredicate, - resultMapper = resultMapper + resultMapper = resultMapper, ) } } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClient.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClient.kt index 10c48de8..fbd31819 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClient.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClient.kt @@ -24,7 +24,7 @@ import java.util.concurrent.locks.ReentrantReadWriteLock class LoadBalancingJsonRpcClient private constructor( rpcClients: List, - private val maxInflightRequestsPerClient: UInt + private val maxInflightRequestsPerClient: UInt, ) : JsonRpcClient { companion object { @@ -32,11 +32,11 @@ private constructor( fun create( rpcClients: List, - requestLimitPerEndpoint: UInt + requestLimitPerEndpoint: UInt, ): LoadBalancingJsonRpcClient { val loadBalancingJsonRpcClient = LoadBalancingJsonRpcClient( rpcClients, - requestLimitPerEndpoint + requestLimitPerEndpoint, ) loadBalancingJsonRpcClients.add(loadBalancingJsonRpcClient) return loadBalancingJsonRpcClient @@ -55,7 +55,7 @@ private constructor( private data class RpcRequestContext( val request: JsonRpcRequest, val promise: Promise>, - val resultMapper: (Any?) -> Any? + val resultMapper: (Any?) -> Any?, ) private val clientsPool: List = rpcClients.map { RpcClientContext(it, 0u) } @@ -96,7 +96,7 @@ private constructor( private fun enqueueRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { val resultPromise: Promise> = Promise.promise() @@ -106,7 +106,7 @@ private constructor( override fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { val result = enqueueRequest(request, resultMapper) serveNextWaitingInTheQueue() @@ -115,7 +115,7 @@ private constructor( private fun dispatchRequest( rpcClientContext: RpcClientContext, - queuedRequest: RpcRequestContext + queuedRequest: RpcRequestContext, ) { rpcClientContext.rpcClient .makeRequest(queuedRequest.request, queuedRequest.resultMapper) diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClient.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClient.kt index a4463b8e..61f72362 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClient.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClient.kt @@ -34,7 +34,7 @@ class VertxHttpJsonRpcClient( private val responseObjectMapper: ObjectMapper = objectMapper, private val log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), private val requestResponseLogLevel: Level = Level.TRACE, - private val failuresLogLevel: Level = Level.DEBUG + private val failuresLogLevel: Level = Level.DEBUG, ) : JsonRpcClient { private val requestOptions = RequestOptions().apply { setMethod(HttpMethod.POST) @@ -47,14 +47,14 @@ class VertxHttpJsonRpcClient( jsonrpc = request.jsonrpc, id = request.id, method = request.method, - params = requestParamsObjectMapper.valueToTree(request.params) - ) + params = requestParamsObjectMapper.valueToTree(request.params), + ), ) } override fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { val json = serializeRequest(request) @@ -72,14 +72,14 @@ class VertxHttpJsonRpcClient( isError = true, response = response, requestBody = json, - responseBody = bodyBuffer.toString().lines().firstOrNull() ?: "" + responseBody = bodyBuffer.toString().lines().firstOrNull() ?: "", ) Future.failedFuture( JsonRpcErrorException( message = "HTTP errorCode=${response.statusCode()}, message=${response.statusMessage()}", - httpStatusCode = response.statusCode() - ) + httpStatusCode = response.statusCode(), + ), ) } } @@ -91,9 +91,9 @@ class VertxHttpJsonRpcClient( description = "Time of Upstream API JsonRpc Requests", tags = listOf( Tag("endpoint", endpoint.host), - Tag("method", request.method) - ) - ).captureTime(requestFuture.toCompletionStage().toCompletableFuture()) + Tag("method", request.method), + ), + ).captureTime(requestFuture.toCompletionStage().toCompletableFuture()), ) } .onFailure { th -> logRequestFailure(json, th) } @@ -102,7 +102,7 @@ class VertxHttpJsonRpcClient( private fun handleResponse( requestBody: String, httpResponse: HttpClientResponse, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { var isError = false var responseBody = "" @@ -119,8 +119,8 @@ class VertxHttpJsonRpcClient( Ok( JsonRpcSuccessResponse( responseId, - resultMapper(jsonResponse.get("result").toPrimitiveOrJsonNode()) - ) + resultMapper(jsonResponse.get("result").toPrimitiveOrJsonNode()), + ), ) } @@ -128,7 +128,7 @@ class VertxHttpJsonRpcClient( isError = true val errorResponse = JsonRpcErrorResponse( responseId, - responseObjectMapper.treeToValue(jsonResponse["error"], JsonRpcError::class.java) + responseObjectMapper.treeToValue(jsonResponse["error"], JsonRpcError::class.java), ) Err(errorResponse) } @@ -143,8 +143,8 @@ class VertxHttpJsonRpcClient( else -> Future.failedFuture( IllegalArgumentException( "Error parsing JSON-RPC response: message=${e.message}", - e - ) + e, + ), ) } } @@ -163,7 +163,7 @@ class VertxHttpJsonRpcClient( response: HttpClientResponse, requestBody: String, responseBody: String, - failureCause: Throwable? = null + failureCause: Throwable? = null, ) { val logLevel = if (isError) failuresLogLevel else requestResponseLogLevel if (isError && log.level != requestResponseLogLevel) { @@ -178,13 +178,13 @@ class VertxHttpJsonRpcClient( endpoint, response.statusCode(), responseBody, - failureCause?.message ?: "" + failureCause?.message ?: "", ) } private fun logRequestFailure( requestBody: String, - failureCause: Throwable + failureCause: Throwable, ) { log.log( failuresLogLevel, @@ -192,7 +192,7 @@ class VertxHttpJsonRpcClient( endpoint, requestBody, failureCause.message, - failureCause + failureCause, ) } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientFactory.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientFactory.kt index 2bd69471..a360a246 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientFactory.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientFactory.kt @@ -30,7 +30,7 @@ interface JsonRpcClientFactory { shallRetryRequestsClientBasePredicate: Predicate> = Predicate { it is Err }, log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): JsonRpcV2Client } @@ -39,7 +39,7 @@ class VertxHttpJsonRpcClientFactory( private val metricsFacade: MetricsFacade, private val requestResponseLogLevel: Level = Level.TRACE, private val failuresLogLevel: Level = Level.DEBUG, - private val requestIdSupplier: Supplier = SequentialIdSupplier.singleton + private val requestIdSupplier: Supplier = SequentialIdSupplier.singleton, ) : JsonRpcClientFactory { fun create( endpoint: URL, @@ -49,7 +49,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper: ObjectMapper = objectMapper, log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), requestResponseLogLevel: Level = this.requestResponseLogLevel, - failuresLogLevel: Level = this.failuresLogLevel + failuresLogLevel: Level = this.failuresLogLevel, ): VertxHttpJsonRpcClient { val clientOptions = HttpClientOptions() @@ -67,7 +67,7 @@ class VertxHttpJsonRpcClientFactory( requestParamsObjectMapper = requestObjectMapper, responseObjectMapper = responseObjectMapper, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) } @@ -79,7 +79,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper: ObjectMapper = objectMapper, log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), requestResponseLogLevel: Level = this.requestResponseLogLevel, - failuresLogLevel: Level = this.failuresLogLevel + failuresLogLevel: Level = this.failuresLogLevel, ): JsonRpcClient { return LoadBalancingJsonRpcClient.create( endpoints.map { endpoint -> @@ -91,10 +91,10 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper = responseObjectMapper, log = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) }, - maxInflightRequestsPerClient + maxInflightRequestsPerClient, ) } @@ -108,7 +108,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper: ObjectMapper = objectMapper, log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), requestResponseLogLevel: Level = this.requestResponseLogLevel, - failuresLogLevel: Level = this.failuresLogLevel + failuresLogLevel: Level = this.failuresLogLevel, ): JsonRpcClient { val rpcClient = create( endpoint = endpoint, @@ -118,7 +118,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper = responseObjectMapper, log = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) return JsonRpcRequestRetryer( @@ -126,9 +126,9 @@ class VertxHttpJsonRpcClientFactory( rpcClient, config = JsonRpcRequestRetryer.Config( methodsToRetry = methodsToRetry, - requestRetry = retryConfig + requestRetry = retryConfig, ), - log = log + log = log, ) } @@ -143,7 +143,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper: ObjectMapper = objectMapper, log: Logger = LogManager.getLogger(VertxHttpJsonRpcClient::class.java), requestResponseLogLevel: Level = this.requestResponseLogLevel, - failuresLogLevel: Level = this.failuresLogLevel + failuresLogLevel: Level = this.failuresLogLevel, ): JsonRpcClient { val loadBalancingClient = createWithLoadBalancing( endpoints = endpoints, @@ -153,7 +153,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper = responseObjectMapper, log = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) return JsonRpcRequestRetryer( @@ -161,11 +161,11 @@ class VertxHttpJsonRpcClientFactory( loadBalancingClient, config = JsonRpcRequestRetryer.Config( methodsToRetry = methodsToRetry, - requestRetry = retryConfig + requestRetry = retryConfig, ), requestObjectMapper = requestObjectMapper, failuresLogLevel = failuresLogLevel, - log = log + log = log, ) } @@ -179,7 +179,7 @@ class VertxHttpJsonRpcClientFactory( shallRetryRequestsClientBasePredicate: Predicate>, log: Logger, requestResponseLogLevel: Level, - failuresLogLevel: Level + failuresLogLevel: Level, ): JsonRpcV2Client { assert(endpoints.isNotEmpty()) { "endpoints set is empty " } assert(endpoints.size == endpoints.toSet().size) { @@ -196,7 +196,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper = responseObjectMapper, log = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) } else { create( @@ -206,7 +206,7 @@ class VertxHttpJsonRpcClientFactory( responseObjectMapper = responseObjectMapper, log = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel + failuresLogLevel = failuresLogLevel, ) }.let { // Wrap the client with a retryer @@ -217,13 +217,13 @@ class VertxHttpJsonRpcClientFactory( requestObjectMapper = requestObjectMapper, shallRetryRequestsClientBasePredicate = shallRetryRequestsClientBasePredicate, failuresLogLevel = failuresLogLevel, - log = log + log = log, ) }.let { // Wrap the client with a v2 client helper JsonRpcV2ClientImpl( delegate = it, - idSupplier = requestIdSupplier + idSupplier = requestIdSupplier, ) } } diff --git a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/httpserver/HttpJsonRpcServer.kt b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/httpserver/HttpJsonRpcServer.kt index 20dc92ee..8908f227 100644 --- a/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/httpserver/HttpJsonRpcServer.kt +++ b/jvm-libs/generic/json-rpc/src/main/kotlin/net/consensys/linea/jsonrpc/httpserver/HttpJsonRpcServer.kt @@ -15,7 +15,7 @@ class HttpJsonRpcServer( private val port: UInt, private val path: String, private val requestHandler: Handler, - val serverName: String = "" + val serverName: String = "", ) : AbstractVerticle() { private val log: Logger = LogManager.getLogger(this.javaClass) private lateinit var httpServer: HttpServer @@ -36,7 +36,7 @@ class HttpJsonRpcServer( log.info( "{} http server started and listening on port {}", serverName, - res.result().actualPort() + res.result().actualPort(), ) startPromise.complete() } else { diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/linea/jsonrpc/TestingJsonRpcServerTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/linea/jsonrpc/TestingJsonRpcServerTest.kt index bc3ba621..fd65ff5b 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/linea/jsonrpc/TestingJsonRpcServerTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/linea/jsonrpc/TestingJsonRpcServerTest.kt @@ -30,22 +30,22 @@ class TestingJsonRpcServerTest { fun beforeEach(vertx: io.vertx.core.Vertx) { jsonRpcServer = TestingJsonRpcServer( vertx = vertx, - recordRequestsResponses = true + recordRequestsResponses = true, ) val rpcClientFactory = VertxHttpJsonRpcClientFactory( vertx = vertx, - metricsFacade = MicrometerMetricsFacade(registry = SimpleMeterRegistry()) + metricsFacade = MicrometerMetricsFacade(registry = SimpleMeterRegistry()), ) client = rpcClientFactory.createJsonRpcV2Client( endpoints = listOf(URI.create("http://localhost:${jsonRpcServer.boundPort}")), retryConfig = RequestRetryConfig( maxRetries = 10u, backoffDelay = 10.milliseconds, - timeout = 2.minutes + timeout = 2.minutes, ), shallRetryRequestsClientBasePredicate = { false - } // disable retry + }, // disable retry ) } @@ -56,7 +56,7 @@ class TestingJsonRpcServerTest { method = "not_existing_method", params = mapOf("k1" to "v1", "k2" to 100), resultMapper = { it }, - shallRetryRequestPredicate = { false } + shallRetryRequestPredicate = { false }, ).get() }.hasCauseInstanceOf(JsonRpcErrorResponseException::class.java) .hasMessageContaining("Method not found") @@ -68,7 +68,7 @@ class TestingJsonRpcServerTest { assertThat(request.method).isEqualTo("not_existing_method") assertThat(request.params).isEqualTo(mapOf("k1" to "v1", "k2" to 100)) assertThat(responseFuture.get()).isEqualTo( - Err(JsonRpcErrorResponse.methodNotFound(request.id, data = "not_existing_method")) + Err(JsonRpcErrorResponse.methodNotFound(request.id, data = "not_existing_method")), ) } } @@ -91,8 +91,8 @@ class TestingJsonRpcServerTest { client.makeRequest( method = "add", params = listOf(1, 2, 3), - resultMapper = { it } - ).get() + resultMapper = { it }, + ).get(), ) .isEqualTo(6) @@ -100,8 +100,8 @@ class TestingJsonRpcServerTest { client.makeRequest( method = "addUser", params = mapOf("name" to "John", "email" to "john@email.com"), - resultMapper = { it } - ).get() + resultMapper = { it }, + ).get(), ) .isEqualTo("user=John email=john@email.com") diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessorTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessorTest.kt index 5d0dbee5..c3a04d25 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessorTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/JsonRpcMessageProcessorTest.kt @@ -38,12 +38,12 @@ class JsonRpcMessageProcessorTest { @Test fun `handleMessage should catch exceptions and return internal error`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val request = buildJsonRpcRequest(method = "eth_blockNumber") val processor = JsonRpcMessageProcessor( { _, _, _ -> throw RuntimeException("Something went wrong") }, - metricsFacade + metricsFacade, ) processor(null, request.toString()) .onComplete( @@ -51,16 +51,16 @@ class JsonRpcMessageProcessorTest { assertError( response, JsonObject.mapFrom(JsonRpcErrorCode.INTERNAL_ERROR.toErrorObject()), - request + request, ) testContext.completeNow() - } + }, ) } @Test fun `handleMessage should return error when message can't be deserialized`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val jsonStr = "{ bad json }" val future = processor(null, jsonStr) @@ -69,13 +69,13 @@ class JsonRpcMessageProcessorTest { testContext.succeeding { response -> assertError(response, expectedError) testContext.completeNow() - } + }, ) } @Test fun `handleMessage should return error when message contains invalid JSON-RPC request`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val jsonStr = Json.encode(JsonArray().add(JsonObject())) val future = processor(null, jsonStr) @@ -83,22 +83,22 @@ class JsonRpcMessageProcessorTest { testContext.succeeding { response -> assertError( response, - JsonObject.mapFrom(JsonRpcErrorCode.INVALID_REQUEST.toErrorObject()) + JsonObject.mapFrom(JsonRpcErrorCode.INVALID_REQUEST.toErrorObject()), ) testContext.completeNow() - } + }, ) } @Test fun `handleMessage bulk should return error when one message is invalid JSON-RPC request`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val requests = listOf( buildJsonRpcRequest(id = 1, "eth_blockNumber"), JsonObject().put("invalid_key", "any value"), - buildJsonRpcRequest(id = 2, "eth_getBlockByNumber", "latest") + buildJsonRpcRequest(id = 2, "eth_getBlockByNumber", "latest"), ) val jsonStr = Json.encode(JsonArray(requests)) @@ -107,16 +107,16 @@ class JsonRpcMessageProcessorTest { testContext.succeeding { response -> assertError( response, - JsonObject.mapFrom(JsonRpcErrorCode.INVALID_REQUEST.toErrorObject()) + JsonObject.mapFrom(JsonRpcErrorCode.INVALID_REQUEST.toErrorObject()), ) testContext.completeNow() - } + }, ) } @Test fun `handleMessage should execute single JSON-RPC request and return success response`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val request = buildJsonRpcRequest(method = "eth_blockNumber") processor(null, request.toString()) @@ -124,18 +124,18 @@ class JsonRpcMessageProcessorTest { testContext.succeeding { response -> assertResult(response, JsonObject(), request) testContext.completeNow() - } + }, ) } @Test fun `handleMessage should execute bulk JSON-RPC requests and return success response`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val requests = listOf( buildJsonRpcRequest(id = 1, "read_value"), - buildJsonRpcRequest(id = 2, "update_value", "latest") + buildJsonRpcRequest(id = 2, "update_value", "latest"), ) val jsonStr = Json.encode(JsonArray(requests)) @@ -146,7 +146,7 @@ class JsonRpcMessageProcessorTest { assertResult(responses.getJsonObject(0).toString(), JsonObject(), requests[0]) assertResult(responses.getJsonObject(1).toString(), JsonObject(), requests[1]) testContext.completeNow() - } + }, ) } @@ -158,9 +158,9 @@ class JsonRpcMessageProcessorTest { Err( JsonRpcErrorResponse( jsonRpcRequest.id, - JsonRpcError.invalidMethodParameter("Required argument missing") - ) - ) + JsonRpcError.invalidMethodParameter("Required argument missing"), + ), + ), ) -100 -> Future.failedFuture(Exception("An internal bug")) @@ -171,7 +171,7 @@ class JsonRpcMessageProcessorTest { @Test fun `handleMessage should return error when any of the requests fail`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val requests = listOf( @@ -181,7 +181,7 @@ class JsonRpcMessageProcessorTest { buildJsonRpcRequest(id = -100, "update_value", "latest"), buildJsonRpcRequest(id = 4, "update_value", "latest"), buildJsonRpcRequest(id = 5, "read_value"), - buildJsonRpcRequest(id = 6, "update_value", "latest") + buildJsonRpcRequest(id = 6, "update_value", "latest"), ) val jsonStr = Json.encode(JsonArray(requests)) @@ -196,18 +196,18 @@ class JsonRpcMessageProcessorTest { assertError( responses.getJsonObject(1).toString(), JsonObject.mapFrom( - JsonRpcError.invalidMethodParameter("Required argument missing") + JsonRpcError.invalidMethodParameter("Required argument missing"), ), - requests[1] + requests[1], ) assertResult(responses.getJsonObject(2).toString(), JsonObject(), requests[2]) assertError( responses.getJsonObject(3).toString(), JsonObject.mapFrom(JsonRpcError.internalError()), - requests[3] + requests[3], ) testContext.completeNow() - } + }, ) } @@ -222,7 +222,7 @@ class JsonRpcMessageProcessorTest { val bulkRequests1 = listOf( buildJsonRpcRequest(id = 1, "read_value"), - buildJsonRpcRequest(id = 2, "update_value", "latest") + buildJsonRpcRequest(id = 2, "update_value", "latest"), ) val bulkRequests2 = listOf( @@ -232,7 +232,7 @@ class JsonRpcMessageProcessorTest { buildJsonRpcRequest(id = -100, "update_value", "latest"), buildJsonRpcRequest(id = 4, "update_value", "latest"), buildJsonRpcRequest(id = 5, "read_value"), - buildJsonRpcRequest(id = 6, "update_value", "latest") + buildJsonRpcRequest(id = 6, "update_value", "latest"), ) val singleAsBulk = listOf(buildJsonRpcRequest(id = 10, "read_value")) @@ -257,26 +257,26 @@ class JsonRpcMessageProcessorTest { assertThat( meterRegistry .counter("jsonrpc.counter", "method", "read_value", "success", "true") - .count() + .count(), ) .isEqualTo(5.0) assertThat( meterRegistry .counter("jsonrpc.counter", "method", "read_value", "success", "false") - .count() + .count(), ) .isEqualTo(1.0) assertThat( meterRegistry .counter("jsonrpc.counter", "method", "update_value", "success", "true") - .count() + .count(), ) .isEqualTo(5.0) assertThat( meterRegistry .counter("jsonrpc.counter", "method", "update_value", "success", "false") - .count() + .count(), ) .isEqualTo(3.0) @@ -289,15 +289,15 @@ class JsonRpcMessageProcessorTest { assertThat(meterRegistry.timer("jsonrpc.serialization.request", "method", "read_value").count()) .isEqualTo(6) assertThat( - meterRegistry.timer("jsonrpc.serialization.request", "method", "update_value").count() + meterRegistry.timer("jsonrpc.serialization.request", "method", "update_value").count(), ) .isEqualTo(8) assertThat( - meterRegistry.timer("jsonrpc.serialization.response", "method", "read_value").count() + meterRegistry.timer("jsonrpc.serialization.response", "method", "read_value").count(), ) .isEqualTo(6) assertThat( - meterRegistry.timer("jsonrpc.serialization.response", "method", "update_value").count() + meterRegistry.timer("jsonrpc.serialization.response", "method", "update_value").count(), ) .isEqualTo(8) @@ -307,7 +307,7 @@ class JsonRpcMessageProcessorTest { private fun buildJsonRpcRequest( id: Int = 1, method: String = "eth_blockNumber", - vararg params: Any + vararg params: Any, ): JsonObject { return JsonObject() .put("jsonrpc", "2.0") @@ -319,7 +319,7 @@ class JsonRpcMessageProcessorTest { private fun assertResult( responseStr: String, expectedResult: JsonObject, - originalRequest: JsonObject + originalRequest: JsonObject, ) { val response = JsonObject(responseStr) assertThat(response.getValue("id")).isEqualTo(originalRequest.getValue("id")) @@ -330,7 +330,7 @@ class JsonRpcMessageProcessorTest { private fun assertError( responseStr: String, expectedError: Any, - originalRequest: JsonObject? = null + originalRequest: JsonObject? = null, ) { val response = JsonObject(responseStr) originalRequest?.let { diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOutTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOutTest.kt index 5aa12e0c..fa85c2ee 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOutTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestFanOutTest.kt @@ -44,8 +44,8 @@ class JsonRpcRequestFanOutTest { listOf( Ok(JsonRpcSuccessResponse("1", 1)), Ok(JsonRpcSuccessResponse("1", 2)), - Ok(JsonRpcSuccessResponse("1", 3)) - ) + Ok(JsonRpcSuccessResponse("1", 3)), + ), ) verify(rpcClient1).makeRequest(eq(request), anyOrNull()) verify(rpcClient2).makeRequest(eq(request), anyOrNull()) diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerTest.kt index 36473b84..abc441f6 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcRequestRetryerTest.kt @@ -41,7 +41,7 @@ class JsonRpcRequestRetryerTest { jsonrpc = "2.0", id = "1", method = "eth_blockNumber", - params = listOf("0x1") + params = listOf("0x1"), ) private val networkError1 = SocketException("Forced network error 1") private val networkError2 = SocketException("Forced network error 2") @@ -52,8 +52,8 @@ class JsonRpcRequestRetryerTest { maxRetries = maxRetries.toUInt(), timeout = 20.seconds, backoffDelay = 10.milliseconds, - failuresWarningThreshold = 2u - ) + failuresWarningThreshold = 2u, + ), ) private lateinit var vertx: Vertx @@ -65,7 +65,7 @@ class JsonRpcRequestRetryerTest { backoffDelay = 10.milliseconds, maxRetries = maxRetries, timeout = 20.seconds, - initialDelay = null + initialDelay = null, ) delegate = mock() { on { makeRequest(any(), anyOrNull()) } @@ -111,7 +111,7 @@ class JsonRpcRequestRetryerTest { val result = requestRetrier.makeRequest( ethBlockNumberRequest, - stopRetriesPredicate = { result -> result is Ok && result.value.result == "0x2" } + stopRetriesPredicate = { result -> result is Ok && result.value.result == "0x2" }, ).get() assertThat(result).isEqualTo(Ok(JsonRpcSuccessResponse("1", "0x2"))) @@ -161,7 +161,7 @@ class JsonRpcRequestRetryerTest { val error = assertThrows { requestRetrier.makeRequest( ethBlockNumberRequest, - stopRetriesPredicate = { result -> result is Ok && result.value.result == "0x100" } + stopRetriesPredicate = { result -> result is Ok && result.value.result == "0x100" }, ) .get() } @@ -183,10 +183,10 @@ class JsonRpcRequestRetryerTest { alwaysDownEndpoint, config.copy( methodsToRetry = methodsToRetry, - requestRetry = config.requestRetry.copy(failuresWarningThreshold = 2u) + requestRetry = config.requestRetry.copy(failuresWarningThreshold = 2u), ), log = log, - failuresLogLevel = Level.INFO + failuresLogLevel = Level.INFO, ) val error = assertThrows { requestRetryer.makeRequest(ethBlockNumberRequest).get() } @@ -197,14 +197,14 @@ class JsonRpcRequestRetryerTest { eq("Request '{}' already retried {} times. lastError={}"), eq("""{"jsonrpc":"2.0","id":"1","method":"eth_blockNumber","params":["0x1"]}"""), eq(2), - eq(networkError1) + eq(networkError1), ) verify(log).log( eq(Level.INFO), eq("Request '{}' already retried {} times. lastError={}"), eq("""{"jsonrpc":"2.0","id":"1","method":"eth_blockNumber","params":["0x1"]}"""), eq(4), - eq(networkError1) + eq(networkError1), ) } @@ -221,10 +221,10 @@ class JsonRpcRequestRetryerTest { alwaysDownEndpoint, config.copy( methodsToRetry = methodsToRetry, - requestRetry = config.requestRetry.copy(failuresWarningThreshold = 0u) + requestRetry = config.requestRetry.copy(failuresWarningThreshold = 0u), ), log = log, - failuresLogLevel = Level.INFO + failuresLogLevel = Level.INFO, ) val error = assertThrows { requestRetryer.makeRequest(ethBlockNumberRequest).get() } @@ -235,7 +235,7 @@ class JsonRpcRequestRetryerTest { any(), any(), any(), - eq(networkError1) + eq(networkError1), ) } } diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImplTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImplTest.kt index 6eaa4a87..b7f5e7b2 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImplTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/JsonRpcV2ClientImplTest.kt @@ -64,25 +64,25 @@ class JsonRpcV2ClientImplTest { SimpleModule().apply { this.addSerializer(ByteArray::class.java, ByteArrayToHexSerializer) this.addSerializer(ULong::class.java, ULongToHexSerializer) - } + }, ) private val jsonRpcResultOk = """{"jsonrpc": "2.0", "id": 1, "result": "OK"}""" private fun retryConfig( maxRetries: UInt = 2u, timeout: Duration = 8.seconds, // bellow 2s we may have flacky tests when running whole test suite in parallel - backoffDelay: Duration = 5.milliseconds + backoffDelay: Duration = 5.milliseconds, ) = RequestRetryConfig( maxRetries = maxRetries, timeout = timeout, - backoffDelay = backoffDelay + backoffDelay = backoffDelay, ) private fun createClientAndSetupWireMockServer( responseObjectMapper: ObjectMapper = defaultObjectMapper, requestObjectMapper: ObjectMapper = defaultObjectMapper, retryConfig: RequestRetryConfig = defaultRetryConfig, - shallRetryRequestsClientBasePredicate: Predicate> = Predicate { false } + shallRetryRequestsClientBasePredicate: Predicate> = Predicate { false }, ): JsonRpcV2Client { wiremock = WireMockServer(WireMockConfiguration.options().dynamicPort()) wiremock.start() @@ -94,7 +94,7 @@ class JsonRpcV2ClientImplTest { responseObjectMapper = responseObjectMapper, requestObjectMapper = requestObjectMapper, retryConfig = retryConfig, - shallRetryRequestsClientBasePredicate = shallRetryRequestsClientBasePredicate + shallRetryRequestsClientBasePredicate = shallRetryRequestsClientBasePredicate, ) } @@ -103,14 +103,14 @@ class JsonRpcV2ClientImplTest { responseObjectMapper: ObjectMapper = defaultObjectMapper, requestObjectMapper: ObjectMapper = defaultObjectMapper, retryConfig: RequestRetryConfig = defaultRetryConfig, - shallRetryRequestsClientBasePredicate: Predicate> = Predicate { false } + shallRetryRequestsClientBasePredicate: Predicate> = Predicate { false }, ): JsonRpcV2Client { return factory.createJsonRpcV2Client( endpoints = uris, retryConfig = retryConfig, requestObjectMapper = requestObjectMapper, responseObjectMapper = responseObjectMapper, - shallRetryRequestsClientBasePredicate = shallRetryRequestsClientBasePredicate + shallRetryRequestsClientBasePredicate = shallRetryRequestsClientBasePredicate, ) } @@ -139,7 +139,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = listOf("superUser", "Alice"), - resultMapper = { it } + resultMapper = { it }, ).get() assertThatJson(wiremock.jsonRequest()).isEqualTo( @@ -150,7 +150,7 @@ class JsonRpcV2ClientImplTest { "method": "someMethod", "params": ["superUser", "Alice"] } - """ + """, ) } @@ -161,7 +161,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = mapOf("superUser" to "Alice"), - resultMapper = { it } + resultMapper = { it }, ).get() assertThatJson(wiremock.jsonRequest()).isEqualTo( @@ -172,7 +172,7 @@ class JsonRpcV2ClientImplTest { "method": "someMethod", "params": {"superUser":"Alice"} } - """ + """, ) } @@ -180,7 +180,7 @@ class JsonRpcV2ClientImplTest { val name: String, val email: String, val address: ByteArray, - val value: ULong + val value: ULong, ) @Test @@ -190,7 +190,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = User(name = "John", email = "email@example.com", address = "0x01ffbb".decodeHex(), value = 987UL), - resultMapper = { it } + resultMapper = { it }, ).get() // 0x01ffbb -> "Af+7" in Base64, jackon's default encoding for ByteArray assertThatJson(wiremock.jsonRequest()).isEqualTo( @@ -201,7 +201,7 @@ class JsonRpcV2ClientImplTest { "method": "someMethod", "params": {"name":"John", "email":"email@example.com", "address":"Af+7", "value":987} } - """ + """, ) } @@ -214,7 +214,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = obj, - resultMapper = { it } + resultMapper = { it }, ).get() assertThatJson(wiremock.jsonRequest()).isEqualTo( @@ -225,7 +225,7 @@ class JsonRpcV2ClientImplTest { "method": "someMethod", "params": {"name":"John", "email":"email@example.com", "address":"Af+7", "value":987} } - """ + """, ) wiremock.stop() } @@ -237,7 +237,7 @@ class JsonRpcV2ClientImplTest { this.addSerializer(ULong::class.java, ULongToHexSerializer) this.addSerializer(Integer::class.java, JIntegerToHexSerializer) this.addSerializer(BigInteger::class.java, BigIntegerToHexSerializer) - } + }, ) createClientAndSetupWireMockServer(requestObjectMapper = objMapperWithNumbersAsHex).also { client -> @@ -245,7 +245,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = obj, - resultMapper = { it } + resultMapper = { it }, ).get() assertThatJson(wiremock.jsonRequest()).isEqualTo( @@ -256,7 +256,7 @@ class JsonRpcV2ClientImplTest { "method": "someMethod", "params": {"name":"John", "email":"email@example.com", "address":"0x01ffbb", "value": "0x3db"} } - """ + """, ) } } @@ -269,7 +269,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = listOf(index), - resultMapper = { it } + resultMapper = { it }, ) } SafeFuture.collectAll(requestsPromises.stream()).get() @@ -290,7 +290,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -305,7 +305,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -320,7 +320,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -335,7 +335,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -350,7 +350,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -362,13 +362,13 @@ class JsonRpcV2ClientImplTest { fun `when result is an Object, returns JsonNode`() { replyRequestWith( 200, - """{"jsonrpc": "2.0", "id": 1, "result": {"name": "Alice", "age": 23}}""" + """{"jsonrpc": "2.0", "id": 1, "result": {"name": "Alice", "age": 23}}""", ) client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -385,7 +385,7 @@ class JsonRpcV2ClientImplTest { client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } + resultMapper = { it }, ) .get() .also { response -> @@ -406,7 +406,7 @@ class JsonRpcV2ClientImplTest { resultMapper = { it as JsonNode SimpleUser(it.get("name").asText(), it.get("age").asInt()) - } + }, ) .get() .also { response -> @@ -419,7 +419,7 @@ class JsonRpcV2ClientImplTest { resultMapper = { it as JsonNode defaultObjectMapper.treeToValue(it, SimpleUser::class.java) - } + }, ) .get() .also { response -> @@ -442,15 +442,15 @@ class JsonRpcV2ClientImplTest { } } } - """.trimMargin() + """.trimMargin(), ) assertThat( client.makeRequest( method = "someMethod", params = emptyList(), - resultMapper = { it } - ) + resultMapper = { it }, + ), ).failsWithin(10.seconds.toJavaDuration()) .withThrowableThat() .isInstanceOfSatisfying(ExecutionException::class.java) { @@ -463,8 +463,8 @@ class JsonRpcV2ClientImplTest { "key1" to "value1", "key2" to 20, "key3" to listOf(1, 2, 3), - "key4" to null - ) + "key4" to null, + ), ) assertThat(cause.rpcErrorData).isEqualTo(expectedData) } @@ -473,7 +473,7 @@ class JsonRpcV2ClientImplTest { @Test fun `when it gets an error propagates to shallRetryRequestPredicate and retries while is true`() { createClientAndSetupWireMockServer( - retryConfig = retryConfig(maxRetries = 10u) + retryConfig = retryConfig(maxRetries = 10u), ).also { client -> val responses = listOf( 500 to "Internal Error", @@ -481,7 +481,7 @@ class JsonRpcV2ClientImplTest { 200 to """{"jsonrpc": "2.0", "id": 1, "error": {"code": -32602, "message": "Invalid params"}}""", 200 to """{"jsonrpc": "2.0", "id": 1, "result": null }""", 200 to """{"jsonrpc": "2.0", "id": 1, "result": "some result" }""", - 200 to """{"jsonrpc": "2.0", "id": 1, "result": "expected result" }""" + 200 to """{"jsonrpc": "2.0", "id": 1, "result": "expected result" }""", ) replyRequestsWith(responses = responses) val retryPredicateCalls = mutableListOf>() @@ -496,7 +496,7 @@ class JsonRpcV2ClientImplTest { resultMapper = { it as String? it?.uppercase() - } + }, ).get() assertThat(wiremock.serveEvents.serveEvents).hasSize(responses.size) @@ -523,7 +523,7 @@ class JsonRpcV2ClientImplTest { @Test fun `when it has connection error propagates to shallRetryRequestPredicate and retries while is true`() { createClientAndSetupWireMockServer( - retryConfig = retryConfig(maxRetries = 10u) + retryConfig = retryConfig(maxRetries = 10u), ).also { client -> // stop the server to simulate connection error wiremock.stop() @@ -537,7 +537,7 @@ class JsonRpcV2ClientImplTest { retryPredicateCalls.add(it) retryPredicateCalls.size < 2 }, - resultMapper = { it as String? } + resultMapper = { it as String? }, ) assertThatThrownBy { reqFuture.get() } @@ -559,7 +559,7 @@ class JsonRpcV2ClientImplTest { fun `when it has connection error propagates to shallRetryRequestPredicate and retries until retry config elapses`() { createClient( uris = listOf(URI.create("http://127.0.0.1:19472")), - retryConfig = retryConfig(maxRetries = 2u, timeout = 8.seconds, backoffDelay = 5.milliseconds) + retryConfig = retryConfig(maxRetries = 2u, timeout = 8.seconds, backoffDelay = 5.milliseconds), ).also { client -> val retryPredicateCalls = mutableListOf>() @@ -570,7 +570,7 @@ class JsonRpcV2ClientImplTest { retryPredicateCalls.add(it) true // keep retrying }, - resultMapper = { it as String? } + resultMapper = { it as String? }, ) assertThatThrownBy { reqFuture.get() } @@ -595,9 +595,9 @@ class JsonRpcV2ClientImplTest { retryConfig = RequestRetryConfig( maxRetries = 10u, timeout = 5.minutes, - backoffDelay = 1.milliseconds + backoffDelay = 1.milliseconds, ), - shallRetryRequestsClientBasePredicate = baseRetryPredicate + shallRetryRequestsClientBasePredicate = baseRetryPredicate, ).also { client -> replyRequestsWith( listOf( @@ -607,8 +607,8 @@ class JsonRpcV2ClientImplTest { 200 to """{"jsonrpc": "2.0", "id": 1, "result": "retry_b_3" }""", 200 to """{"jsonrpc": "2.0", "id": 1, "result": "retry_b_4" }""", 200 to """{"jsonrpc": "2.0", "id": 1, "result": "retry_b_5" }""", - 200 to """{"jsonrpc": "2.0", "id": 1, "result": "some_result" }""" - ) + 200 to """{"jsonrpc": "2.0", "id": 1, "result": "some_result" }""", + ), ) val retryPredicateCalls = mutableListOf>() val reqFuture = client.makeRequest( @@ -618,7 +618,7 @@ class JsonRpcV2ClientImplTest { retryPredicateCalls.add(it) it.getOr("").startsWith("retry_b") }, - resultMapper = { it as String } + resultMapper = { it as String }, ) assertThat(reqFuture.get()).isEqualTo("some_result") @@ -630,8 +630,8 @@ class JsonRpcV2ClientImplTest { "retry_b_3", "retry_b_4", "retry_b_5", - "some_result" - ) + "some_result", + ), ) } } @@ -643,8 +643,8 @@ class JsonRpcV2ClientImplTest { .willReturn( status(statusCode) .withHeader("Content-type", "text/plain") - .apply { if (body != null) withBody(body) } - ) + .apply { if (body != null) withBody(body) }, + ), ) } @@ -658,9 +658,9 @@ class JsonRpcV2ClientImplTest { .willReturn( status(firstResponseStatus) .withHeader("Content-type", "text/plain") - .apply { if (firstResponseBody != null) withBody(firstResponseBody) } + .apply { if (firstResponseBody != null) withBody(firstResponseBody) }, ) - .willSetStateTo("req_0") + .willSetStateTo("req_0"), ) responses @@ -674,9 +674,9 @@ class JsonRpcV2ClientImplTest { .willReturn( status(statusCode) .withHeader("Content-type", "text/plain") - .apply { if (body != null) withBody(body) } + .apply { if (body != null) withBody(body) }, ) - .willSetStateTo("req_${index + 1}") + .willSetStateTo("req_${index + 1}"), ) } } diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClientTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClientTest.kt index 61084c86..db1bd59e 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClientTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/LoadBalancingJsonRpcClientTest.kt @@ -36,7 +36,7 @@ class LoadBalancingJsonRpcClientTest { private val requestId: AtomicInteger = AtomicInteger(0) private fun rpcRequest( method: String = "eth_blockNumber", - params: List = emptyList() + params: List = emptyList(), ): JsonRpcRequestListParams = JsonRpcRequestListParams("2.0", requestId.incrementAndGet(), method, params) @BeforeEach @@ -123,7 +123,7 @@ class LoadBalancingJsonRpcClientTest { numberOfRpcClients, maxInflightRequestsPerRpcClient, numberOfThreads, - numberOfRequestPerThread + numberOfRequestPerThread, ) } @@ -137,7 +137,7 @@ class LoadBalancingJsonRpcClientTest { numberOfRpcClients, maxInflightRequestsPerRpcClient, numberOfThreads, - numberOfRequestPerThread + numberOfRequestPerThread, ) } @@ -151,7 +151,7 @@ class LoadBalancingJsonRpcClientTest { numberOfRpcClients, maxInflightRequestsPerRpcClient, numberOfThreads, - numberOfRequestPerThread + numberOfRequestPerThread, ) } @@ -159,7 +159,7 @@ class LoadBalancingJsonRpcClientTest { numberOfRpcClients: Int, maxInflightRequestsPerRpcClient: UInt, numberOfThreads: Int, - numberOfRequestPerThread: Int + numberOfRequestPerThread: Int, ) { val executor = Executors.newCachedThreadPool() val producersStartBarrier = CyclicBarrier(numberOfThreads + 1) @@ -175,7 +175,7 @@ class LoadBalancingJsonRpcClientTest { loadBalancer, numberOfRequestPerThread, producersStartBarrier, - receivedResponsesLatch + receivedResponsesLatch, ) } for (t in 1..numberOfThreads) { @@ -195,7 +195,7 @@ class LoadBalancingJsonRpcClientTest { val loadBalancer: LoadBalancingJsonRpcClient, val numberOfRequests: Int, val startBarrier: CyclicBarrier, - val responsesReceivedLatch: CountDownLatch + val responsesReceivedLatch: CountDownLatch, ) : Runnable { private var responsesHandledAtomic = AtomicInteger(0) fun responsesHandled(): Int = responsesHandledAtomic.get() @@ -209,7 +209,7 @@ class LoadBalancingJsonRpcClientTest { val requestId = "${id}_$req" loadBalancer .makeRequest( - JsonRpcRequestListParams("2.0", requestId, "sleepMs", listOf(responseDelay, shallFail)) + JsonRpcRequestListParams("2.0", requestId, "sleepMs", listOf(responseDelay, shallFail)), ) .map { if (futureHandlerShallThrow) { @@ -230,7 +230,7 @@ class LoadBalancingJsonRpcClientTest { private class FakeJsonRpcClient(val id: Int) : JsonRpcClient { override fun makeRequest( request: JsonRpcRequest, - resultMapper: (Any?) -> Any? + resultMapper: (Any?) -> Any?, ): Future> { val promise = Promise.promise>() val paramsList = request.params as List<*> @@ -255,7 +255,7 @@ class LoadBalancingJsonRpcClientTest { private fun JsonRpcClient.replyWithDelay( delayInMilliseconds: Long, - result: Result + result: Result, ): Promise> { val promise = Promise.promise>() val answer: Answer>> = Answer { diff --git a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientTest.kt b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientTest.kt index b1a34520..cc4a5ac9 100644 --- a/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientTest.kt +++ b/jvm-libs/generic/json-rpc/src/test/kotlin/net/consensys/linea/jsonrpc/client/VertxHttpJsonRpcClientTest.kt @@ -87,7 +87,7 @@ class VertxHttpJsonRpcClientTest { JsonObject() .put("name", "Alice") .put("email", "alice@wonderland.io") - .put("address", "0xaabbccdd".decodeHex()) + .put("address", "0xaabbccdd".decodeHex()), ) client.makeRequest(JsonRpcRequestListParams("2.0", 1, "addUser", params)).get() @@ -115,9 +115,9 @@ class VertxHttpJsonRpcClientTest { EqualToJsonPattern( expectedJsonBody, /*ignoreArrayOrder*/ false, /*ignoreExtraElements*/ - false - ) - ) + false, + ), + ), ) } @@ -157,7 +157,7 @@ class VertxHttpJsonRpcClientTest { JsonObject() .put("jsonrpc", "2.0") .put("id", "1") - .put("result", JsonObject().put("odd", 23).put("even", 10)) + .put("result", JsonObject().put("odd", 23).put("even", 10)), ) client @@ -172,7 +172,7 @@ class VertxHttpJsonRpcClientTest { client .makeRequest( request = JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList()), - resultMapper = ::toPrimitiveOrJacksonJsonNode + resultMapper = ::toPrimitiveOrJacksonJsonNode, ) .get() .also { response -> @@ -191,7 +191,7 @@ class VertxHttpJsonRpcClientTest { |"id": "1", |"result": ["a", 2, "c", 4] |} - """.trimMargin() + """.trimMargin(), ) client @@ -206,7 +206,7 @@ class VertxHttpJsonRpcClientTest { client .makeRequest( request = JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList()), - resultMapper = ::toPrimitiveOrJacksonJsonNode + resultMapper = ::toPrimitiveOrJacksonJsonNode, ) .get() .also { response -> @@ -219,7 +219,7 @@ class VertxHttpJsonRpcClientTest { @Test fun makesRequest_successWithMapper() { replyRequestWith( - JsonObject().put("jsonrpc", "2.0").put("id", "1").put("result", "some_random_value") + JsonObject().put("jsonrpc", "2.0").put("id", "1").put("result", "some_random_value"), ) val resultMapper = { value: Any? -> (value as String).uppercase() } @@ -242,8 +242,8 @@ class VertxHttpJsonRpcClientTest { JsonObject() .put("code", -32602) .put("message", "Invalid params") - .put("data", JsonObject().put("k", "v")) - ) + .put("data", JsonObject().put("k", "v")), + ), ) val response = client.makeRequest(JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList())).get() @@ -253,9 +253,9 @@ class VertxHttpJsonRpcClientTest { Err( JsonRpcErrorResponse( "1", - JsonRpcError(-32602, "Invalid params", mapOf("k" to "v")) - ) - ) + JsonRpcError(-32602, "Invalid params", mapOf("k" to "v")), + ), + ), ) } @@ -264,7 +264,7 @@ class VertxHttpJsonRpcClientTest { replyRequestWith( JsonObject() .put("jsonrpc", "2.0") - .put("error", JsonObject().put("code", -32602).put("message", "Parse Error")) + .put("error", JsonObject().put("code", -32602).put("message", "Parse Error")), ) val response = client.makeRequest(JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList())).get() @@ -277,18 +277,18 @@ class VertxHttpJsonRpcClientTest { @Timeout(15, unit = TimeUnit.SECONDS) fun makesRequest_malFormattedJsonResponse() { replyRequestWith( - JsonObject().put("jsonrpc", "2.0").put("id", "1").put("nonsense", "some_random_value") + JsonObject().put("jsonrpc", "2.0").put("id", "1").put("nonsense", "some_random_value"), ) assertThat( client .makeRequest(JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList())) - .toSafeFuture() + .toSafeFuture(), ) .failsWithin(Duration.ofSeconds(14)) .withThrowableOfType(ExecutionException::class.java) .withMessage( - "java.lang.IllegalArgumentException: Invalid JSON-RPC response without result or error" + "java.lang.IllegalArgumentException: Invalid JSON-RPC response without result or error", ) } @@ -301,7 +301,7 @@ class VertxHttpJsonRpcClientTest { vertx.createHttpClient(clientOptions), endpoint, metricsFacade, - log = log + log = log, ) val request = JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList()) @@ -316,7 +316,7 @@ class VertxHttpJsonRpcClientTest { eq(endpoint), eq(JsonObject.mapFrom(request).encode()), any(), - any() + any(), ) } @@ -329,7 +329,7 @@ class VertxHttpJsonRpcClientTest { vertx.createHttpClient(clientOptions), endpoint, metricsFacade, - log = log + log = log, ) val request = JsonRpcRequestListParams("2.0", 1, "randomNumbers", emptyList()) @@ -344,7 +344,7 @@ class VertxHttpJsonRpcClientTest { eq(endpoint), eq(JsonObject.mapFrom(request).encode()), any(), - any() + any(), ) } @@ -360,7 +360,7 @@ class VertxHttpJsonRpcClientTest { val timer = meterRegistry.timer( "jsonrpc.request", - listOf(Tag.of("method", "randomNumber"), Tag.of("endpoint", "localhost")) + listOf(Tag.of("method", "randomNumber"), Tag.of("endpoint", "localhost")), ) assertThat(timer).isNotNull @@ -378,8 +378,8 @@ class VertxHttpJsonRpcClientTest { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(jsonRpcResponse.toString()) - ) + .withBody(jsonRpcResponse.toString()), + ), ) } @@ -390,8 +390,8 @@ class VertxHttpJsonRpcClientTest { .willReturn( status(statusCode) .withHeader("Content-type", "text/plain") - .apply { if (body != null) withBody(body) } - ) + .apply { if (body != null) withBody(body) }, + ), ) } } diff --git a/jvm-libs/generic/json-rpc/src/testFixtures/kotlin/linea/jsonrpc/TestingJsonRpcServer.kt b/jvm-libs/generic/json-rpc/src/testFixtures/kotlin/linea/jsonrpc/TestingJsonRpcServer.kt index 642b6430..6ed1d98e 100644 --- a/jvm-libs/generic/json-rpc/src/testFixtures/kotlin/linea/jsonrpc/TestingJsonRpcServer.kt +++ b/jvm-libs/generic/json-rpc/src/testFixtures/kotlin/linea/jsonrpc/TestingJsonRpcServer.kt @@ -36,7 +36,7 @@ open class TestingJsonRpcServer( loggerName: String = serverName, val vertx: Vertx = Vertx.vertx(), val responseObjectMapper: ObjectMapper = jacksonObjectMapper(), - responsesArtificialDelay: Duration? = null + responsesArtificialDelay: Duration? = null, ) { val log: Logger = LogManager.getLogger(loggerName) private var httpServer: HttpJsonRpcServer = createHttpServer(port) @@ -45,7 +45,7 @@ open class TestingJsonRpcServer( private var verticleId: String? = null private val handlers: MutableMap Any?> = ConcurrentHashMap() private var requests: MutableList< - Pair>> + Pair>>, > = mutableListOf() var responsesArtificialDelay: Duration? = responsesArtificialDelay @@ -63,10 +63,10 @@ open class TestingJsonRpcServer( requestsHandler = this::handleRequest, metricsFacade = MicrometerMetricsFacade(registry = SimpleMeterRegistry()), log = log, - responseResultObjectMapper = responseObjectMapper - ) + responseResultObjectMapper = responseObjectMapper, + ), ), - serverName = serverName + serverName = serverName, ) } @@ -100,7 +100,7 @@ open class TestingJsonRpcServer( private fun handleRequest( user: User?, jsonRpcRequest: JsonRpcRequest, - requestJson: JsonObject + requestJson: JsonObject, ): Future> { // need this otherwise kotlin compiler/IDE struggle to infer the type val result: Future> = ( @@ -112,9 +112,9 @@ open class TestingJsonRpcServer( Ok( JsonRpcSuccessResponse( request = jsonRpcRequest, - result = result - ) - ) + result = result, + ), + ), ) } catch (e: JsonRpcErrorResponseException) { Future.succeededFuture(Err(JsonRpcErrorResponse(jsonRpcRequest.id, e.asJsonRpcError()))) @@ -141,7 +141,7 @@ open class TestingJsonRpcServer( */ fun handle( method: String, - methodHandler: (jsonRpcRequest: JsonRpcRequest) -> Any? + methodHandler: (jsonRpcRequest: JsonRpcRequest) -> Any?, ) { handlers[method] = methodHandler } @@ -169,7 +169,10 @@ open class TestingJsonRpcServer( private fun SafeFuture.delayed(delay: Duration): SafeFuture { val promise = SafeFuture() vertx.setTimer(delay.inWholeMilliseconds) { - this.thenAccept(promise::complete).exceptionally { promise.completeExceptionally(it); null } + this.thenAccept(promise::complete).exceptionally { + promise.completeExceptionally(it) + null + } } return promise } diff --git a/jvm-libs/generic/logging/src/main/kotlin/linea/log4j/Configuration.kt b/jvm-libs/generic/logging/src/main/kotlin/linea/log4j/Configuration.kt index 200ef448..9548cc4b 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/linea/log4j/Configuration.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/linea/log4j/Configuration.kt @@ -5,7 +5,7 @@ import org.apache.logging.log4j.core.config.Configurator fun configureLoggers( rootLevel: Level = Level.INFO, - vararg loggerConfigs: Pair + vararg loggerConfigs: Pair, ) { Configurator.setRootLevel(rootLevel) loggerConfigs.forEach { (loggerName, level) -> diff --git a/jvm-libs/generic/logging/src/main/kotlin/linea/logging/TimeMeasureLogger.kt b/jvm-libs/generic/logging/src/main/kotlin/linea/logging/TimeMeasureLogger.kt index 72ddf85d..25abe183 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/linea/logging/TimeMeasureLogger.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/linea/logging/TimeMeasureLogger.kt @@ -12,7 +12,7 @@ fun measureTimeAndLog( logger: Logger, logLevel: Level = Level.DEBUG, logMessageProvider: (duration: kotlin.time.Duration, result: T) -> String, - action: () -> T + action: () -> T, ): T { var value: T val duration = measureTime { @@ -26,12 +26,12 @@ fun measureTimeAndLog( class MeasureLogger( private val logger: Logger, - private val logLevel: Level = Level.DEBUG + private val logLevel: Level = Level.DEBUG, ) { fun measureTimeAndLog( logLevel: Level = this.logLevel, logMessageProvider: (duration: kotlin.time.Duration, result: T) -> String, - action: () -> T + action: () -> T, ): T { return measureTimeAndLog(logger, logLevel, logMessageProvider, action) } diff --git a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/DebouncingFilter.kt b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/DebouncingFilter.kt index ee10d81c..c1a240f0 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/DebouncingFilter.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/DebouncingFilter.kt @@ -13,13 +13,13 @@ import kotlin.time.Duration.Companion.seconds data class LogCacheKey( val message: String, - val logLevel: Level + val logLevel: Level, ) @Plugin(name = "DebouncingFilter", category = "Core", elementType = "filter") class DebouncingFilter internal constructor( private val debounceTime: Duration = 30.seconds, - private val maxCacheCapacity: Int = 1000 + private val maxCacheCapacity: Int = 1000, ) : AbstractFilter() { private val logTimesCache = run { // Source: https://stackoverflow.com/questions/15844035/best-hashmap-initial-capacity-while-indexing-a-list @@ -48,11 +48,11 @@ class DebouncingFilter internal constructor( @JvmStatic fun createFilter( @PluginAttribute(value = "debounceTimeMillis", defaultLong = 30000L) debounceTimeMillis: Long, - @PluginAttribute(value = "maxCacheCapacity", defaultInt = 1000) maxCacheCapacity: Int + @PluginAttribute(value = "maxCacheCapacity", defaultInt = 1000) maxCacheCapacity: Int, ): DebouncingFilter { return DebouncingFilter( debounceTime = debounceTimeMillis.milliseconds, - maxCacheCapacity = maxCacheCapacity + maxCacheCapacity = maxCacheCapacity, ) } } diff --git a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/JsonRpcRequestResponseLogger.kt b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/JsonRpcRequestResponseLogger.kt index f761174c..92abd44f 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/JsonRpcRequestResponseLogger.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/JsonRpcRequestResponseLogger.kt @@ -10,7 +10,7 @@ interface JsonRpcRequestResponseLogger { responseStatusCode: Int?, requestBody: String, responseBody: String, - failureCause: Throwable? = null + failureCause: Throwable? = null, ) fun isJsonRpcError(responseStatusCode: Int?, responseBody: String?): Boolean { @@ -22,7 +22,7 @@ class MinimalInLineJsonRpcLogger( val logger: Logger, val requestResponseLogLevel: Level = Level.DEBUG, val failuresLogLevel: Level = Level.WARN, - val maskEndpoint: LogFieldMask = ::noopMask + val maskEndpoint: LogFieldMask = ::noopMask, ) : JsonRpcRequestResponseLogger { private fun logRequestOnLevel(level: Level, endpoint: String, jsonBody: String, throwable: Throwable?) { @@ -42,7 +42,7 @@ class MinimalInLineJsonRpcLogger( responseStatusCode: Int?, requestBody: String, responseBody: String, - failureCause: Throwable? + failureCause: Throwable?, ) { val isError = failureCause != null || isJsonRpcError(responseStatusCode, responseBody) val logLevel = if (isError) failuresLogLevel else requestResponseLogLevel @@ -59,7 +59,7 @@ class MinimalInLineJsonRpcLogger( "<-- {} {} {}", maskedEndpoint, responseStatusCode, - responseBody + responseBody, ) } else { logger.log( @@ -68,7 +68,7 @@ class MinimalInLineJsonRpcLogger( maskedEndpoint, responseStatusCode, responseBody, - failureCause.message + failureCause.message, ) } } diff --git a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/KnownErrors.kt b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/KnownErrors.kt index 131827b8..898ac29f 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/KnownErrors.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/KnownErrors.kt @@ -5,11 +5,11 @@ import org.apache.logging.log4j.Level data class KnownError( val logLevel: Level, val message: Regex, - val stackTrace: Boolean = false + val stackTrace: Boolean = false, ) class KnownErrors( - private val knownErrors: List + private val knownErrors: List, ) { fun find(errorMessage: String): KnownError? { return knownErrors.firstOrNull { errorMessage.matches(it.message) } diff --git a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/Log4jLineaRewriter.kt b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/Log4jLineaRewriter.kt index 40f3225f..aa7fb87e 100644 --- a/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/Log4jLineaRewriter.kt +++ b/jvm-libs/generic/logging/src/main/kotlin/net/consensys/linea/logging/Log4jLineaRewriter.kt @@ -11,21 +11,21 @@ import org.apache.logging.log4j.core.impl.Log4jLogEvent @Plugin(name = "Log4jLineaRewriter", category = "Core", elementType = "rewritePolicy", printObject = true) class Log4jLineaRewriter( - private val knownErrors: KnownErrors + private val knownErrors: KnownErrors, ) : RewritePolicy { companion object { @PluginFactory @JvmStatic fun createPolicy( @PluginElement(value = "knownErrors") - knownErrorsConfig: KnownErrorsConfig + knownErrorsConfig: KnownErrorsConfig, ): Log4jLineaRewriter { return Log4jLineaRewriter( KnownErrors( knownErrorsConfig.knownErrors.toList().map { KnownError(Level.getLevel(it.logLevel), it.messagePattern.toRegex(RegexOption.IGNORE_CASE), it.stackTrace) - } - ) + }, + ), ) } } @@ -62,7 +62,7 @@ class KnownErrorsConfig(val knownErrors: Array) { @JvmStatic fun createKnownErrorsConfig( @PluginElement("KnownError") - knownErrors: Array + knownErrors: Array, ): KnownErrorsConfig { return KnownErrorsConfig(knownErrors) } @@ -73,7 +73,7 @@ class KnownErrorsConfig(val knownErrors: Array) { class KnownErrorConfig( val logLevel: String, val messagePattern: String, - val stackTrace: Boolean = false + val stackTrace: Boolean = false, ) { companion object { @PluginFactory @@ -81,12 +81,12 @@ class KnownErrorConfig( fun createKnownErrorConfig( @PluginAttribute("logLevel") logLevel: String, @PluginAttribute("message") message: String, - @PluginAttribute("stackTrace") stackTrace: Boolean? + @PluginAttribute("stackTrace") stackTrace: Boolean?, ): KnownErrorConfig { return KnownErrorConfig( logLevel = logLevel, messagePattern = message, - stackTrace = stackTrace ?: false + stackTrace = stackTrace ?: false, ) } } diff --git a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/DebouncingFilterTest.kt b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/DebouncingFilterTest.kt index 1b860b7f..0a17c24e 100644 --- a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/DebouncingFilterTest.kt +++ b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/DebouncingFilterTest.kt @@ -19,7 +19,7 @@ class DebouncingFilterTest { fun beforeEach() { debouncer = DebouncingFilter( debounceTime = debounceTime, - maxCacheCapacity = 3 + maxCacheCapacity = 3, ) } @@ -44,13 +44,13 @@ class DebouncingFilterTest { val initialMessageTime = 12L assertThat( debouncer.filter( - eventsBuilder.setTimeMillis(initialMessageTime).build() - ) + eventsBuilder.setTimeMillis(initialMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) assertThat( debouncer.filter( - eventsBuilder.setTimeMillis(initialMessageTime + debounceTime.inWholeMilliseconds + 1).build() - ) + eventsBuilder.setTimeMillis(initialMessageTime + debounceTime.inWholeMilliseconds + 1).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) } @@ -76,34 +76,34 @@ class DebouncingFilterTest { val theSameMessageTime = 12L assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 1").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 1").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 2").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 2").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 3").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 3").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 3").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 3").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.DENY) // Message 4 pushes Message 1 out of the LRU cache assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 4").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 4").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) assertThat( debouncer.filter( - createLogEventBuilderWithString("Message 1").setTimeMillis(theSameMessageTime).build() - ) + createLogEventBuilderWithString("Message 1").setTimeMillis(theSameMessageTime).build(), + ), ).isEqualTo(Filter.Result.ACCEPT) } diff --git a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/Log4JLineaAppenderTest.kt b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/Log4JLineaAppenderTest.kt index a62c4e6b..5eb67df6 100644 --- a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/Log4JLineaAppenderTest.kt +++ b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/Log4JLineaAppenderTest.kt @@ -55,7 +55,7 @@ class Log4JLineaAppenderTest { logger.error( "errorMessage={}", exception.message, - exception + exception, ) val logEvent = listAppender.events.last() @@ -72,7 +72,7 @@ class Log4JLineaAppenderTest { logger.error( "errorMessage={}", exception.message, - exception + exception, ) val logEvent = listAppender.events.last() @@ -90,7 +90,7 @@ class Log4JLineaAppenderTest { logger.error( "errorMessage={}", exception.message, - exception + exception, ) val logEvent = listAppender.events.last() @@ -102,7 +102,7 @@ class Log4JLineaAppenderTest { @Test fun `if error is eth_call log level is rewritten`() { logger.error( - "eth_call for aggregation finalization failed Contract Call has been reverted by the EVM with the reason" + "eth_call for aggregation finalization failed Contract Call has been reverted by the EVM with the reason", ) val logEvent = listAppender.events.last() @@ -112,7 +112,7 @@ class Log4JLineaAppenderTest { @Test fun `if error is not an eth_call log level remains at ERROR level`() { logger.error( - "aggregation finalization failed Contract Call has been reverted by the EVM with the reason" + "aggregation finalization failed Contract Call has been reverted by the EVM with the reason", ) val logEvent = listAppender.events.last() diff --git a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/MinimalInLineJsonRpcLoggerTest.kt b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/MinimalInLineJsonRpcLoggerTest.kt index dc3dd24b..4d166d9b 100644 --- a/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/MinimalInLineJsonRpcLoggerTest.kt +++ b/jvm-libs/generic/logging/src/test/kotlin/net/consensys/linea/logging/MinimalInLineJsonRpcLoggerTest.kt @@ -27,7 +27,7 @@ class MinimalInLineJsonRpcLoggerTest { minimalInLineJsonRpcLogger = MinimalInLineJsonRpcLogger( logger, requestResponseLogLevel = Level.DEBUG, - failuresLogLevel = Level.WARN + failuresLogLevel = Level.WARN, ) whenever(logger.level).thenReturn(Level.INFO) } @@ -50,7 +50,7 @@ class MinimalInLineJsonRpcLoggerTest { eq("testEndpoint"), eq(jsonRequestBody), eq("Http client error"), - eq(error) + eq(error), ) } @@ -63,7 +63,7 @@ class MinimalInLineJsonRpcLoggerTest { eq("<-- {} {} {}"), eq("testEndpoint"), eq(200), - eq(jsonSuccessResponse) + eq(jsonSuccessResponse), ) } @@ -79,7 +79,7 @@ class MinimalInLineJsonRpcLoggerTest { eq("testEndpoint"), eq(500), eq(jsonErrorResponse), - eq("Test exception") + eq("Test exception"), ) } @@ -89,7 +89,7 @@ class MinimalInLineJsonRpcLoggerTest { minimalInLineJsonRpcLogger = MinimalInLineJsonRpcLogger( logger, requestResponseLogLevel = Level.DEBUG, - failuresLogLevel = Level.WARN + failuresLogLevel = Level.WARN, ) whenever(logger.level).thenReturn(Level.DEBUG) minimalInLineJsonRpcLogger.logResponse("testEndpoint", 500, jsonRequestBody, jsonErrorResponse, exception) @@ -100,7 +100,7 @@ class MinimalInLineJsonRpcLoggerTest { eq("testEndpoint"), eq(jsonRequestBody), anyOrNull(), - anyOrNull() + anyOrNull(), ) verify(logger).log( eq(Level.WARN), @@ -108,7 +108,7 @@ class MinimalInLineJsonRpcLoggerTest { eq("testEndpoint"), eq(500), eq(jsonErrorResponse), - eq("Test exception") + eq("Test exception"), ) } diff --git a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/Db.kt b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/Db.kt index 1cbe4fdc..cb109613 100644 --- a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/Db.kt +++ b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/Db.kt @@ -28,7 +28,7 @@ object Db { target: String, username: String, password: String, - migrationLocations: String = "classpath:db/" + migrationLocations: String = "classpath:db/", ) { val dataSource = PGSimpleDataSource().apply { @@ -49,7 +49,7 @@ object Db { fun applyDbMigrations( dataSource: DataSource, target: String, - migrationLocations: String = "classpath:db/" + migrationLocations: String = "classpath:db/", ) { LOG.info("Migrating coordinator database") Flyway.configure() @@ -82,7 +82,7 @@ object Db { database: String, username: String, password: String, - maxPoolSize: Int = DEFAULT_VERTX_CONNECTION_POOL_MAX_SIZE + maxPoolSize: Int = DEFAULT_VERTX_CONNECTION_POOL_MAX_SIZE, ): Pool { val connectOptions = PgConnectOptions() @@ -119,7 +119,7 @@ object Db { username: String, password: String, maxPoolSize: Int = DEFAULT_VERTX_CONNECTION_POOL_MAX_SIZE, - pipeliningLimit: Int = PgConnectOptions.DEFAULT_PIPELINING_LIMIT + pipeliningLimit: Int = PgConnectOptions.DEFAULT_PIPELINING_LIMIT, ): SqlClient { val connectOptions = PgConnectOptions() diff --git a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/DbHelper.kt b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/DbHelper.kt index 8e38fd76..551962ba 100644 --- a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/DbHelper.kt +++ b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/DbHelper.kt @@ -13,7 +13,7 @@ object DbHelper { fun generateUniqueDbName( prefix: String = "test", - clock: Clock = Clock.systemUTC() + clock: Clock = Clock.systemUTC(), ): String { // Just time is not enough, as we can have multiple tests running in parallel val dateStr = formatter.format(clock.instant().atZone(ZoneId.of("UTC"))) @@ -56,7 +56,7 @@ object DbHelper { fun createDataBase( dataSource: DataSource, - databaseName: String + databaseName: String, ) { dataSource.connection .use { con -> con.prepareStatement("CREATE DATABASE $databaseName;").execute() } @@ -64,13 +64,13 @@ object DbHelper { fun dropAndCreateDataBase( dataSource: DataSource, - databaseName: String + databaseName: String, ) { resetAllConnections(dataSource, databaseName) dataSource.connection .use { con -> con.prepareStatement( - "DROP DATABASE IF EXISTS $databaseName; CREATE DATABASE $databaseName;" + "DROP DATABASE IF EXISTS $databaseName; CREATE DATABASE $databaseName;", ).execute() } } diff --git a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryer.kt b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryer.kt index c9386d4f..34548421 100644 --- a/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryer.kt +++ b/jvm-libs/generic/persistence/db/src/main/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryer.kt @@ -10,12 +10,12 @@ import kotlin.time.Duration open class PersistenceRetryer( private val vertx: Vertx, private val config: Config, - private val log: Logger = LogManager.getLogger(PersistenceRetryer::class.java) + private val log: Logger = LogManager.getLogger(PersistenceRetryer::class.java), ) { data class Config( val backoffDelay: Duration, val maxRetries: Int? = null, - val timeout: Duration? = null + val timeout: Duration? = null, ) fun retryQuery( @@ -25,16 +25,16 @@ open class PersistenceRetryer( when { isDuplicateKeyException(error) -> log.info( "Persistence errorMessage={}", - error.message + error.message, ) else -> log.info( "Persistence errorMessage={}, it will retry again in {}", error.message, config.backoffDelay, - error + error, ) } - } + }, ): SafeFuture { return AsyncRetryer.retry( vertx = vertx, @@ -43,7 +43,7 @@ open class PersistenceRetryer( maxRetries = config.maxRetries, stopRetriesOnErrorPredicate = stopRetriesOnErrorPredicate, exceptionConsumer = exceptionConsumer, - action = action + action = action, ) } diff --git a/jvm-libs/generic/persistence/db/src/test/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryerTest.kt b/jvm-libs/generic/persistence/db/src/test/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryerTest.kt index 4cccd207..2f6957ab 100644 --- a/jvm-libs/generic/persistence/db/src/test/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryerTest.kt +++ b/jvm-libs/generic/persistence/db/src/test/kotlin/net/consensys/zkevm/persistence/db/PersistenceRetryerTest.kt @@ -25,8 +25,8 @@ class PersistenceRetryerTest { PersistenceRetryer.Config( backoffDelay = 10.milliseconds, maxRetries = 5, - timeout = 2.seconds - ) + timeout = 2.seconds, + ), ) } @@ -41,8 +41,8 @@ class PersistenceRetryerTest { } else { SafeFuture.completedFuture("success") } - } - ) + }, + ), ).succeedsWithin(1.seconds.toJavaDuration()) .isEqualTo("success") assertThat(callCounter.get()).isEqualTo(2) @@ -57,13 +57,18 @@ class PersistenceRetryerTest { action = { if (callCounter.incrementAndGet() < 20) { SafeFuture.failedFuture( - PgException("duplicate key value violates unique constraint", "some-severity", "some-code", "some-detail") + PgException( + "duplicate key value violates unique constraint", + "some-severity", + "some-code", + "some-detail", + ), ) } else { SafeFuture.completedFuture("success") } - } - ) + }, + ), ).isCompletedExceptionally .isNotCancelled .failsWithin(2.seconds.toJavaDuration()) diff --git a/jvm-libs/generic/serialization/jackson/src/main/kotlin/build/linea/s11n/jackson/ObjectMappers.kt b/jvm-libs/generic/serialization/jackson/src/main/kotlin/build/linea/s11n/jackson/ObjectMappers.kt index dcd093ab..97bfdd87 100644 --- a/jvm-libs/generic/serialization/jackson/src/main/kotlin/build/linea/s11n/jackson/ObjectMappers.kt +++ b/jvm-libs/generic/serialization/jackson/src/main/kotlin/build/linea/s11n/jackson/ObjectMappers.kt @@ -32,5 +32,5 @@ val ethByteAsHexDeserialisersModule = SimpleModule().apply { val ethApiObjectMapper: ObjectMapper = jacksonObjectMapper() .registerModules( ethNumberAsHexSerialisersModule, - ethByteAsHexSerialisersModule + ethByteAsHexSerialisersModule, ) diff --git a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/BytesSerDeTest.kt b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/BytesSerDeTest.kt index 86d405f2..9e9bbc9a 100644 --- a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/BytesSerDeTest.kt +++ b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/BytesSerDeTest.kt @@ -46,7 +46,7 @@ class BytesSerDeTest { nullByte = null, someByte = 0xaf.toByte(), minByte = Byte.MIN_VALUE, - maxByte = Byte.MAX_VALUE + maxByte = Byte.MAX_VALUE, ) @BeforeEach @@ -78,7 +78,7 @@ class BytesSerDeTest { val nullByte: Byte?, val someByte: Byte, val minByte: Byte, - val maxByte: Byte + val maxByte: Byte, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantAsHexNumberSerDeTest.kt b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantAsHexNumberSerDeTest.kt index 16b702b9..208cf83d 100644 --- a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantAsHexNumberSerDeTest.kt +++ b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantAsHexNumberSerDeTest.kt @@ -18,7 +18,7 @@ class InstantAsHexNumberSerDeTest { SimpleModule().apply { this.addSerializer(Instant::class.java, InstantAsHexNumberSerializer) this.addDeserializer(Instant::class.java, InstantAsHexNumberDeserializer) - } + }, ) } @@ -34,7 +34,7 @@ class InstantAsHexNumberSerDeTest { // 2021-01-02T09:00:45+01:30 UTC+01:30, val instantUTCPlus: Instant = Instant.fromEpochSeconds(1609572645), // 2021-01-02T09:00:45-01:30" UTC-01:30 - val instantUTCMinus: Instant = Instant.fromEpochSeconds(1609583445) + val instantUTCMinus: Instant = Instant.fromEpochSeconds(1609583445), ) val expectedJson = """ diff --git a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantISO8601SerDeTest.kt b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantISO8601SerDeTest.kt index 21e5d732..92cebf72 100644 --- a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantISO8601SerDeTest.kt +++ b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/InstantISO8601SerDeTest.kt @@ -21,7 +21,7 @@ class InstantISO8601SerDeTest { val instantNull: Instant? = null, val instantUTC: Instant = Instant.parse("2021-01-02T09:00:45Z"), val instantUTCPlus: Instant = Instant.parse("2021-01-02T09:00:45+01:30"), - val instantUTCMinus: Instant = Instant.parse("2021-01-02T09:00:45-01:30") + val instantUTCMinus: Instant = Instant.parse("2021-01-02T09:00:45-01:30"), ) val json = objectMapper.writeValueAsString(SomeObject()) @@ -33,7 +33,7 @@ class InstantISO8601SerDeTest { "instantUTCPlus": "2021-01-02T07:30:45Z", "instantUTCMinus": "2021-01-02T10:30:45Z" } - """.trimIndent() + """.trimIndent(), ) } @@ -44,7 +44,7 @@ class InstantISO8601SerDeTest { val instantNull: Instant? = null, val instantUTC: Instant = Instant.parse("2021-01-02T09:00:45Z"), val instantUTCPlus: Instant = Instant.parse("2021-01-02T09:00:45+01:30"), - val instantUTCMinus: Instant = Instant.parse("2021-01-02T09:00:45-01:30") + val instantUTCMinus: Instant = Instant.parse("2021-01-02T09:00:45-01:30"), ) val expectedJson = """ diff --git a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/NumbersSerDeTest.kt b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/NumbersSerDeTest.kt index bba6e82d..0ef4c289 100644 --- a/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/NumbersSerDeTest.kt +++ b/jvm-libs/generic/serialization/jackson/src/test/kotlin/build/linea/s11n/jackson/NumbersSerDeTest.kt @@ -47,7 +47,7 @@ class NumbersSerDeTest { val listOfInts: List = listOf(1, 10), val listOfLongs: List = listOf(1, 10), val listOfULongs: List = listOf(1UL, 10UL), - val listOfBigIntegers: List = listOf(1L, 10L).map(BigInteger::valueOf) + val listOfBigIntegers: List = listOf(1L, 10L).map(BigInteger::valueOf), ) val json = objectMapper.writeValueAsString(SomeObject()) @@ -74,7 +74,7 @@ class NumbersSerDeTest { "listOfULongs": ["0x1", "0xa"], "listOfBigIntegers": ["0x1", "0xa"] } - """.trimIndent() + """.trimIndent(), ) } } diff --git a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/ObservabilityServer.kt b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/ObservabilityServer.kt index 4847519b..82416879 100644 --- a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/ObservabilityServer.kt +++ b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/ObservabilityServer.kt @@ -26,7 +26,7 @@ class ObservabilityServer(private val config: Config) : AbstractVerticle() { val healthPath: String = "/health", val metricsHandler: Handler = PrometheusScrapingHandler.create(), val readinessSupplier: (() -> Boolean) = { true }, - val healthCheckHandler: HealthCheckHandler? = null + val healthCheckHandler: HealthCheckHandler? = null, ) private var actualPort: Int? = null diff --git a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxConfiguration.kt b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxConfiguration.kt index a6563c5d..dc6e823b 100644 --- a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxConfiguration.kt +++ b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxConfiguration.kt @@ -19,7 +19,7 @@ fun loadVertxConfig(): VertxOptions { val jsonRetrieverOptions = ConfigStoreOptions().setType("file").setConfig( JsonObject() .put("hierarchical", true) - .put("path", vertxPropertiesConfigFile) + .put("path", vertxPropertiesConfigFile), ) options.addStore(jsonRetrieverOptions) } diff --git a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxFactory.kt b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxFactory.kt index 01da3a89..0fc47159 100644 --- a/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxFactory.kt +++ b/jvm-libs/generic/vertx-helper/src/main/kotlin/net/consensys/linea/vertx/VertxFactory.kt @@ -18,7 +18,7 @@ object VertxFactory { warningExceptionTime: Duration? = 60.seconds, jvmMetricsEnabled: Boolean = true, prometheusMetricsEnabled: Boolean = true, - preferNativeTransport: Boolean = true + preferNativeTransport: Boolean = true, ): Vertx { val configs = JsonObject() maxEventLoopExecuteTime?.let { diff --git a/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ObservabilityServerTest.kt b/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ObservabilityServerTest.kt index 5a8abc98..5d1c16ef 100644 --- a/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ObservabilityServerTest.kt +++ b/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ObservabilityServerTest.kt @@ -40,8 +40,8 @@ class ObservabilityServerTest { val observabilityServer = ObservabilityServer( ObservabilityServer.Config( applicationName = "test", - port = 0 // random port assigned by underlying OS - ) + port = 0, // random port assigned by underlying OS + ), ) val deploymentId = vertx.deployVerticle(observabilityServer).get() @@ -50,7 +50,7 @@ class ObservabilityServerTest { .spec( RequestSpecBuilder() .setBaseUri("http://localhost:${(observabilityServer.port)}/") - .build() + .build(), ) .When { get("/live") @@ -111,7 +111,7 @@ class ObservabilityServerTest { private fun runServerOnARandomPort(vertx: Vertx): Pair { val observabilityServer = ObservabilityServer( - ObservabilityServer.Config(applicationName = "test") + ObservabilityServer.Config(applicationName = "test"), ) val deploymentId = vertx.deployVerticle(observabilityServer).get() return deploymentId to observabilityServer.port diff --git a/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ResourcesConfigurableVertxParameterProvider.kt b/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ResourcesConfigurableVertxParameterProvider.kt index 3df3f184..ddfc3013 100644 --- a/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ResourcesConfigurableVertxParameterProvider.kt +++ b/jvm-libs/generic/vertx-helper/src/test/kotlin/net/consensys/linea/vertx/ResourcesConfigurableVertxParameterProvider.kt @@ -23,7 +23,7 @@ class ResourcesConfigurableVertxParameterProvider : VertxParameterProvider() { "Failure when reading Vert.x options file {} from property {}, will use default options", optionFileName, VERTX_PARAMETER_FILENAME_SYS_PROP, - e + e, ) return JsonObject() } diff --git a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperBesuToLineaDomain.kt b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperBesuToLineaDomain.kt index e9405e2c..bc51f6af 100644 --- a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperBesuToLineaDomain.kt +++ b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperBesuToLineaDomain.kt @@ -30,7 +30,7 @@ object MapperBesuToLineaDomain { nonce = besuBlock.header.nonce.toULong(), baseFeePerGas = besuBlock.header.baseFee.getOrNull()?.toBigInteger()?.toULong(), ommers = besuBlock.body.ommers.map { it.hash.toArray() }, - transactions = besuBlock.body.transactions.map(MapperBesuToLineaDomain::mapToDomain) + transactions = besuBlock.body.transactions.map(MapperBesuToLineaDomain::mapToDomain), ) return block @@ -55,9 +55,9 @@ object MapperBesuToLineaDomain { accessList = transaction.accessList.getOrNull()?.map { accessListEntry -> AccessListEntry( accessListEntry.address.toArray(), - accessListEntry.storageKeys.map { it.toArray() } + accessListEntry.storageKeys.map { it.toArray() }, ) - } + }, ) } } diff --git a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperLineaDomainToBesu.kt b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperLineaDomainToBesu.kt index 881ac057..009a3834 100644 --- a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperLineaDomainToBesu.kt +++ b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/domain/MapperLineaDomainToBesu.kt @@ -30,7 +30,7 @@ object MapperLineaDomainToBesu { return secp256k1.createSignature( tx.r, tx.s, - recId + recId, ) } @@ -105,7 +105,7 @@ object MapperLineaDomainToBesu { .getOrElse { th -> throw RuntimeException( "Error mapping transaction to Besu: block=$blockNumber txIndex=$txIndex transaction=$tx", - th + th, ) } } @@ -132,7 +132,7 @@ object MapperLineaDomainToBesu { val accList = tx.accessList?.map { entry -> AccessListEntry( Address.wrap(Bytes.wrap(entry.address)), - entry.storageKeys.map { Bytes32.wrap(it) } + entry.storageKeys.map { Bytes32.wrap(it) }, ) } ?: emptyList() accessList(accList) diff --git a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/BesuRlpMainnetEncoder.kt b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/BesuRlpMainnetEncoder.kt index 94603150..838ac6f2 100644 --- a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/BesuRlpMainnetEncoder.kt +++ b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/BesuRlpMainnetEncoder.kt @@ -16,14 +16,14 @@ object BesuMainnetBlockRlpDecoder : BesuBlockRlpDecoder { class BesuRlpMainnetEncoderAsyncVertxImpl( val vertx: Vertx, - val encoder: BesuBlockRlpEncoder = BesuMainnetBlockRlpEncoder + val encoder: BesuBlockRlpEncoder = BesuMainnetBlockRlpEncoder, ) : BesuBlockRlpEncoderAsync { override fun encodeAsync(block: Block): SafeFuture { return vertx.executeBlocking( Callable { encoder.encode(block) }, - false + false, ) .toSafeFuture() } @@ -36,7 +36,7 @@ class BesuRlpMainnetEncoderAsyncVertxImpl( */ class BesuRlpDecoderAsyncVertxImpl( private val vertx: Vertx, - private val decoder: BesuBlockRlpDecoder + private val decoder: BesuBlockRlpDecoder, ) : BesuBlockRlpDecoderAsync { companion object { fun mainnetDecoder(vertx: Vertx): BesuBlockRlpDecoderAsync { @@ -53,7 +53,7 @@ class BesuRlpDecoderAsyncVertxImpl( Callable { decoder.decode(block) }, - false + false, ) .toSafeFuture() } diff --git a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/NoSignatureTransactionDecoder.kt b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/NoSignatureTransactionDecoder.kt index f04d418f..500bf301 100644 --- a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/NoSignatureTransactionDecoder.kt +++ b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/NoSignatureTransactionDecoder.kt @@ -43,7 +43,7 @@ class NoSignatureTransactionDecoder { transactionInput .readBytes { addressBytes: Bytes -> if (addressBytes.isEmpty) null else Address.wrap(addressBytes) - } + }, ) .value(Wei.of(transactionInput.readUInt256Scalar())) .payload(transactionInput.readBytes()) @@ -53,11 +53,11 @@ class NoSignatureTransactionDecoder { val accessListEntry = AccessListEntry( Address.wrap(accessListEntryRLPInput.readBytes()), - accessListEntryRLPInput.readList { obj: RLPInput -> obj.readBytes32() } + accessListEntryRLPInput.readList { obj: RLPInput -> obj.readBytes32() }, ) accessListEntryRLPInput.leaveList() accessListEntry - } + }, ) transactionInput.readUnsignedByteScalar() builder.sender(Address.extract(transactionInput.readUInt256Scalar())) @@ -83,10 +83,10 @@ class NoSignatureTransactionDecoder { null } else { Address.wrap( - v + v, ) } - } + }, ) .value(Wei.of(transactionInput.readUInt256Scalar())) .payload(transactionInput.readBytes()) @@ -96,11 +96,11 @@ class NoSignatureTransactionDecoder { val accessListEntry = AccessListEntry( Address.wrap(accessListEntryRLPInput.readBytes()), - accessListEntryRLPInput.readList { obj: RLPInput -> obj.readBytes32() } + accessListEntryRLPInput.readList { obj: RLPInput -> obj.readBytes32() }, ) accessListEntryRLPInput.leaveList() accessListEntry - } + }, ) transactionInput.readUnsignedByteScalar() builder.sender(Address.extract(transactionInput.readUInt256Scalar())) @@ -123,10 +123,10 @@ class NoSignatureTransactionDecoder { null } else { Address.wrap( - v + v, ) } - } + }, ) .value(Wei.of(input.readUInt256Scalar())) .payload(input.readBytes()) diff --git a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/RLP.kt b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/RLP.kt index ac969283..0239a384 100644 --- a/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/RLP.kt +++ b/jvm-libs/linea/besu-rlp-and-mappers/src/main/kotlin/linea/rlp/RLP.kt @@ -14,7 +14,7 @@ object RLP { fun decodeBlockWithMainnetFunctions(block: ByteArray): org.hyperledger.besu.ethereum.core.Block { return Block.readFrom( RLP.input(Bytes.wrap(block)), - MainnetBlockHeaderFunctions() + MainnetBlockHeaderFunctions(), ) } @@ -29,7 +29,7 @@ object RLP { } fun decodeList( - bytes: ByteArray + bytes: ByteArray, ): List { val items = mutableListOf() val rlpInput = RLP.input(Bytes.wrap(bytes), false) diff --git a/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/BlobCompressor.kt b/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/BlobCompressor.kt index 43b4e5d6..4c3db6c1 100644 --- a/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/BlobCompressor.kt +++ b/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/BlobCompressor.kt @@ -32,28 +32,28 @@ interface BlobCompressor { val blockAppended: Boolean, val compressedSizeBefore: Int, // even when block is not appended, compressedSizeAfter should as if it was appended - val compressedSizeAfter: Int + val compressedSizeAfter: Int, ) fun compressedSize(data: ByteArray): Int } class GoBackedBlobCompressor private constructor( - internal val goNativeBlobCompressor: GoNativeBlobCompressor + internal val goNativeBlobCompressor: GoNativeBlobCompressor, ) : BlobCompressor { companion object { @JvmStatic fun getInstance( compressorVersion: BlobCompressorVersion, - dataLimit: Int + dataLimit: Int, ): GoBackedBlobCompressor { require(dataLimit > 0) { "dataLimit=$dataLimit must be greater than 0" } val goNativeBlobCompressor = GoNativeBlobCompressorFactory.getInstance(compressorVersion) val initialized = goNativeBlobCompressor.Init( dataLimit = dataLimit, - dictPath = GoNativeBlobCompressorFactory.dictionaryPath.toString() + dictPath = GoNativeBlobCompressorFactory.dictionaryPath.toString(), ) if (!initialized) { throw InstantiationException(goNativeBlobCompressor.Error()) @@ -81,7 +81,7 @@ class GoBackedBlobCompressor private constructor( blockRLPEncoded.size, compressionSizeBefore, compressedSizeAfter, - 1.0 - ((compressedSizeAfter - compressionSizeBefore).toDouble() / blockRLPEncoded.size) + 1.0 - ((compressedSizeAfter - compressionSizeBefore).toDouble() / blockRLPEncoded.size), ) val error = goNativeBlobCompressor.Error() if (error != null) { diff --git a/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/GoNativeBlobCompressor.kt b/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/GoNativeBlobCompressor.kt index 2bd8f5e0..6a888527 100644 --- a/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/GoNativeBlobCompressor.kt +++ b/jvm-libs/linea/blob-compressor/src/main/kotlin/linea/blob/GoNativeBlobCompressor.kt @@ -100,7 +100,7 @@ interface GoNativeBlobCompressor { interface GoNativeBlobCompressorJnaLib : GoNativeBlobCompressor, Library enum class BlobCompressorVersion(val version: String) { - V1_2("v1.2.0") + V1_2("v1.2.0"), } class GoNativeBlobCompressorFactory { @@ -116,7 +116,7 @@ class GoNativeBlobCompressorFactory { @JvmStatic fun getInstance( - version: BlobCompressorVersion + version: BlobCompressorVersion, ): GoNativeBlobCompressor { synchronized(loadedVersions) { return loadedVersions[version] @@ -128,12 +128,14 @@ class GoNativeBlobCompressorFactory { private fun loadLib(version: BlobCompressorVersion): GoNativeBlobCompressor { val extractedLibFile = Native.extractFromResourcePath( getLibFileName(version.version), - GoNativeBlobCompressorFactory::class.java.classLoader + GoNativeBlobCompressorFactory::class.java.classLoader, ) return Native.load( - /* name = */ extractedLibFile.toString(), - /* interfaceClass = */ GoNativeBlobCompressorJnaLib::class.java + /* name = */ + extractedLibFile.toString(), + /* interfaceClass = */ + GoNativeBlobCompressorJnaLib::class.java, ) } } diff --git a/jvm-libs/linea/blob-compressor/src/test/kotlin/net/consensys/linea/blob/GoNativeCompressorAndShnarfCalculatorIntTest.kt b/jvm-libs/linea/blob-compressor/src/test/kotlin/net/consensys/linea/blob/GoNativeCompressorAndShnarfCalculatorIntTest.kt index fee1c376..92ad0a96 100644 --- a/jvm-libs/linea/blob-compressor/src/test/kotlin/net/consensys/linea/blob/GoNativeCompressorAndShnarfCalculatorIntTest.kt +++ b/jvm-libs/linea/blob-compressor/src/test/kotlin/net/consensys/linea/blob/GoNativeCompressorAndShnarfCalculatorIntTest.kt @@ -116,7 +116,7 @@ class GoNativeCompressorAndShnarfCalculatorIntTest { fun testsCompressionAndsShnarfCalculationWithEip4844Disabled( compressor: GoNativeBlobCompressor, - shnarfCalculator: GoNativeBlobShnarfCalculator + shnarfCalculator: GoNativeBlobShnarfCalculator, ) { testsCompressionAndsShnarfCalculation(compressor, shnarfCalculator, false) { result -> assertThat(result.commitment.decodeHex()).hasSize(0) @@ -129,7 +129,7 @@ class GoNativeCompressorAndShnarfCalculatorIntTest { fun testsCompressionAndsShnarfCalculationWithEip4844Enabled( compressor: GoNativeBlobCompressor, - shnarfCalculator: GoNativeBlobShnarfCalculator + shnarfCalculator: GoNativeBlobShnarfCalculator, ) { testsCompressionAndsShnarfCalculation(compressor, shnarfCalculator, true) { result -> assertThat(result.commitment.decodeHex()).hasSize(48) @@ -144,7 +144,7 @@ class GoNativeCompressorAndShnarfCalculatorIntTest { compressor: GoNativeBlobCompressor, shnarfCalculator: GoNativeBlobShnarfCalculator, eip4844Enabled: Boolean, - resultAsserterFn: (CalculateShnarfResult) -> Unit + resultAsserterFn: (CalculateShnarfResult) -> Unit, ) { val block = CompressorTestData.blocksRlpEncoded.first() assertTrue(compressor.Write(block, block.size)) @@ -161,7 +161,7 @@ class GoNativeCompressorAndShnarfCalculatorIntTest { prevShnarf = Random.nextBytes(32).encodeHex(), conflationOrderStartingBlockNumber = 1, conflationOrderUpperBoundariesLen = 2, - conflationOrderUpperBoundaries = longArrayOf(10, 20) + conflationOrderUpperBoundaries = longArrayOf(10, 20), ) assertThat(result).isNotNull assertThat(result.errorMessage).isEmpty() diff --git a/jvm-libs/linea/blob-compressor/src/testFixtures/kotlin/net/consensys/linea/nativecompressor/TestDataGeneratorHelper.kt b/jvm-libs/linea/blob-compressor/src/testFixtures/kotlin/net/consensys/linea/nativecompressor/TestDataGeneratorHelper.kt index 6278acf5..2ddcdc20 100644 --- a/jvm-libs/linea/blob-compressor/src/testFixtures/kotlin/net/consensys/linea/nativecompressor/TestDataGeneratorHelper.kt +++ b/jvm-libs/linea/blob-compressor/src/testFixtures/kotlin/net/consensys/linea/nativecompressor/TestDataGeneratorHelper.kt @@ -10,7 +10,7 @@ import java.nio.file.Files import java.nio.file.Path fun loadBlocksFromProverRequests( - proverExecutionRequestsFolder: Path + proverExecutionRequestsFolder: Path, ): List> { val blocks = Files .list(proverExecutionRequestsFolder) @@ -38,14 +38,14 @@ fun loadBlocksFromProverRequests( fun generateEncodeBlocksToBinaryFromProverRequests( proverExecutionRequestsFolder: Path, - outputFilePath: Path + outputFilePath: Path, ) { val blocks = loadBlocksFromProverRequests(proverExecutionRequestsFolder) Files.write(outputFilePath, RLP.encodeList(blocks.map { it.second })) } fun loadBlocksRlpEncoded( - binFile: Path + binFile: Path, ): List { return RLP.decodeList(Files.readAllBytes(binFile)) } @@ -57,7 +57,7 @@ fun main() { generateEncodeBlocksToBinaryFromProverRequests( proverExecutionRequestsDir, - destFile + destFile, ) // Just a visual indicator that it can read/decode again diff --git a/jvm-libs/linea/blob-decompressor/src/main/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressor.kt b/jvm-libs/linea/blob-decompressor/src/main/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressor.kt index 2e3d88db..7598ab1d 100644 --- a/jvm-libs/linea/blob-decompressor/src/main/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressor.kt +++ b/jvm-libs/linea/blob-decompressor/src/main/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressor.kt @@ -14,7 +14,7 @@ interface BlobDecompressor { internal class Adapter( private val delegate: GoNativeBlobDecompressorJnaBinding, private val maxExpectedCompressionRatio: Int = 20, - dictionaries: List + dictionaries: List, ) : BlobDecompressor { init { delegate.Init() @@ -81,14 +81,14 @@ internal interface GoNativeBlobDecompressorJnaBinding { internal interface GoNativeBlobDecompressorJnaLib : GoNativeBlobDecompressorJnaBinding, Library enum class BlobDecompressorVersion(val version: String) { - V1_2_0("v1.2.0") + V1_2_0("v1.2.0"), } class GoNativeBlobDecompressorFactory { companion object { private val DICTIONARY_NAMES = arrayOf( "compressor-dictionaries/compressor_dict.bin", - "compressor-dictionaries/v2025-04-21.bin" + "compressor-dictionaries/v2025-04-21.bin", ) private val dictionaryPaths = DICTIONARY_NAMES.map { dictionaryName -> copyResourceToTmpDir(dictionaryName, GoNativeBlobDecompressorFactory::class.java.classLoader) @@ -97,15 +97,15 @@ class GoNativeBlobDecompressorFactory { private fun getLibFileName(version: String) = "blob_decompressor_jna_$version" fun getInstance( - version: BlobDecompressorVersion + version: BlobDecompressorVersion, ): BlobDecompressor { val libFile = Native.extractFromResourcePath( getLibFileName(version.version), - GoNativeBlobDecompressorFactory::class.java.classLoader + GoNativeBlobDecompressorFactory::class.java.classLoader, ) return Native.load( libFile.toString(), - GoNativeBlobDecompressorJnaLib::class.java + GoNativeBlobDecompressorJnaLib::class.java, ).let { Adapter(delegate = it, dictionaries = dictionaryPaths) } diff --git a/jvm-libs/linea/blob-decompressor/src/test/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressorTest.kt b/jvm-libs/linea/blob-decompressor/src/test/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressorTest.kt index 111c12a8..fe9cad4a 100644 --- a/jvm-libs/linea/blob-decompressor/src/test/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressorTest.kt +++ b/jvm-libs/linea/blob-decompressor/src/test/kotlin/net/consensys/linea/blob/GoNativeBlobDecompressorTest.kt @@ -54,7 +54,7 @@ class GoNativeBlobDecompressorTest { gasLimit = 22_0000uL, to = null, value = 1uL.eth.toBigInteger(), - input = byteArrayOf() + input = byteArrayOf(), ) val tx1 = TransactionFactory.createTransactionEip1559( nonce = 123uL, @@ -67,22 +67,22 @@ class GoNativeBlobDecompressorTest { address = "0x0000000000000000000000000000000000000001".decodeHex(), storageKeys = listOf( "0x0000000000000000000000000000000000000000000000000000000000000001".decodeHex(), - "0x0000000000000000000000000000000000000000000000000000000000000002".decodeHex() - ) + "0x0000000000000000000000000000000000000000000000000000000000000002".decodeHex(), + ), ), AccessListEntry( address = "0x0000000000000000000000000000000000000002".decodeHex(), storageKeys = listOf( "0x0000000000000000000000000000000000000000000000000000000000000011".decodeHex(), - "0x0000000000000000000000000000000000000000000000000000000000000012".decodeHex() - ) - ) - ) + "0x0000000000000000000000000000000000000000000000000000000000000012".decodeHex(), + ), + ), + ), ) val originalBesuBlock = createBlock( number = 123uL, timestamp = Instant.parse("2025-01-02T12:23:45Z"), - transactions = listOf(tx0, tx1) + transactions = listOf(tx0, tx1), ).toBesu() compressor.appendBlock(RLP.encodeBlock(originalBesuBlock)) diff --git a/jvm-libs/linea/blob-shnarf-calculator/src/main/kotlin/linea/blob/GoNativeBlobShnarfCalculator.kt b/jvm-libs/linea/blob-shnarf-calculator/src/main/kotlin/linea/blob/GoNativeBlobShnarfCalculator.kt index ee18e7b0..8a3e5b38 100644 --- a/jvm-libs/linea/blob-shnarf-calculator/src/main/kotlin/linea/blob/GoNativeBlobShnarfCalculator.kt +++ b/jvm-libs/linea/blob-shnarf-calculator/src/main/kotlin/linea/blob/GoNativeBlobShnarfCalculator.kt @@ -16,7 +16,7 @@ class CalculateShnarfResult( @JvmField var expectedShnarf: String, // error message is empty if there is no error // it cannot be null because JNA call blow up with segfault. - @JvmField var errorMessage: String + @JvmField var errorMessage: String, ) : Structure() { // JNA requires a default constructor @@ -32,7 +32,7 @@ class CalculateShnarfResult( "expectedX", "expectedY", "expectedShnarf", - "errorMessage" + "errorMessage", ) } } @@ -50,7 +50,7 @@ interface GoNativeBlobShnarfCalculator { prevShnarf: String, conflationOrderStartingBlockNumber: Long, conflationOrderUpperBoundariesLen: Int, - conflationOrderUpperBoundaries: LongArray + conflationOrderUpperBoundaries: LongArray, ): CalculateShnarfResult } @@ -58,7 +58,7 @@ interface GoNativeBlobShnarfCalculator { internal interface GoNativeBlobShnarfCalculatorJna : GoNativeBlobShnarfCalculator, Library enum class ShnarfCalculatorVersion(val version: String) { - V1_2("v1.2.0") + V1_2("v1.2.0"), } class GoNativeShnarfCalculatorFactory { @@ -66,15 +66,15 @@ class GoNativeShnarfCalculatorFactory { private fun getLibFileName(version: String) = "shnarf_calculator_jna_$version" fun getInstance( - version: ShnarfCalculatorVersion + version: ShnarfCalculatorVersion, ): GoNativeBlobShnarfCalculator { val extractedLibFile = Native.extractFromResourcePath( getLibFileName(version.version), - GoNativeShnarfCalculatorFactory::class.java.classLoader + GoNativeShnarfCalculatorFactory::class.java.classLoader, ) return Native.load( extractedLibFile.toString(), - GoNativeBlobShnarfCalculatorJna::class.java + GoNativeBlobShnarfCalculatorJna::class.java, ) } } diff --git a/jvm-libs/linea/blob-shnarf-calculator/src/test/kotlin/linea/blob/GoNativeBlobShnarfCalculatorTest.kt b/jvm-libs/linea/blob-shnarf-calculator/src/test/kotlin/linea/blob/GoNativeBlobShnarfCalculatorTest.kt index 1c4a9dcb..2745dd14 100644 --- a/jvm-libs/linea/blob-shnarf-calculator/src/test/kotlin/linea/blob/GoNativeBlobShnarfCalculatorTest.kt +++ b/jvm-libs/linea/blob-shnarf-calculator/src/test/kotlin/linea/blob/GoNativeBlobShnarfCalculatorTest.kt @@ -48,7 +48,7 @@ class GoNativeBlobShnarfCalculatorTest { } fun testCalculateShnarfEip4844Disabled( - calculator: GoNativeBlobShnarfCalculator + calculator: GoNativeBlobShnarfCalculator, ) { testCalculate(calculator, eip4844Enabled = false) { result -> Assertions.assertNotNull(result.commitment) @@ -61,7 +61,7 @@ class GoNativeBlobShnarfCalculatorTest { } fun testCalculateShnarfEip4844Enabled( - calculator: GoNativeBlobShnarfCalculator + calculator: GoNativeBlobShnarfCalculator, ) { testCalculate(calculator, eip4844Enabled = true) { result -> Assertions.assertNotNull(result.commitment) @@ -76,7 +76,7 @@ class GoNativeBlobShnarfCalculatorTest { private fun testCalculate( calculator: GoNativeBlobShnarfCalculator, eip4844Enabled: Boolean, - assertResultFn: (CalculateShnarfResult) -> Unit = {} + assertResultFn: (CalculateShnarfResult) -> Unit = {}, ) { val result = calculator.CalculateShnarf( eip4844Enabled = eip4844Enabled, @@ -86,7 +86,7 @@ class GoNativeBlobShnarfCalculatorTest { prevShnarf = Random.Default.nextBytes(32).encodeHex(), conflationOrderStartingBlockNumber = 1L, conflationOrderUpperBoundariesLen = 3, - conflationOrderUpperBoundaries = longArrayOf(10L, 20L, 30L) + conflationOrderUpperBoundaries = longArrayOf(10L, 20L, 30L), ) Assertions.assertNotNull(result) @@ -123,7 +123,7 @@ class GoNativeBlobShnarfCalculatorTest { prevShnarf = Random.Default.nextBytes(32).encodeHex(), conflationOrderStartingBlockNumber = 0L, conflationOrderUpperBoundariesLen = 2, - conflationOrderUpperBoundaries = longArrayOf(10L, 20L) + conflationOrderUpperBoundaries = longArrayOf(10L, 20L), ) // .let { result -> forcedLeakBuffer.add(result) } } @@ -132,7 +132,7 @@ class GoNativeBlobShnarfCalculatorTest { println( "total=${Runtime.getRuntime().totalMemory()}, " + "free=${Runtime.getRuntime().freeMemory()}, " + - "max=${Runtime.getRuntime().maxMemory()}" + "max=${Runtime.getRuntime().maxMemory()}", ) } } diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/EthLogsSearcherImpl.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/EthLogsSearcherImpl.kt index 61a57d9d..38c45284 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/EthLogsSearcherImpl.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/EthLogsSearcherImpl.kt @@ -30,10 +30,10 @@ class EthLogsSearcherImpl( val ethApiClient: EthApiClient, val config: Config = Config(), val clock: Clock = Clock.System, - val log: Logger = LogManager.getLogger(EthLogsSearcherImpl::class.java) + val log: Logger = LogManager.getLogger(EthLogsSearcherImpl::class.java), ) : EthLogsSearcher, EthLogsClient by ethApiClient { data class Config( - val loopSuccessBackoffDelay: Duration = 1.milliseconds + val loopSuccessBackoffDelay: Duration = 1.milliseconds, ) override fun findLog( @@ -42,7 +42,7 @@ class EthLogsSearcherImpl( chunkSize: Int, address: String, topics: List, - shallContinueToSearch: (EthLog) -> SearchDirection? + shallContinueToSearch: (EthLog) -> SearchDirection?, ): SafeFuture { require(chunkSize > 0) { "chunkSize=$chunkSize must be greater than 0" } @@ -51,7 +51,7 @@ class EthLogsSearcherImpl( if (start > end) { // this is to prevent edge case when fromBlock number is after toBlock=LATEST/FINALIZED SafeFuture.failedFuture( - IllegalStateException("invalid range: fromBlock=$fromBlock is after toBlock=$toBlock ($end)") + IllegalStateException("invalid range: fromBlock=$fromBlock is after toBlock=$toBlock ($end)"), ) } else { findLogWithBinarySearch( @@ -60,7 +60,7 @@ class EthLogsSearcherImpl( chunkSize = chunkSize, address = address, topics = topics, - shallContinueToSearchPredicate = shallContinueToSearch + shallContinueToSearchPredicate = shallContinueToSearch, ) } } @@ -73,7 +73,7 @@ class EthLogsSearcherImpl( topics: List, chunkSize: UInt, searchTimeout: Duration, - stopAfterTargetLogsCount: UInt? + stopAfterTargetLogsCount: UInt?, ): SafeFuture { require(chunkSize > 0u) { "chunkSize=$chunkSize must be greater than 0" } @@ -82,7 +82,7 @@ class EthLogsSearcherImpl( if (start > end) { // this is to prevent edge case when fromBlock number is after toBlock=LATEST/FINALIZED SafeFuture.failedFuture( - IllegalStateException("invalid range: fromBlock=$fromBlock is after toBlock=$toBlock ($end)") + IllegalStateException("invalid range: fromBlock=$fromBlock is after toBlock=$toBlock ($end)"), ) } else { getLogsLoopingForward( @@ -92,7 +92,7 @@ class EthLogsSearcherImpl( topics = topics, chunkSize = chunkSize, searchTimeout = searchTimeout, - logsSoftLimit = stopAfterTargetLogsCount + logsSoftLimit = stopAfterTargetLogsCount, ) } } @@ -105,7 +105,7 @@ class EthLogsSearcherImpl( topics: List, chunkSize: UInt, searchTimeout: Duration, - logsSoftLimit: UInt? + logsSoftLimit: UInt?, ): SafeFuture { val cursor = ConsecutiveSearchCursor(fromBlock, toBlock, chunkSize.toInt(), SearchDirection.FORWARD) @@ -122,7 +122,7 @@ class EthLogsSearcherImpl( val noMoreChunksToCollect = !cursor.hasNext() enoughLogsCollected || collectionTimeoutElapsed || noMoreChunksToCollect - } + }, ) { val chunk = cursor.next() val chunkInterval = CommonDomainFunctions.blockIntervalString(chunk.start, chunk.endInclusive) @@ -136,7 +136,7 @@ class EthLogsSearcherImpl( log.trace( "logs collected: chunk={} logsCount={}", chunkInterval, - result.size + result.size, ) } } @@ -150,12 +150,12 @@ class EthLogsSearcherImpl( endBlockNumber, address, topics.joinToString(", ") { it ?: "null" }, - logs.size + logs.size, ) EthLogsSearcher.LogSearchResult( logs = logs, startBlockNumber = fromBlock, - endBlockNumber = endBlockNumber + endBlockNumber = endBlockNumber, ) } } @@ -166,7 +166,7 @@ class EthLogsSearcherImpl( chunkSize: Int, address: String, topics: List, - shallContinueToSearchPredicate: (EthLog) -> SearchDirection? + shallContinueToSearchPredicate: (EthLog) -> SearchDirection?, ): SafeFuture { val cursor = BinarySearchCursor(fromBlock, toBlock, chunkSize) log.trace("searching between blocks={}", CommonDomainFunctions.blockIntervalString(fromBlock, toBlock)) @@ -178,7 +178,7 @@ class EthLogsSearcherImpl( backoffDelay = config.loopSuccessBackoffDelay, stopRetriesPredicate = { it is SearchResult.ItemFound || nextChunkToSearchRef.get() == null - } + }, ) { log.trace("searching in chunk={}", nextChunkToSearchRef.get()) val (chunkStart, chunkEnd) = nextChunkToSearchRef.get()!! @@ -195,7 +195,7 @@ class EthLogsSearcherImpl( "search result chunk={} searchResult={} nextChunkToSearch={}", chunkInterval, result, - nextChunkToSearchRef.get() + nextChunkToSearchRef.get(), ) } }.thenApply { either -> @@ -211,13 +211,13 @@ class EthLogsSearcherImpl( toBlock: ULong, address: String, topics: List, - shallContinueToSearchPredicate: (EthLog) -> SearchDirection? + shallContinueToSearchPredicate: (EthLog) -> SearchDirection?, ): SafeFuture { return getLogs( fromBlock = fromBlock.toBlockParameter(), toBlock = toBlock.toBlockParameter(), address = address, - topics = topics + topics = topics, ) .thenApply { logs -> if (logs.isEmpty()) { @@ -239,11 +239,11 @@ class EthLogsSearcherImpl( private fun getAbsoluteBlockNumbers( fromBlock: BlockParameter, - toBlock: BlockParameter + toBlock: BlockParameter, ): SafeFuture> { return SafeFuture.collectAll( getBlockParameterNumber(fromBlock), - getBlockParameterNumber(toBlock) + getBlockParameterNumber(toBlock), ).thenApply { (start, end) -> start to end } diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/BinarySearchCursor.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/BinarySearchCursor.kt index 6df0dc6f..0122dfac 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/BinarySearchCursor.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/BinarySearchCursor.kt @@ -5,7 +5,7 @@ import linea.SearchDirection internal fun rangeChunks( start: ULong, end: ULong, - chunkSize: Int + chunkSize: Int, ): List { return (start..end step chunkSize.toLong()) .map { chunkStart -> @@ -26,7 +26,7 @@ internal fun rangeChunks( internal class BinarySearchCursor( val from: ULong, val to: ULong, - val chunkSize: Int + val chunkSize: Int, ) { init { require(from <= to) { "invalid range: from=$from must be less or equal to=$to" } diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursor.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursor.kt index 2a043173..6ff713db 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursor.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/main/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursor.kt @@ -6,7 +6,7 @@ internal class ConsecutiveSearchCursor( val from: ULong, val to: ULong, val chunkSize: Int, - val direction: SearchDirection + val direction: SearchDirection, ) : Iterator { private val chunks: List = run { diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherIntTest.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherIntTest.kt index a912178e..ccc333f9 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherIntTest.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherIntTest.kt @@ -37,7 +37,7 @@ internal data class EthGetLogsRequest( val fromBlock: ULong, val toBlock: ULong, val topics: List, - val address: List + val address: List, ) class EthLogsSearcherImplIntTest { @@ -55,7 +55,7 @@ class EthLogsSearcherImplIntTest { configureLoggers( rootLevel = Level.INFO, log.name to Level.DEBUG, - "test.case.Web3JLogsSearcher" to Level.DEBUG + "test.case.Web3JLogsSearcher" to Level.DEBUG, ) } @@ -65,7 +65,7 @@ class EthLogsSearcherImplIntTest { } private fun setupClientWithWireMockServer( - retryConfig: RetryConfig = RetryConfig.noRetries + retryConfig: RetryConfig = RetryConfig.noRetries, ) { wireMockServer = WireMockServer(WireMockConfiguration.options().dynamicPort()) wireMockServer.start() @@ -77,22 +77,22 @@ class EthLogsSearcherImplIntTest { ethApiClient = createEthApiClient( web3jClient = web3jClient, requestRetryConfig = retryConfig, - vertx = vertx + vertx = vertx, ), config = EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = 1.milliseconds - ) + loopSuccessBackoffDelay = 1.milliseconds, + ), ) } private fun setupClientWithTestingJsonRpcServer( retryConfig: RetryConfig = RetryConfig.noRetries, - subsetOfBlocksWithLogs: List? = null + subsetOfBlocksWithLogs: List? = null, ) { TestingJsonRpcServer = TestingJsonRpcServer( vertx = vertx, serverName = "fake-execution-layer-log-searcher", - recordRequestsResponses = true + recordRequestsResponses = true, ) setUpFakeLogsServerToHandleEthLogs(TestingJsonRpcServer, subsetOfBlocksWithLogs) logsClient = EthLogsSearcherImpl( @@ -100,12 +100,12 @@ class EthLogsSearcherImplIntTest { ethApiClient = createEthApiClient( vertx = vertx, web3jClient = Web3j.build(HttpService(URI("http://127.0.0.1:" + TestingJsonRpcServer.boundPort).toString())), - requestRetryConfig = retryConfig + requestRetryConfig = retryConfig, ), config = EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = 1.milliseconds + loopSuccessBackoffDelay = 1.milliseconds, ), - log = LogManager.getLogger("test.case.Web3JLogsSearcher") + log = LogManager.getLogger("test.case.Web3JLogsSearcher"), ) } @@ -117,8 +117,8 @@ class EthLogsSearcherImplIntTest { aResponse() .withStatus(statusCode) .withBody(responseBody) - .withHeader("Content-Type", "application/json") - ) + .withHeader("Content-Type", "application/json"), + ), ) } @@ -136,7 +136,7 @@ class EthLogsSearcherImplIntTest { }, "id": 1 } - """.trimIndent() + """.trimIndent(), ) assertThatThrownBy { @@ -144,7 +144,7 @@ class EthLogsSearcherImplIntTest { 0UL.toBlockParameter(), 20UL.toBlockParameter(), address = address, - topics = emptyList() + topics = emptyList(), ).get() } .hasCauseInstanceOf(RuntimeException::class.java) @@ -172,7 +172,7 @@ class EthLogsSearcherImplIntTest { "transactionIndex": "0x0" }] } - """.trimIndent() + """.trimIndent(), ) assertThatThrownBy { @@ -180,7 +180,7 @@ class EthLogsSearcherImplIntTest { 0UL.toBlockParameter(), 20UL.toBlockParameter(), address = address, - topics = emptyList() + topics = emptyList(), ).get() } } @@ -190,8 +190,8 @@ class EthLogsSearcherImplIntTest { setupClientWithTestingJsonRpcServer( retryConfig = RetryConfig( backoffDelay = 1.milliseconds, - maxRetries = 4u - ) + maxRetries = 4u, + ), ) TestingJsonRpcServer.handle("eth_getLogs", { _ -> @@ -208,7 +208,7 @@ class EthLogsSearcherImplIntTest { 0UL.toBlockParameter(), 20UL.toBlockParameter(), address = address, - topics = emptyList() + topics = emptyList(), ) getLogsFuture.get().also { logs -> @@ -222,7 +222,7 @@ class EthLogsSearcherImplIntTest { replyEthGetLogsWith( statusCode = 500, - responseBody = "Internal Server Error" + responseBody = "Internal Server Error", ) assertThatThrownBy { @@ -230,7 +230,7 @@ class EthLogsSearcherImplIntTest { 0UL.toBlockParameter(), 20UL.toBlockParameter(), address = address, - topics = emptyList() + topics = emptyList(), ).get() } .hasCauseInstanceOf(org.web3j.protocol.exceptions.ClientConnectionException::class.java) @@ -247,11 +247,11 @@ class EthLogsSearcherImplIntTest { createEthApiClient( web3jClient, requestRetryConfig = RetryConfig.noRetries, - vertx = null + vertx = null, ), config = EthLogsSearcherImpl.Config( - loopSuccessBackoffDelay = 1.milliseconds - ) + loopSuccessBackoffDelay = 1.milliseconds, + ), ) assertThatThrownBy { @@ -259,7 +259,7 @@ class EthLogsSearcherImplIntTest { 0UL.toBlockParameter(), 20UL.toBlockParameter(), address = address, - topics = emptyList() + topics = emptyList(), ).get() } .hasCauseInstanceOf(java.net.UnknownHostException::class.java) @@ -269,7 +269,7 @@ class EthLogsSearcherImplIntTest { private fun shallContinueToSearch( ethLog: EthLog, - targetNumber: ULong + targetNumber: ULong, ): SearchDirection? { val number = ULong.fromHexString(ethLog.topics[1].encodeHex()) val direction = when { @@ -282,7 +282,7 @@ class EthLogsSearcherImplIntTest { ethLog.blockNumber, number, targetNumber, - direction + direction, ) return direction } @@ -301,7 +301,7 @@ class EthLogsSearcherImplIntTest { chunkSize = 10, shallContinueToSearch = { ethLog -> shallContinueToSearch(ethLog, targetNumber = number.toULong()) - } + }, ) .get() .also { log -> @@ -325,7 +325,7 @@ class EthLogsSearcherImplIntTest { shallContinueToSearch = { ethLog -> logsEvaluated.add(ethLog.blockNumber) shallContinueToSearch(ethLog, targetNumber = 89UL) - } + }, ) .get() .also { log -> @@ -339,7 +339,7 @@ class EthLogsSearcherImplIntTest { @Test fun `findLogs searches L1 and returns null when not found - target expected in chunk that has no logs`() { setupClientWithTestingJsonRpcServer( - subsetOfBlocksWithLogs = listOf(100UL..109UL, 150UL..159UL) + subsetOfBlocksWithLogs = listOf(100UL..109UL, 150UL..159UL), ) val logsEvaluated = mutableListOf() @@ -351,7 +351,7 @@ class EthLogsSearcherImplIntTest { chunkSize = 10, shallContinueToSearch = { ethLog -> shallContinueToSearch(ethLog, targetNumber = 120UL) - } + }, ) .get() .also { log -> @@ -363,7 +363,7 @@ class EthLogsSearcherImplIntTest { @Test fun `findLogs searches L1 and returns null when not found - target is after toBlock`() { setupClientWithTestingJsonRpcServer( - subsetOfBlocksWithLogs = listOf(100UL..109UL, 150UL..200UL) + subsetOfBlocksWithLogs = listOf(100UL..109UL, 150UL..200UL), ) val logsEvaluated = mutableListOf() @@ -375,7 +375,7 @@ class EthLogsSearcherImplIntTest { chunkSize = 10, shallContinueToSearch = { ethLog -> shallContinueToSearch(ethLog, targetNumber = 250UL) - } + }, ) .get() .also { log -> @@ -389,7 +389,7 @@ class EthLogsSearcherImplIntTest { @Test fun `findLogs searches L1 and returns item when - target found an chunk in the middle`() { setupClientWithTestingJsonRpcServer( - subsetOfBlocksWithLogs = listOf(10UL..19UL, 30UL..37UL, 50UL..100UL) + subsetOfBlocksWithLogs = listOf(10UL..19UL, 30UL..37UL, 50UL..100UL), ) val logsEvaluated = mutableListOf() logsClient.findLog( @@ -400,7 +400,7 @@ class EthLogsSearcherImplIntTest { chunkSize = 5, shallContinueToSearch = { ethLog -> shallContinueToSearch(ethLog, targetNumber = 35UL) - } + }, ) .get() .also { log -> @@ -416,13 +416,13 @@ class EthLogsSearcherImplIntTest { fromBlock: Int, toBlock: Int, stepSize: Int = 1, - topic: String = "0x" + topic: String = "0x", ): List> { return (fromBlock..toBlock step stepSize) .map { generateLogJson( blockNumber = it, - topic = topic + topic = topic, ) } } @@ -430,11 +430,11 @@ class EthLogsSearcherImplIntTest { private fun generateLogJson( blockNumber: Int, topic: String = "0x", - transactionHash: String = "0x" + transactionHash: String = "0x", ): Map { val topics = listOf( topic, - blockNumber.toULong().toHexStringUInt256() + blockNumber.toULong().toHexStringUInt256(), ) return mapOf( "address" to "0x", @@ -445,13 +445,13 @@ class EthLogsSearcherImplIntTest { "removed" to false, "topics" to topics, "transactionHash" to transactionHash, - "transactionIndex" to "0x0" + "transactionIndex" to "0x0", ) } internal fun generateLogs( blocksWithLogs: List, - filter: EthGetLogsRequest + filter: EthGetLogsRequest, ): List> { return generateEffectiveIntervals(blocksWithLogs, filter.fromBlock, filter.toBlock) // .also { @@ -485,13 +485,13 @@ class EthLogsSearcherImplIntTest { fromBlock = fromBlock, toBlock = toBlock, topics = topics, - address = logsFilter["address"] as List + address = logsFilter["address"] as List, ) } private fun setUpFakeLogsServerToHandleEthLogs( TestingJsonRpcServer: TestingJsonRpcServer, - subsetOfBlocksWithLogs: List? + subsetOfBlocksWithLogs: List?, ) { TestingJsonRpcServer.apply { this.handle("eth_getLogs", { request -> @@ -502,7 +502,7 @@ class EthLogsSearcherImplIntTest { } ?: generateLogsForBlockRange( fromBlock = filter.fromBlock.toInt(), toBlock = filter.toBlock.toInt(), - topic = filter.topics[0] + topic = filter.topics[0], ) }) } diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherTest.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherTest.kt index a3c2ed07..0f3840aa 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherTest.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/LogsSearcherTest.kt @@ -25,26 +25,26 @@ class LogsSearcherTest { transactionIndex = 0UL, logIndex = 0UL, blockHash = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef".decodeHex(), - removed = false + removed = false, ) private val initialLogs = listOf( templateLog.copy( blockNumber = 200UL, - topics = listOf(testTopic1.decodeHex(), testTopic2.decodeHex()) + topics = listOf(testTopic1.decodeHex(), testTopic2.decodeHex()), ), templateLog.copy( blockNumber = 300UL, - topics = listOf(testTopic1.decodeHex()) + topics = listOf(testTopic1.decodeHex()), ), templateLog.copy( blockNumber = 350UL, - topics = listOf(testTopic2.decodeHex()) + topics = listOf(testTopic2.decodeHex()), ), templateLog.copy( blockNumber = 400UL, address = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa02".decodeHex(), - topics = listOf(testTopic2.decodeHex()) - ) + topics = listOf(testTopic2.decodeHex()), + ), ) private lateinit var vertx: Vertx private lateinit var fakeElClient: FakeEthApiClient @@ -73,7 +73,7 @@ class LogsSearcherTest { topics = emptyList(), chunkSize = 10U, searchTimeout = 1000000.seconds, - stopAfterTargetLogsCount = null + stopAfterTargetLogsCount = null, ).get() assertThat(result.logs).isEqualTo(initialLogs.take(3)) @@ -90,7 +90,7 @@ class LogsSearcherTest { topics = emptyList(), chunkSize = 100U, searchTimeout = 5.seconds, - stopAfterTargetLogsCount = null + stopAfterTargetLogsCount = null, ).get() assertThat(result.logs).isEqualTo(listOf(initialLogs[3])) @@ -105,7 +105,7 @@ class LogsSearcherTest { topics = listOf(testTopic1), chunkSize = 100U, searchTimeout = 5.seconds, - stopAfterTargetLogsCount = null + stopAfterTargetLogsCount = null, ).get() assertThat(result.logs).isEqualTo(initialLogs.take(2)) @@ -120,7 +120,7 @@ class LogsSearcherTest { topics = emptyList(), chunkSize = 50U, searchTimeout = 2.hours, - stopAfterTargetLogsCount = 1U + stopAfterTargetLogsCount = 1U, ).get() assertThat(result.logs).isEqualTo(initialLogs.take(1)) @@ -131,7 +131,7 @@ class LogsSearcherTest { searcher = EthLogsSearcherImpl( vertx, fakeElClient, - config = EthLogsSearcherImpl.Config(loopSuccessBackoffDelay = 1.seconds) + config = EthLogsSearcherImpl.Config(loopSuccessBackoffDelay = 1.seconds), ) val result = searcher.getLogsRollingForward( fromBlock = BlockParameter.BlockNumber(initialLogs.first().blockNumber), @@ -140,7 +140,7 @@ class LogsSearcherTest { topics = emptyList(), chunkSize = 50U, searchTimeout = 1.seconds, // it only has time for the first iteration - stopAfterTargetLogsCount = null + stopAfterTargetLogsCount = null, ).get() assertThat(result.logs).hasSize(1) @@ -155,7 +155,7 @@ class LogsSearcherTest { topics = listOf("0x3333333333333333333333333333333333333333333333333333333333333333"), chunkSize = 100U, searchTimeout = 5.seconds, - stopAfterTargetLogsCount = null + stopAfterTargetLogsCount = null, ).get() assertThat(result.logs).isEmpty() diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/ULongRangesHelperTest.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/ULongRangesHelperTest.kt index 14d981fd..5212da64 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/ULongRangesHelperTest.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/ULongRangesHelperTest.kt @@ -7,7 +7,7 @@ import org.junit.jupiter.api.Test internal fun generateEffectiveIntervals( blocksWithLogs: List, filterFromBlock: ULong, - filterToBlock: ULong + filterToBlock: ULong, ): List { // if blocksWithLogs is [10..19, 25..29, 40..49] and filter.fromBlock=15 and filter.toBlock=45 // then we will return logs for blocks [15..19, 25..29, 40..45] @@ -29,7 +29,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 0UL, - filterToBlock = 9UL + filterToBlock = 9UL, ) .also { assertThat(it).isEmpty() @@ -39,7 +39,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 0UL, - filterToBlock = 15UL + filterToBlock = 15UL, ) .also { assertThat(it).containsExactly(10UL..15UL) @@ -48,7 +48,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 15UL, - filterToBlock = 25UL + filterToBlock = 25UL, ) .also { assertThat(it).containsExactly(15UL..19UL) @@ -58,7 +58,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 0UL, - filterToBlock = 25UL + filterToBlock = 25UL, ) .also { assertThat(it).containsExactly(10UL..19UL) @@ -68,7 +68,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 42UL, - filterToBlock = 45UL + filterToBlock = 45UL, ) .also { assertThat(it).containsExactly(42UL..45UL) @@ -78,7 +78,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 50UL, - filterToBlock = 55UL + filterToBlock = 55UL, ) .also { assertThat(it).isEmpty() @@ -88,7 +88,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 0UL, - filterToBlock = 100UL + filterToBlock = 100UL, ) .also { assertThat(it).containsExactly(10UL..19UL, 40UL..49UL, 60UL..69UL) @@ -98,7 +98,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 15UL, - filterToBlock = 65UL + filterToBlock = 65UL, ) .also { assertThat(it).containsExactly(15UL..19UL, 40UL..49UL, 60UL..65UL) @@ -108,7 +108,7 @@ class ULongRangesHelperTest { generateEffectiveIntervals( blocksWithLogs = blocksWithLogs, filterFromBlock = 15UL, - filterToBlock = 45UL + filterToBlock = 45UL, ) .also { assertThat(it).containsExactly(15UL..19UL, 40UL..45UL) diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/BinarySearchCursorTest.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/BinarySearchCursorTest.kt index 108a9580..9f4a2d68 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/BinarySearchCursorTest.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/BinarySearchCursorTest.kt @@ -14,7 +14,7 @@ class BinarySearchCursorTest { 20UL..29UL, 30UL..39UL, 40UL..49UL, - 50UL..50UL + 50UL..50UL, ) assertThat(rangeChunks(0uL, 45uL, 10)).containsExactly( @@ -22,7 +22,7 @@ class BinarySearchCursorTest { 10UL..19UL, 20UL..29UL, 30UL..39UL, - 40UL..45UL + 40UL..45UL, ) } @@ -32,22 +32,22 @@ class BinarySearchCursorTest { BinarySearchCursor( from = 1uL, to = 100uL, - chunkSize = 10 - ).next(searchDirection = null) + chunkSize = 10, + ).next(searchDirection = null), ).isEqualTo(41UL to 50UL) assertThat( BinarySearchCursor( from = 1uL, to = 100uL, - chunkSize = 10 - ).next(searchDirection = SearchDirection.FORWARD) + chunkSize = 10, + ).next(searchDirection = SearchDirection.FORWARD), ).isEqualTo(41UL to 50UL) assertThat( BinarySearchCursor( from = 1uL, to = 100uL, - chunkSize = 10 - ).next(searchDirection = SearchDirection.BACKWARD) + chunkSize = 10, + ).next(searchDirection = SearchDirection.BACKWARD), ).isEqualTo(41UL to 50UL) } @@ -110,7 +110,7 @@ class BinarySearchCursorTest { 61UL to 70UL, 71UL to 80UL, 81UL to 90UL, - 91UL to 100UL + 91UL to 100UL, ) } diff --git a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursorTest.kt b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursorTest.kt index 03c4a553..ea533401 100644 --- a/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursorTest.kt +++ b/jvm-libs/linea/clients/eth-logs-searcher/src/test/kotlin/linea/ethapi/cursor/ConsecutiveSearchCursorTest.kt @@ -22,7 +22,7 @@ class ConsecutiveSearchCursorTest { 20uL..29uL, 30uL..39uL, 40uL..49uL, - 50uL..55uL + 50uL..55uL, ) } @@ -41,7 +41,7 @@ class ConsecutiveSearchCursorTest { 30uL..39uL, 20uL..29uL, 10uL..19uL, - 0uL..9uL + 0uL..9uL, ) } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/EthLogsSearcher.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/EthLogsSearcher.kt index 7c897ffc..c5bde209 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/EthLogsSearcher.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/EthLogsSearcher.kt @@ -9,7 +9,7 @@ import kotlin.time.Duration enum class SearchDirection { FORWARD, - BACKWARD + BACKWARD, } interface EthLogsSearcher : EthLogsClient { @@ -24,13 +24,13 @@ interface EthLogsSearcher : EthLogsClient { chunkSize: Int = 1000, address: String, topics: List, - shallContinueToSearch: (EthLog) -> SearchDirection? // null means stop searching + shallContinueToSearch: (EthLog) -> SearchDirection?, // null means stop searching ): SafeFuture data class LogSearchResult( val logs: List, override val startBlockNumber: ULong, - override val endBlockNumber: ULong + override val endBlockNumber: ULong, ) : BlockInterval { val isEmpty: Boolean = logs.isEmpty() } @@ -46,6 +46,6 @@ interface EthLogsSearcher : EthLogsClient { topics: List, chunkSize: UInt = 1000u, searchTimeout: Duration, - stopAfterTargetLogsCount: UInt? = null + stopAfterTargetLogsCount: UInt? = null, ): SafeFuture } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/ContractInitializedEvent.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/ContractInitializedEvent.kt index f754be20..b8c286d6 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/ContractInitializedEvent.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/ContractInitializedEvent.kt @@ -12,9 +12,9 @@ data class ContractInitializedEvent(val version: UInt) { fun fromEthLog(ethLog: EthLog): EthLogEvent { return EthLogEvent( event = ContractInitializedEvent( - version = ethLog.data.sliceOf32(sliceNumber = 0).toULongFromLast8Bytes().toUInt() + version = ethLog.data.sliceOf32(sliceNumber = 0).toULongFromLast8Bytes().toUInt(), ), - log = ethLog + log = ethLog, ) } } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1L2MessageHashesAddedToInboxEvent.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1L2MessageHashesAddedToInboxEvent.kt index bf120eec..1330ad61 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1L2MessageHashesAddedToInboxEvent.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1L2MessageHashesAddedToInboxEvent.kt @@ -1,7 +1,7 @@ package linea.contract.events data class L1L2MessageHashesAddedToInboxEvent( - val messageHashesRlpEncoded: ByteArray + val messageHashesRlpEncoded: ByteArray, ) { companion object { const val topic = "0x9995fb3da0c2de4012f2b814b6fc29ce7507571dcb20b8d0bd38621a842df1eb" diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1RollingHashUpdatedEvent.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1RollingHashUpdatedEvent.kt index b1207916..8715b014 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1RollingHashUpdatedEvent.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L1RollingHashUpdatedEvent.kt @@ -16,7 +16,7 @@ event RollingHashUpdated(uint256 indexed messageNumber, bytes32 indexed rollingH data class L1RollingHashUpdatedEvent( val messageNumber: ULong, // Unique indexed message number for the message val rollingHash: ByteArray, // Rolling hash computed for the current message number - val messageHash: ByteArray // Hash of the message parameters + val messageHash: ByteArray, // Hash of the message parameters ) { companion object { @@ -27,9 +27,9 @@ data class L1RollingHashUpdatedEvent( event = L1RollingHashUpdatedEvent( messageNumber = ethLog.topics[1].toULongFromLast8Bytes(), rollingHash = ethLog.topics[2], - messageHash = ethLog.topics[3] + messageHash = ethLog.topics[3], ), - log = ethLog + log = ethLog, ) } } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L2RollingHashUpdatedEvent.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L2RollingHashUpdatedEvent.kt index 633b1f10..4a694ba1 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L2RollingHashUpdatedEvent.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/L2RollingHashUpdatedEvent.kt @@ -15,7 +15,7 @@ event RollingHashUpdated(uint256 indexed messageNumber, bytes32 indexed rollingH data class L2RollingHashUpdatedEvent( val messageNumber: ULong, // Unique L1 computed indexed message number for the message - val rollingHash: ByteArray // L1 rolling hash computed for the current message number + val rollingHash: ByteArray, // L1 rolling hash computed for the current message number ) { companion object { @@ -25,9 +25,9 @@ data class L2RollingHashUpdatedEvent( return EthLogEvent( event = L2RollingHashUpdatedEvent( messageNumber = ethLog.topics[1].toULongFromLast8Bytes(), - rollingHash = ethLog.topics[2] + rollingHash = ethLog.topics[2], ), - log = ethLog + log = ethLog, ) } } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/MessageSentEvent.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/MessageSentEvent.kt index 34ffceb6..8eaefb84 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/MessageSentEvent.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/events/MessageSentEvent.kt @@ -34,7 +34,7 @@ data class MessageSentEvent( val fee: BigInteger, // Fee paid in Wei val value: BigInteger, // Value sent in Wei val calldata: ByteArray, // Calldata passed to the recipient - val messageHash: ByteArray // Hash of the message parameters + val messageHash: ByteArray, // Hash of the message parameters ) : Comparable { companion object { const val topic = "0xe856c2b8bd4eb0027ce32eeaf595c21b0b6b4644b326e5b7bd80a1cf8db72e6c" @@ -48,9 +48,9 @@ data class MessageSentEvent( fee = BigInteger(ethLog.data.sliceOf32(sliceNumber = 0)), value = BigInteger(ethLog.data.sliceOf32(sliceNumber = 1)), calldata = ethLog.data.sliceArray(32 * 3..ethLog.data.size - 1), - messageHash = ethLog.topics[3] + messageHash = ethLog.topics[3], ), - log = ethLog + log = ethLog, ) } } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l1/LineaRollupSmartContractClient.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l1/LineaRollupSmartContractClient.kt index 105cf979..d83fc473 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l1/LineaRollupSmartContractClient.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l1/LineaRollupSmartContractClient.kt @@ -4,7 +4,7 @@ import linea.domain.BlockParameter import tech.pegasys.teku.infrastructure.async.SafeFuture enum class LineaContractVersion : Comparable { - V6 // more efficient data submission and new events for state recovery + V6, // more efficient data submission and new events for state recovery } interface LineaRollupSmartContractClientReadOnly : ContractVersionProvider { @@ -23,7 +23,7 @@ interface LineaRollupSmartContractClientReadOnly : ContractVersionProvider /** @@ -33,7 +33,7 @@ interface LineaRollupSmartContractClientReadOnly : ContractVersionProvider /** @@ -41,6 +41,6 @@ interface LineaRollupSmartContractClientReadOnly : ContractVersionProvider } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l2/L2MessageServiceSmartContractClient.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l2/L2MessageServiceSmartContractClient.kt index c380d00f..6cb558b9 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l2/L2MessageServiceSmartContractClient.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/contract/l2/L2MessageServiceSmartContractClient.kt @@ -5,7 +5,7 @@ import linea.domain.BlockParameter import tech.pegasys.teku.infrastructure.async.SafeFuture enum class L2MessageServiceSmartContractVersion : Comparable { - V1 // initial version + V1, // initial version } interface L2MessageServiceSmartContractClientReadOnly : ContractVersionProvider { @@ -14,7 +14,7 @@ interface L2MessageServiceSmartContractClientReadOnly : ContractVersionProvider< fun getLastAnchoredL1MessageNumber(block: BlockParameter): SafeFuture fun getRollingHashByL1MessageNumber( block: BlockParameter, - l1MessageNumber: ULong + l1MessageNumber: ULong, ): SafeFuture } @@ -45,6 +45,6 @@ interface L2MessageServiceSmartContractClient : L2MessageServiceSmartContractCli messageHashes: List, startingMessageNumber: ULong, finalMessageNumber: ULong, - finalRollingHash: ByteArray + finalRollingHash: ByteArray, ): SafeFuture } diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthApiClient.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthApiClient.kt index 555cf2da..1bddc01a 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthApiClient.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthApiClient.kt @@ -7,11 +7,11 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface EthApiClient : EthLogsClient { fun findBlockByNumber( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture fun getBlockByNumber( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { return findBlockByNumber(blockParameter).thenApply { block -> block ?: throw IllegalArgumentException("block=$blockParameter not found!") @@ -19,11 +19,11 @@ interface EthApiClient : EthLogsClient { } fun findBlockByNumberWithoutTransactionsData( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture fun getBlockByNumberWithoutTransactionsData( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { return findBlockByNumberWithoutTransactionsData(blockParameter).thenApply { block -> block ?: throw IllegalArgumentException("block=$blockParameter not found!") diff --git a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthLogsClient.kt b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthLogsClient.kt index a51d4f6c..8e822388 100644 --- a/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthLogsClient.kt +++ b/jvm-libs/linea/clients/interfaces/src/main/kotlin/linea/ethapi/EthLogsClient.kt @@ -9,6 +9,6 @@ interface EthLogsClient { fromBlock: BlockParameter, toBlock: BlockParameter, address: String, - topics: List + topics: List, ): SafeFuture> } diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L1RollingHashUpdatedEventTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L1RollingHashUpdatedEventTest.kt index 167f406f..4da2ea3f 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L1RollingHashUpdatedEventTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L1RollingHashUpdatedEventTest.kt @@ -25,8 +25,8 @@ class L1RollingHashUpdatedEventTest { "0xea3b023b4c8680d4b4824f0143132c95476359a2bb70a81d6c5a36f6918f6339".decodeHex(), "0x00000000000000000000000000000000000000000000000000000000000b415a".decodeHex(), "0x7abd5eea8cbb46bba0aa83369dcc0d9b18931a825b73f45d98da586070eafa8b".decodeHex(), - "0x24dca2d33621322ef7c85d7cea38b673c06cbb86a7f15c8aa5f658485f932fd0".decodeHex() - ) + "0x24dca2d33621322ef7c85d7cea38b673c06cbb86a7f15c8aa5f658485f932fd0".decodeHex(), + ), ) // When @@ -36,11 +36,11 @@ class L1RollingHashUpdatedEventTest { val expectedEvent = L1RollingHashUpdatedEvent( messageNumber = 0xB415A.toULong(), rollingHash = "0x7abd5eea8cbb46bba0aa83369dcc0d9b18931a825b73f45d98da586070eafa8b".decodeHex(), - messageHash = "0x24dca2d33621322ef7c85d7cea38b673c06cbb86a7f15c8aa5f658485f932fd0".decodeHex() + messageHash = "0x24dca2d33621322ef7c85d7cea38b673c06cbb86a7f15c8aa5f658485f932fd0".decodeHex(), ) val expectedEthLogEvent = EthLogEvent( event = expectedEvent, - log = ethLog + log = ethLog, ) Assertions.assertThat(result).isEqualTo(expectedEthLogEvent) diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L2RollingHashUpdatedEventTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L2RollingHashUpdatedEventTest.kt index ad83d044..b7006ed4 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L2RollingHashUpdatedEventTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/L2RollingHashUpdatedEventTest.kt @@ -23,8 +23,8 @@ class L2RollingHashUpdatedEventTest { topics = listOf( "0x99b65a4301b38c09fb6a5f27052d73e8372bbe8f6779d678bfe8a41b66cce7ac".decodeHex(), "0x00000000000000000000000000000000000000000000000000000000000b415e".decodeHex(), - "0x3444eb64c4a09587c01e9102c567e34f9fc9a6a367c2c5abad5a57dbf1df98de".decodeHex() - ) + "0x3444eb64c4a09587c01e9102c567e34f9fc9a6a367c2c5abad5a57dbf1df98de".decodeHex(), + ), ) // When @@ -33,11 +33,11 @@ class L2RollingHashUpdatedEventTest { // Then val expectedEvent = L2RollingHashUpdatedEvent( messageNumber = 0xB415E.toULong(), - rollingHash = "0x3444eb64c4a09587c01e9102c567e34f9fc9a6a367c2c5abad5a57dbf1df98de".decodeHex() + rollingHash = "0x3444eb64c4a09587c01e9102c567e34f9fc9a6a367c2c5abad5a57dbf1df98de".decodeHex(), ) val expectedEthLogEvent = EthLogEvent( event = expectedEvent, - log = ethLog + log = ethLog, ) Assertions.assertThat(result).isEqualTo(expectedEthLogEvent) diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/MessageSentEventTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/MessageSentEventTest.kt index c1532f88..ddda1865 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/MessageSentEventTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/events/MessageSentEventTest.kt @@ -59,8 +59,8 @@ class MessageSentEventTest { "0xe856c2b8bd4eb0027ce32eeaf595c21b0b6b4644b326e5b7bd80a1cf8db72e6c".decodeHex(), "0x00000000000000000000000017e764ba16c95815ca06fb5d174f08d842e340df".decodeHex(), // from "0x0000000000000000000000007a98052d4be677df72ede5a3f2829c893d10388d".decodeHex(), // to - "0x6011e7f01aae0e2cd2650cbe229a330f93821d5ed8a2e8830d1e64ba3c76cc3f".decodeHex() // messageHash - ) + "0x6011e7f01aae0e2cd2650cbe229a330f93821d5ed8a2e8830d1e64ba3c76cc3f".decodeHex(), // messageHash + ), ) // When @@ -74,11 +74,11 @@ class MessageSentEventTest { fee = BigInteger("2386f26fc10000", 16), value = BigInteger("de0b6b3a7640000", 16), calldata = "0x$callData".decodeHex(), - messageHash = "0x6011e7f01aae0e2cd2650cbe229a330f93821d5ed8a2e8830d1e64ba3c76cc3f".decodeHex() + messageHash = "0x6011e7f01aae0e2cd2650cbe229a330f93821d5ed8a2e8830d1e64ba3c76cc3f".decodeHex(), ) val expectedEthLogEvent = EthLogEvent( event = expectedEvent, - log = ethLog + log = ethLog, ) assertThat(result).isEqualTo(expectedEthLogEvent) @@ -91,7 +91,7 @@ class MessageSentEventTest { fee = 0uL.toBigInteger(), value = 0uL.toBigInteger(), calldata = ByteArray(0), - messageHash = "0x0000000000000000000000000000000000000000".decodeHex() + messageHash = "0x0000000000000000000000000000000000000000".decodeHex(), ) @Test diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/l2/FakeL2MessageServiceTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/l2/FakeL2MessageServiceTest.kt index 299b14fa..d0429717 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/l2/FakeL2MessageServiceTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/contract/l2/FakeL2MessageServiceTest.kt @@ -14,7 +14,7 @@ class FakeL2MessageServiceTest { private val testMessageHashes = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), - "0x3333333333333333333333333333333333333333333333333333333333333333".decodeHex() + "0x3333333333333333333333333333333333333333333333333333333333333333".decodeHex(), ) @BeforeEach @@ -41,7 +41,7 @@ class FakeL2MessageServiceTest { messageHashes = testMessageHashes, startingMessageNumber = 1UL, finalMessageNumber = 3UL, - finalRollingHash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".decodeHex() + finalRollingHash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".decodeHex(), ).get() .also { txHash -> val lastMessageNumber = fakeL2MessageService.getLastAnchoredL1MessageNumber(BlockParameter.Tag.LATEST).get() @@ -58,11 +58,11 @@ class FakeL2MessageServiceTest { fakeL2MessageService.anchorL1L2MessageHashes( messageHashes = listOf( "0x4444444444444444444444444444444444444444444444444444444444444444".decodeHex(), - "0x5555555555555555555555555555555555555555555555555555555555555555".decodeHex() + "0x5555555555555555555555555555555555555555555555555555555555555555".decodeHex(), ), startingMessageNumber = 4UL, finalMessageNumber = 5UL, - finalRollingHash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaB".decodeHex() + finalRollingHash = "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaB".decodeHex(), ).get() .also { txHash -> val lastMessageNumber = fakeL2MessageService.getLastAnchoredL1MessageNumber(BlockParameter.Tag.LATEST).get() @@ -72,7 +72,7 @@ class FakeL2MessageServiceTest { assertThat(txHash).isNotEmpty() assertThat(lastMessageNumber).isEqualTo(5UL) assertThat(lastRollingHash).isEqualTo( - "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaB".decodeHex() + "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaB".decodeHex(), ) assertThat(anchoredMessages.map { it.encodeHex() }).isEqualTo( listOf( @@ -80,8 +80,8 @@ class FakeL2MessageServiceTest { "0x2222222222222222222222222222222222222222222222222222222222222222", "0x3333333333333333333333333333333333333333333333333333333333333333", "0x4444444444444444444444444444444444444444444444444444444444444444", - "0x5555555555555555555555555555555555555555555555555555555555555555" - ) + "0x5555555555555555555555555555555555555555555555555555555555555555", + ), ) } } diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/FakeEthApiClientTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/FakeEthApiClientTest.kt index 0c89cc0a..3eebab78 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/FakeEthApiClientTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/FakeEthApiClientTest.kt @@ -22,26 +22,26 @@ class FakeEthApiClientTest { transactionIndex = 0UL, logIndex = 0UL, blockHash = "0xabcdefabcdefabcdefabcdefabcdefabcdefabcdef".decodeHex(), - removed = false + removed = false, ) private val initialLogs = listOf( templateLog.copy( blockNumber = 100UL, - topics = listOf(testTopic1.decodeHex(), testTopic2.decodeHex()) + topics = listOf(testTopic1.decodeHex(), testTopic2.decodeHex()), ), templateLog.copy( blockNumber = 200UL, - topics = listOf(testTopic1.decodeHex()) + topics = listOf(testTopic1.decodeHex()), ), templateLog.copy( blockNumber = 250UL, - topics = listOf(testTopic2.decodeHex()) + topics = listOf(testTopic2.decodeHex()), ), templateLog.copy( blockNumber = 300UL, address = "0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb01".decodeHex(), - topics = listOf(testTopic2.decodeHex()) - ) + topics = listOf(testTopic2.decodeHex()), + ), ) @BeforeEach @@ -55,7 +55,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 300UL.toBlockParameter(), address = testAddress, - emptyList() + emptyList(), ).get() assertThat(logs).isEqualTo(initialLogs.take(3)) @@ -67,7 +67,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 200UL.toBlockParameter(), address = testAddress, - emptyList() + emptyList(), ).get() assertThat(logs).isEqualTo(initialLogs.take(2)) @@ -79,7 +79,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 300UL.toBlockParameter(), address = testAddress, - listOf(testTopic1) + listOf(testTopic1), ).get() .also { logs -> assertThat(logs).isEqualTo(initialLogs.take(2)) @@ -89,7 +89,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 300UL.toBlockParameter(), address = testAddress, - listOf(null, testTopic2) + listOf(null, testTopic2), ).get() .also { logs -> assertThat(logs).isEqualTo(listOf(initialLogs[0])) @@ -102,7 +102,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 300UL.toBlockParameter(), address = testAddress, - listOf("0x3333333333333333333333333333333333333333333333333333333333333333") + listOf("0x3333333333333333333333333333333333333333333333333333333333333333"), ).get() assertThat(logs).isEmpty() @@ -114,7 +114,7 @@ class FakeEthApiClientTest { fromBlock = 0UL.toBlockParameter(), toBlock = 300UL.toBlockParameter(), address = testAddress, - listOf(null) + listOf(null), ).get() assertThat(logs).isEqualTo(initialLogs.take(3)) @@ -128,8 +128,8 @@ class FakeEthApiClientTest { BlockParameter.Tag.FINALIZED to 100UL, BlockParameter.Tag.SAFE to 110UL, BlockParameter.Tag.LATEST to 120UL, - BlockParameter.Tag.PENDING to 121UL - ) + BlockParameter.Tag.PENDING to 121UL, + ), ).also { client -> client.setFinalizedBlockTag(500UL) assertThat(client.getBlockByNumber(BlockParameter.Tag.LATEST).get().number).isEqualTo(500UL) @@ -151,8 +151,8 @@ class FakeEthApiClientTest { BlockParameter.Tag.FINALIZED to 100UL, BlockParameter.Tag.SAFE to 110UL, BlockParameter.Tag.LATEST to 120UL, - BlockParameter.Tag.PENDING to 121UL - ) + BlockParameter.Tag.PENDING to 121UL, + ), ).also { client -> client.setSafeBlockTag(500UL) assertThat(client.getBlockByNumber(BlockParameter.Tag.LATEST).get().number).isEqualTo(500UL) @@ -175,8 +175,8 @@ class FakeEthApiClientTest { BlockParameter.Tag.FINALIZED to 100UL, BlockParameter.Tag.SAFE to 110UL, BlockParameter.Tag.LATEST to 120UL, - BlockParameter.Tag.PENDING to 121UL - ) + BlockParameter.Tag.PENDING to 121UL, + ), ).also { client -> client.setLatestBlockTag(500UL) assertThat(client.getBlockByNumber(BlockParameter.Tag.LATEST).get().number).isEqualTo(500UL) diff --git a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/TopicsFilterTest.kt b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/TopicsFilterTest.kt index ba4e4132..a41aea25 100644 --- a/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/TopicsFilterTest.kt +++ b/jvm-libs/linea/clients/interfaces/src/test/kotlin/linea/ethapi/TopicsFilterTest.kt @@ -10,11 +10,11 @@ class TopicsFilterTest { fun `should return true when all topics match`() { val logTopics = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val topicsFilter = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val result = FakeEthApiClient.matchesTopicFilter(logTopics, topicsFilter) @@ -27,11 +27,11 @@ class TopicsFilterTest { val logTopics = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), - "0x3333333333333333333333333333333333333333333333333333333333333333".decodeHex() + "0x3333333333333333333333333333333333333333333333333333333333333333".decodeHex(), ) val topicsFilter = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val result = FakeEthApiClient.matchesTopicFilter(logTopics, topicsFilter) @@ -43,11 +43,11 @@ class TopicsFilterTest { fun `should return true when topics filter contains null (wildcard)`() { val logTopics = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val topicsFilter = listOf( null, - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val result = FakeEthApiClient.matchesTopicFilter(logTopics, topicsFilter) @@ -59,11 +59,11 @@ class TopicsFilterTest { fun `should return false when topics do not match`() { val logTopics = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val topicsFilter = listOf( "0x3333333333333333333333333333333333333333333333333333333333333333".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val result = FakeEthApiClient.matchesTopicFilter(logTopics, topicsFilter) @@ -75,7 +75,7 @@ class TopicsFilterTest { fun `should return true when topics filter is empty`() { val logTopics = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val topicsFilter = emptyList() @@ -87,11 +87,11 @@ class TopicsFilterTest { @Test fun `should return false when log topics are fewer than topics filter`() { val logTopics = listOf( - "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex() + "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), ) val topicsFilter = listOf( "0x1111111111111111111111111111111111111111111111111111111111111111".decodeHex(), - "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex() + "0x2222222222222222222222222222222222222222222222222222222222222222".decodeHex(), ) val result = FakeEthApiClient.matchesTopicFilter(logTopics, topicsFilter) diff --git a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contract/l2/FakeL2MessageService.kt b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contract/l2/FakeL2MessageService.kt index d35340b7..096ce2eb 100644 --- a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contract/l2/FakeL2MessageService.kt +++ b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contract/l2/FakeL2MessageService.kt @@ -8,7 +8,7 @@ import kotlin.random.Random class FakeL2MessageService( val contractAddress: String = Random.nextBytes(20).encodeHex(), val contractDeployBlock: ULong = 0uL, - var contractVersion: L2MessageServiceSmartContractVersion = L2MessageServiceSmartContractVersion.V1 + var contractVersion: L2MessageServiceSmartContractVersion = L2MessageServiceSmartContractVersion.V1, ) : L2MessageServiceSmartContractClient { private val anchoredMessageHashes: MutableList = mutableListOf() private val anchoredMessageRollingHashes: MutableMap = mutableMapOf() @@ -29,7 +29,7 @@ class FakeL2MessageService( @Synchronized fun setLastAnchoredL1Message( l1MessageNumber: ULong, - rollingHash: ByteArray + rollingHash: ByteArray, ) { this.anchoredMessageRollingHashes[l1MessageNumber] = rollingHash this.lastAnchoredL1MessageNumber = l1MessageNumber @@ -41,7 +41,7 @@ class FakeL2MessageService( messageHashes: List, startingMessageNumber: ULong, finalMessageNumber: ULong, - finalRollingHash: ByteArray + finalRollingHash: ByteArray, ): SafeFuture { require(startingMessageNumber == lastAnchoredL1MessageNumber + 1UL) { "startingMessageNumber=$startingMessageNumber must be equal to " + diff --git a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contrat/events/ModelsFactory.kt b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contrat/events/ModelsFactory.kt index de355cfe..51a7c16d 100644 --- a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contrat/events/ModelsFactory.kt +++ b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/contrat/events/ModelsFactory.kt @@ -22,7 +22,7 @@ fun createMessageSentEthLogV1( value: ULong = 2_000UL, messageNumber: ULong = 10_000UL, calldata: ByteArray = "deadbeef".decodeHex(), - messageHash: ByteArray = Random.nextBytes(32) + messageHash: ByteArray = Random.nextBytes(32), ): EthLog { return EthLog( removed = false, @@ -43,8 +43,8 @@ fun createMessageSentEthLogV1( MessageSentEvent.topic.decodeHex(), from.decodeHex().padLeft(32), // from to.decodeHex().padLeft(32), // to - messageHash // messageHash - ) + messageHash, // messageHash + ), ) } @@ -57,7 +57,7 @@ fun createL1RollingHashUpdatedEthLogV1( rollingHash: ByteArray = Random.nextBytes(32), messageHash: ByteArray = Random.nextBytes(32), transactionHash: ByteArray = Random.nextBytes(32), - blockHash: ByteArray = Random.nextBytes(32) + blockHash: ByteArray = Random.nextBytes(32), ): EthLog { return EthLog( removed = false, @@ -72,14 +72,14 @@ fun createL1RollingHashUpdatedEthLogV1( L1RollingHashUpdatedEvent.topic.decodeHex(), // topic is static messageNumber.toHexStringUInt256().decodeHex(), rollingHash, - messageHash - ) + messageHash, + ), ) } data class L1MessageSentV1EthLogs( val messageSent: EthLogEvent, - val l1RollingHashUpdated: EthLogEvent + val l1RollingHashUpdated: EthLogEvent, ) fun createL1MessageSentV1Logs( @@ -94,7 +94,7 @@ fun createL1MessageSentV1Logs( messageNumber: ULong = 10_000UL, calldata: ByteArray = "deadbeef".decodeHex(), messageHash: ByteArray, - rollingHash: ByteArray + rollingHash: ByteArray, ): L1MessageSentV1EthLogs { val l1RollingHashUpdated = createL1RollingHashUpdatedEthLogV1( blockNumber = blockNumber, @@ -103,7 +103,7 @@ fun createL1MessageSentV1Logs( contractAddress = contractAddress, messageNumber = messageNumber, rollingHash = rollingHash, - messageHash = messageHash + messageHash = messageHash, ) val messageSent = createMessageSentEthLogV1( blockNumber = blockNumber, @@ -116,12 +116,12 @@ fun createL1MessageSentV1Logs( value = value, messageNumber = messageNumber, calldata = calldata, - messageHash = messageHash + messageHash = messageHash, ) return L1MessageSentV1EthLogs( messageSent = MessageSentEvent.fromEthLog(messageSent), - l1RollingHashUpdated = L1RollingHashUpdatedEvent.fromEthLog(l1RollingHashUpdated) + l1RollingHashUpdated = L1RollingHashUpdatedEvent.fromEthLog(l1RollingHashUpdated), ) } @@ -133,7 +133,7 @@ fun createL2RollingHashUpdatedEthLogV1( messageNumber: ULong = 10_000UL, rollingHash: ByteArray = Random.nextBytes(32), transactionHash: ByteArray = Random.nextBytes(32), - blockHash: ByteArray = Random.nextBytes(32) + blockHash: ByteArray = Random.nextBytes(32), ): EthLog { return EthLog( removed = false, @@ -147,7 +147,7 @@ fun createL2RollingHashUpdatedEthLogV1( topics = listOf( L2RollingHashUpdatedEvent.topic.decodeHex(), // topic is static messageNumber.toHexStringUInt256().decodeHex(), - rollingHash - ) + rollingHash, + ), ) } diff --git a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/ethapi/FakeEthApiClient.kt b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/ethapi/FakeEthApiClient.kt index 78dd6883..d0577496 100644 --- a/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/ethapi/FakeEthApiClient.kt +++ b/jvm-libs/linea/clients/interfaces/src/testFixtures/kotlin/linea/ethapi/FakeEthApiClient.kt @@ -24,10 +24,10 @@ class FakeEthApiClient( BlockParameter.Tag.LATEST to 0UL, BlockParameter.Tag.SAFE to 0UL, BlockParameter.Tag.FINALIZED to 0UL, - BlockParameter.Tag.PENDING to 0UL + BlockParameter.Tag.PENDING to 0UL, ), private val topicsTranslation: Map = emptyMap(), - private val log: Logger = LogManager.getLogger(FakeEthApiClient::class.java) + private val log: Logger = LogManager.getLogger(FakeEthApiClient::class.java), ) : EthApiClient { private val blockTags: MutableMap = initialTagsBlocks.toMutableMap() private val logsDb: MutableList = mutableListOf() @@ -66,7 +66,7 @@ class FakeEthApiClient( blockTags[BlockParameter.Tag.LATEST] = blockNumber coerceTagsAtMostTo( listOf(BlockParameter.Tag.FINALIZED, BlockParameter.Tag.SAFE, BlockParameter.Tag.PENDING), - blockNumber + blockNumber, ) } @@ -76,11 +76,11 @@ class FakeEthApiClient( coerceTagsAtLeastTo( listOf(BlockParameter.Tag.LATEST, BlockParameter.Tag.PENDING), - blockNumber + blockNumber, ) coerceTagsAtMostTo( listOf(BlockParameter.Tag.FINALIZED), - blockNumber + blockNumber, ) } @@ -90,7 +90,7 @@ class FakeEthApiClient( coerceTagsAtLeastTo( listOf(BlockParameter.Tag.SAFE, BlockParameter.Tag.LATEST, BlockParameter.Tag.PENDING), - blockNumber + blockNumber, ) } @@ -126,7 +126,7 @@ class FakeEthApiClient( } override fun findBlockByNumberWithoutTransactionsData( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { return findBlockByNumber(blockParameter).thenApply { block -> block?.toBlockWithRandomTxHashes() } } @@ -136,14 +136,14 @@ class FakeEthApiClient( } private fun generateFakeBlock( - blockNumber: ULong + blockNumber: ULong, ): Block { val parentBlock = blocksDb[blockNumber - 1UL] val timestamp = genesisTimestamp + (blockTime * blockNumber.toInt()) return createBlock( number = blockNumber, parentHash = parentBlock?.hash ?: Random.nextBytes(32), - timestamp = timestamp + timestamp = timestamp, ) } @@ -152,7 +152,7 @@ class FakeEthApiClient( fromBlock: BlockParameter, toBlock: BlockParameter, address: String, - topics: List + topics: List, ): SafeFuture> { val addressBytes = address.decodeHex() val topicsFilter = topics.map { it?.decodeHex() } @@ -167,7 +167,7 @@ class FakeEthApiClient( .let { logsMatching -> log.trace( "logDb: {}", - logsDb.joinToString(prefix = "\n ", separator = "\n ") { log -> log.toString() } + logsDb.joinToString(prefix = "\n ", separator = "\n ") { log -> log.toString() }, ) log.debug( "getLogs: {}..{} address={} topics={} logsSize={} logs={}", @@ -176,7 +176,7 @@ class FakeEthApiClient( address, topics.joinToString(", ") { t -> t?.let { topicsTranslation[t] ?: t } ?: "null" }, logsMatching.size, - logsMatching.joinToString(prefix = "\n ", separator = "\n ") { log -> log.toString() } + logsMatching.joinToString(prefix = "\n ", separator = "\n ") { log -> log.toString() }, ) SafeFuture.completedFuture(logsMatching) } @@ -184,7 +184,7 @@ class FakeEthApiClient( private fun findLogsInRange( fromBlock: BlockParameter, - toBlock: BlockParameter + toBlock: BlockParameter, ): List { return logsDb.filter { isInRange(it.blockNumber, fromBlock, toBlock) } } @@ -192,7 +192,7 @@ class FakeEthApiClient( private fun isInRange( blockNumber: ULong, fromBlock: BlockParameter, - toBlock: BlockParameter + toBlock: BlockParameter, ): Boolean { val fromBlockNumber: ULong = blockParameterToBlockNumber(fromBlock) val toBlockNumber: ULong = blockParameterToBlockNumber(toBlock) @@ -201,7 +201,7 @@ class FakeEthApiClient( } private fun blockParameterToBlockNumber( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): ULong { return when (blockParameter) { is BlockParameter.Tag -> blockTags[blockParameter] @@ -214,7 +214,7 @@ class FakeEthApiClient( companion object { fun matchesTopicFilter( logTopics: List, - topicsFilter: List + topicsFilter: List, ): Boolean { if (topicsFilter.size > logTopics.size) return false diff --git a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/ContractDeploymentBlockNumberProvider.kt b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/ContractDeploymentBlockNumberProvider.kt index e23b55bd..9525e613 100644 --- a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/ContractDeploymentBlockNumberProvider.kt +++ b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/ContractDeploymentBlockNumberProvider.kt @@ -11,7 +11,7 @@ import java.util.concurrent.atomic.AtomicReference typealias ContractDeploymentBlockNumberProvider = () -> SafeFuture class StaticContractDeploymentBlockNumberProvider( - private val deploymentBlockNumber: ULong + private val deploymentBlockNumber: ULong, ) : ContractDeploymentBlockNumberProvider { override fun invoke(): SafeFuture { return SafeFuture.completedFuture(deploymentBlockNumber) @@ -21,7 +21,7 @@ class StaticContractDeploymentBlockNumberProvider( class EventBasedContractDeploymentBlockNumberProvider( private val ethApiClient: EthApiClient, private val contractAddress: String, - private val log: Logger = LogManager.getLogger(EventBasedContractDeploymentBlockNumberProvider::class.java) + private val log: Logger = LogManager.getLogger(EventBasedContractDeploymentBlockNumberProvider::class.java), ) : ContractDeploymentBlockNumberProvider { private val deploymentBlockNumberCache = AtomicReference(0UL) @@ -34,7 +34,7 @@ class EventBasedContractDeploymentBlockNumberProvider( fromBlock = BlockParameter.Tag.EARLIEST, toBlock = BlockParameter.Tag.LATEST, address = contractAddress, - topics = listOf(Upgraded.topic) + topics = listOf(Upgraded.topic), ).thenApply { logs -> if (logs.isEmpty()) { throw IllegalStateException("Upgraded event not found: contractAddress=$contractAddress") @@ -47,7 +47,7 @@ class EventBasedContractDeploymentBlockNumberProvider( log.error( "Failed to get deployment block number for contract={} errorMessage={}", contractAddress, - it.message + it.message, ) } } diff --git a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/Web3JContractAsyncHelper.kt b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/Web3JContractAsyncHelper.kt index 58b909c2..d3ee1c4f 100644 --- a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/Web3JContractAsyncHelper.kt +++ b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/Web3JContractAsyncHelper.kt @@ -41,7 +41,7 @@ class Web3JContractAsyncHelper( val transactionManager: AsyncFriendlyTransactionManager, private val contractGasProvider: ContractGasProvider, private val smartContractErrors: SmartContractErrors, - private val useEthEstimateGas: Boolean + private val useEthEstimateGas: Boolean, ) { private val log: Logger = LogManager.getLogger(this::class.java) @@ -54,13 +54,13 @@ class Web3JContractAsyncHelper( private fun getGasLimit( function: Function, blobs: List? = null, - blobVersionedHashes: List? = null + blobVersionedHashes: List? = null, ): SafeFuture { return if (useEthEstimateGas) { getEthEstimatedGas( FunctionEncoder.encode(function), blobs, - blobVersionedHashes + blobVersionedHashes, ).thenApply { it ?: contractGasProvider.getGasLimit(function.name) } @@ -72,7 +72,7 @@ class Web3JContractAsyncHelper( private fun getEthEstimatedGas( encodedFunction: String, blobs: List? = null, - blobVersionedHashes: List? = null + blobVersionedHashes: List? = null, ): SafeFuture { return if (blobs != null && blobVersionedHashes != null) { createEip4844FunctionCallTransaction(encodedFunction, blobs, blobVersionedHashes) @@ -90,14 +90,14 @@ class Web3JContractAsyncHelper( "eth_estimateGas failed for tx with blobCarrying={} error={} revertReason={}", withBlobs, it.error.message, - getRevertReason(it.error, smartContractErrors) + getRevertReason(it.error, smartContractErrors), ) null } else { log.debug( "eth_estimateGas for tx with blobCarrying={} estimatedGas={}", withBlobs, - it.amountUsed + it.amountUsed, ) it.amountUsed } @@ -106,7 +106,7 @@ class Web3JContractAsyncHelper( } private fun createFunctionCallTransaction( - encodedFunction: String + encodedFunction: String, ): Transaction { return Transaction.createFunctionCallTransaction( transactionManager.fromAddress, @@ -114,14 +114,14 @@ class Web3JContractAsyncHelper( null, null, contractAddress, - encodedFunction + encodedFunction, ) } private fun createEip4844FunctionCallTransaction( encodedFunction: String, blobs: List, - blobVersionedHashes: List + blobVersionedHashes: List, ): Eip4844Transaction { return Eip4844Transaction.createFunctionCallTransaction( from = transactionManager.fromAddress, @@ -132,14 +132,14 @@ class Web3JContractAsyncHelper( maxPriorityFeePerGas = null, maxFeePerGas = null, gasLimit = null, - blobVersionedHashes = blobVersionedHashes + blobVersionedHashes = blobVersionedHashes, ) } private fun createEip4844Transaction( function: Function, blobs: List, - gasPriceCaps: GasPriceCaps? = null + gasPriceCaps: GasPriceCaps? = null, ): SafeFuture { require(blobs.size in 1..9) { "Blobs size=${blobs.size} must be between 1 and 9." } @@ -160,7 +160,7 @@ class Web3JContractAsyncHelper( maxPriorityFeePerGas = gasPriceCaps?.maxPriorityFeePerGasCap?.toBigInteger(), maxFeePerGas = gasPriceCaps?.maxFeePerGasCap?.toBigInteger(), gasLimit = gasLimit, - blobVersionedHashes = blobVersionedHashes + blobVersionedHashes = blobVersionedHashes, ) } } @@ -170,13 +170,13 @@ class Web3JContractAsyncHelper( } private fun getEip1559GasFees( - functionName: String + functionName: String, ): EIP1559GasFees { return when (contractGasProvider) { is AtomicContractEIP1559GasProvider -> contractGasProvider.getEIP1559GasFees() is ContractEIP1559GasProvider -> EIP1559GasFees( maxPriorityFeePerGas = contractGasProvider.getMaxPriorityFeePerGas(functionName).toULong(), - maxFeePerGas = contractGasProvider.getMaxFeePerGas(functionName).toULong() + maxFeePerGas = contractGasProvider.getMaxFeePerGas(functionName).toULong(), ) else -> throw UnsupportedOperationException("GasProvider does not support EIP1559!") @@ -193,7 +193,7 @@ class Web3JContractAsyncHelper( @Synchronized fun sendTransaction( function: Function, - weiValue: BigInteger + weiValue: BigInteger, ): EthSendTransaction { val encodedData = FunctionEncoder.encode(function) val sendRawTransactionResult: EthSendTransaction = @@ -207,7 +207,7 @@ class Web3JContractAsyncHelper( contractAddress, encodedData, weiValue, - false + false, ) } else { transactionManager.sendTransaction( @@ -216,7 +216,7 @@ class Web3JContractAsyncHelper( contractAddress, encodedData, weiValue, - false + false, ) } @@ -227,7 +227,7 @@ class Web3JContractAsyncHelper( function: Function, weiValue: BigInteger, gasPriceCaps: GasPriceCaps? = null, - gasLimit: BigInteger + gasLimit: BigInteger, ): CompletableFuture { val transaction = if (isGasProviderSupportedEIP1559()) { val (maxPriorityFeePerGas, maxFeePerGas) = getEip1559GasFees(function.name) @@ -237,7 +237,7 @@ class Web3JContractAsyncHelper( maxPriorityFeePerGas = maxPriorityFeePerGas, maxFeePerGas = maxFeePerGas, dynamicMaxPriorityFeePerGas = gasPriceCaps?.maxPriorityFeePerGasCap, - dynamicMaxFeePerGas = gasPriceCaps?.maxFeePerGasCap + dynamicMaxFeePerGas = gasPriceCaps?.maxFeePerGasCap, ) transactionManager.createRawTransaction( @@ -248,7 +248,7 @@ class Web3JContractAsyncHelper( gasLimit = gasLimit, to = contractAddress, value = weiValue, - data = FunctionEncoder.encode(function) + data = FunctionEncoder.encode(function), ) } else { transactionManager.createRawTransaction( @@ -256,7 +256,7 @@ class Web3JContractAsyncHelper( gasLimit = gasLimit, to = contractAddress, value = weiValue, - data = FunctionEncoder.encode(function) + data = FunctionEncoder.encode(function), ) } val signedMessage = transactionManager.sign(transaction) @@ -269,7 +269,7 @@ class Web3JContractAsyncHelper( fun sendTransactionAsync( function: Function, weiValue: BigInteger, - gasPriceCaps: GasPriceCaps? = null + gasPriceCaps: GasPriceCaps? = null, ): CompletableFuture { return getGasLimit(function) .thenCompose { gasLimit -> @@ -281,7 +281,7 @@ class Web3JContractAsyncHelper( fun sendTransactionAfterEthCallAsync( function: Function, weiValue: BigInteger, - gasPriceCaps: GasPriceCaps? = null + gasPriceCaps: GasPriceCaps? = null, ): CompletableFuture { return getGasLimit(function) .thenCompose { gasLimit -> @@ -295,7 +295,7 @@ class Web3JContractAsyncHelper( fun sendBlobCarryingTransactionAndGetTxHash( function: Function, blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { require(blobs.size in 1..9) { "Blobs size=${blobs.size} must be between 1 and 9." } return sendBlobCarryingTransaction(function, BigInteger.ZERO, blobs.toWeb3jTxBlob(), gasPriceCaps) @@ -307,7 +307,7 @@ class Web3JContractAsyncHelper( function: Function, weiValue: BigInteger, blobs: List, - gasPriceCaps: GasPriceCaps? = null + gasPriceCaps: GasPriceCaps? = null, ): SafeFuture { val blobVersionedHashes = blobs .map { BlobUtils.kzgToVersionedHash(BlobUtils.getCommitment(it)).toArray() } @@ -323,7 +323,7 @@ class Web3JContractAsyncHelper( maxFeePerBlobGas = maxFeePerBlobGas, dynamicMaxPriorityFeePerGas = gasPriceCaps?.maxPriorityFeePerGasCap, dynamicMaxFeePerGas = gasPriceCaps?.maxFeePerGasCap, - dynamicMaxFeePerBlobGas = gasPriceCaps?.maxFeePerBlobGasCap + dynamicMaxFeePerBlobGas = gasPriceCaps?.maxFeePerBlobGasCap, ) val transaction = transactionManager.createRawTransaction( @@ -336,7 +336,7 @@ class Web3JContractAsyncHelper( to = contractAddress, data = FunctionEncoder.encode(function), value = weiValue, - maxFeePerBlobGas = gasPriceCaps?.maxFeePerBlobGasCap?.toBigInteger() ?: maxFeePerBlobGas.toBigInteger() + maxFeePerBlobGas = gasPriceCaps?.maxFeePerBlobGasCap?.toBigInteger() ?: maxFeePerBlobGas.toBigInteger(), ) val signedMessage = transactionManager.sign(transaction) web3j.ethSendRawTransaction(signedMessage) @@ -347,7 +347,7 @@ class Web3JContractAsyncHelper( @Synchronized fun executeRemoteCallTransaction( function: Function, - weiValue: BigInteger + weiValue: BigInteger, ): RemoteFunctionCall { val encodedData = FunctionEncoder.encode(function) val transactionSent = sendTransaction(function, weiValue) @@ -356,14 +356,14 @@ class Web3JContractAsyncHelper( @Synchronized fun executeRemoteCallTransaction( - function: Function + function: Function, ): RemoteFunctionCall { return executeRemoteCallTransaction(function, BigInteger.ZERO) } fun executeEthCall( function: Function, - overrideGasLimit: BigInteger? = null + overrideGasLimit: BigInteger? = null, ): SafeFuture { return (overrideGasLimit?.let { SafeFuture.completedFuture(overrideGasLimit) } ?: getGasLimit(function)) .thenCompose { gasLimit -> @@ -373,7 +373,7 @@ class Web3JContractAsyncHelper( null, gasLimit, contractAddress, - FunctionEncoder.encode(function) + FunctionEncoder.encode(function), ).let { tx -> web3j.informativeEthCall(tx, smartContractErrors) } @@ -383,12 +383,12 @@ class Web3JContractAsyncHelper( fun executeBlobEthCall( function: Function, blobs: List, - gasPriceCaps: GasPriceCaps? + gasPriceCaps: GasPriceCaps?, ): SafeFuture { return createEip4844Transaction( function, blobs.toWeb3jTxBlob(), - gasPriceCaps + gasPriceCaps, ).thenCompose { tx -> web3j.informativeEthCall(tx, smartContractErrors) } @@ -401,7 +401,7 @@ class Web3JContractAsyncHelper( maxFeePerBlobGas: ULong? = null, dynamicMaxPriorityFeePerGas: ULong?, dynamicMaxFeePerGas: ULong?, - dynamicMaxFeePerBlobGas: ULong? = null + dynamicMaxFeePerBlobGas: ULong? = null, ) { val withBlob = maxFeePerBlobGas != null || dynamicMaxFeePerBlobGas != null log.info( @@ -416,7 +416,7 @@ class Web3JContractAsyncHelper( "dynamicMaxFeePerBlobGas=${dynamicMaxFeePerBlobGas?.toGWei()} GWei" } else { "" - } + }, ) } } diff --git a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l1/Web3JLineaRollupSmartContractClientReadOnly.kt b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l1/Web3JLineaRollupSmartContractClientReadOnly.kt index 68427994..3f4c0116 100644 --- a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l1/Web3JLineaRollupSmartContractClientReadOnly.kt +++ b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l1/Web3JLineaRollupSmartContractClientReadOnly.kt @@ -23,7 +23,7 @@ private val fakeCredentials = Credentials.create(ByteArray(32).encodeHex()) open class Web3JLineaRollupSmartContractClientReadOnly( val web3j: Web3j, val contractAddress: String, - private val log: Logger = LogManager.getLogger(Web3JLineaRollupSmartContractClientReadOnly::class.java) + private val log: Logger = LogManager.getLogger(Web3JLineaRollupSmartContractClientReadOnly::class.java), ) : LineaRollupSmartContractClientReadOnly { protected fun contractClientAtBlock(blockParameter: BlockParameter): LineaRollupV6 { @@ -37,7 +37,7 @@ open class Web3JLineaRollupSmartContractClientReadOnly( contractAddress, web3j, fakeCredentials, - StaticGasProvider(BigInteger.ZERO, BigInteger.ZERO) + StaticGasProvider(BigInteger.ZERO, BigInteger.ZERO), ).apply { this.setDefaultBlockParameter(blockParameter.toWeb3j()) } @@ -60,7 +60,7 @@ open class Web3JLineaRollupSmartContractClientReadOnly( log.info( "Smart contract upgraded: prevVersion={} upgradedVersion={}", smartContractVersionCache.get(), - contractLatestVersion + contractLatestVersion, ) } smartContractVersionCache.set(contractLatestVersion) @@ -118,7 +118,7 @@ open class Web3JLineaRollupSmartContractClientReadOnly( .thenCompose { version -> when (version!!) { LineaContractVersion.V6 -> contractClientAtBlock(blockParameter, LineaRollupV6::class.java).blobShnarfExists( - shnarf + shnarf, ) } .sendAsync() diff --git a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/SmartContractFunctionCallBuilders.kt b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/SmartContractFunctionCallBuilders.kt index 5a4afb79..84fa0776 100644 --- a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/SmartContractFunctionCallBuilders.kt +++ b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/SmartContractFunctionCallBuilders.kt @@ -13,19 +13,22 @@ internal fun buildAnchorL1L2MessageHashesV1( messageHashes: List, startingMessageNumber: BigInteger, finalMessageNumber: BigInteger, - finalRollingHash: ByteArray + finalRollingHash: ByteArray, ): Function { return Function( - /* name = */ FUNC_ANCHORL1L2MESSAGEHASHES, - /* inputParameters = */ listOf>( + /* name = */ + FUNC_ANCHORL1L2MESSAGEHASHES, + /* inputParameters = */ + listOf>( DynamicArray( Bytes32::class.java, - messageHashes.map { Bytes32(it) } + messageHashes.map { Bytes32(it) }, ), Uint256(startingMessageNumber), Uint256(finalMessageNumber), - Bytes32(finalRollingHash) + Bytes32(finalRollingHash), ), - /* outputParameters = */ emptyList>() + /* outputParameters = */ + emptyList>(), ) } diff --git a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/Web3JL2MessageServiceSmartContractClient.kt b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/Web3JL2MessageServiceSmartContractClient.kt index 71d52b7e..9f05422f 100644 --- a/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/Web3JL2MessageServiceSmartContractClient.kt +++ b/jvm-libs/linea/clients/linea-contract-clients/src/main/kotlin/linea/contract/l2/Web3JL2MessageServiceSmartContractClient.kt @@ -31,7 +31,7 @@ class Web3JL2MessageServiceSmartContractClient( private val contractAddress: String, private val web3jContractHelper: Web3JContractAsyncHelper, private val deploymentBlockNumberProvider: ContractDeploymentBlockNumberProvider, - private val log: Logger = LogManager.getLogger(Web3JL2MessageServiceSmartContractClient::class.java) + private val log: Logger = LogManager.getLogger(Web3JL2MessageServiceSmartContractClient::class.java), ) : L2MessageServiceSmartContractClient { companion object { fun create( @@ -43,7 +43,7 @@ class Web3JL2MessageServiceSmartContractClient( feeHistoryRewardPercentile: Double, transactionManager: AsyncFriendlyTransactionManager, smartContractErrors: SmartContractErrors, - smartContractDeploymentBlockNumber: ULong? + smartContractDeploymentBlockNumber: ULong?, ): Web3JL2MessageServiceSmartContractClient { val gasProvider = EIP1559GasProvider( web3jClient = web3jClient, @@ -51,8 +51,8 @@ class Web3JL2MessageServiceSmartContractClient( gasLimit = gasLimit, maxFeePerGasCap = maxFeePerGasCap, feeHistoryBlockCount = feeHistoryBlockCount, - feeHistoryRewardPercentile = feeHistoryRewardPercentile - ) + feeHistoryRewardPercentile = feeHistoryRewardPercentile, + ), ) val web3jContractHelper = Web3JContractAsyncHelper( contractAddress = contractAddress, @@ -60,21 +60,21 @@ class Web3JL2MessageServiceSmartContractClient( contractGasProvider = gasProvider, transactionManager = transactionManager, smartContractErrors = smartContractErrors, - useEthEstimateGas = true + useEthEstimateGas = true, ) val deploymentBlockNumberProvider = smartContractDeploymentBlockNumber ?.let { StaticContractDeploymentBlockNumberProvider(it) } ?: EventBasedContractDeploymentBlockNumberProvider( ethApiClient = Web3jEthApiClient(web3jClient), contractAddress = contractAddress, - log = LogManager.getLogger(Web3JL2MessageServiceSmartContractClient::class.java) + log = LogManager.getLogger(Web3JL2MessageServiceSmartContractClient::class.java), ) return Web3JL2MessageServiceSmartContractClient( web3j = web3jClient, contractAddress = contractAddress, web3jContractHelper = web3jContractHelper, - deploymentBlockNumberProvider = deploymentBlockNumberProvider + deploymentBlockNumberProvider = deploymentBlockNumberProvider, ) } } @@ -89,7 +89,7 @@ class Web3JL2MessageServiceSmartContractClient( contractAddress, web3j, fakeCredentials, - StaticGasProvider(BigInteger.ZERO, BigInteger.ZERO) + StaticGasProvider(BigInteger.ZERO, BigInteger.ZERO), ).apply { this.setDefaultBlockParameter(blockParameter.toWeb3j()) } @@ -111,7 +111,7 @@ class Web3JL2MessageServiceSmartContractClient( log.info( "L2 Message Service Smart contract upgraded: prevVersion={} upgradedVersion={}", smartContractVersionCache.get(), - contractLatestVersion + contractLatestVersion, ) } smartContractVersionCache.set(contractLatestVersion) @@ -142,7 +142,7 @@ class Web3JL2MessageServiceSmartContractClient( override fun getRollingHashByL1MessageNumber( block: BlockParameter, - l1MessageNumber: ULong + l1MessageNumber: ULong, ): SafeFuture { return contractClientAtBlock(block, L2MessageService::class.java) .l1RollingHashes(l1MessageNumber.toBigInteger()) @@ -153,13 +153,13 @@ class Web3JL2MessageServiceSmartContractClient( messageHashes: List, startingMessageNumber: ULong, finalMessageNumber: ULong, - finalRollingHash: ByteArray + finalRollingHash: ByteArray, ): SafeFuture { return anchorL1L2MessageHashesV2( messageHashes = messageHashes, startingMessageNumber = startingMessageNumber.toBigInteger(), finalMessageNumber = finalMessageNumber.toBigInteger(), - finalRollingHash = finalRollingHash + finalRollingHash = finalRollingHash, ) } @@ -167,20 +167,20 @@ class Web3JL2MessageServiceSmartContractClient( messageHashes: List, startingMessageNumber: BigInteger, finalMessageNumber: BigInteger, - finalRollingHash: ByteArray + finalRollingHash: ByteArray, ): SafeFuture { val function = buildAnchorL1L2MessageHashesV1( messageHashes = messageHashes, startingMessageNumber = startingMessageNumber, finalMessageNumber = finalMessageNumber, - finalRollingHash = finalRollingHash + finalRollingHash = finalRollingHash, ) return web3jContractHelper .sendTransactionAfterEthCallAsync( function = function, weiValue = BigInteger.ZERO, - gasPriceCaps = null + gasPriceCaps = null, ) .thenApply { response -> response.transactionHash diff --git a/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerClientV1.kt b/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerClientV1.kt index fbfd442e..4af0ce37 100644 --- a/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerClientV1.kt +++ b/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerClientV1.kt @@ -10,7 +10,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture enum class StateManagerErrorType : ClientError { UNKNOWN, UNSUPPORTED_VERSION, - BLOCK_MISSING_IN_CHAIN + BLOCK_MISSING_IN_CHAIN, } sealed interface StateManagerRequest : ClientRequest @@ -26,7 +26,7 @@ data class GetZkEVMStateMerkleProofResponse( val zkStateMerkleProof: ArrayNode, val zkParentStateRootHash: ByteArray, val zkEndStateRootHash: ByteArray, - val zkStateManagerVersion: String + val zkStateManagerVersion: String, ) : StateManagerResponse { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -67,7 +67,7 @@ interface StateManagerClientV1 : AsyncClient> { * @throws ClientException with errorType StateManagerErrorType when know error occurs */ fun rollupGetStateMerkleProof( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture = rollupGetStateMerkleProofWithTypedError(blockInterval) .unwrapResultMonad() @@ -76,7 +76,7 @@ interface StateManagerClientV1 : AsyncClient> { * This error typing is not really usefull anymore */ fun rollupGetStateMerkleProofWithTypedError( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture>> fun rollupGetHeadBlockNumber(): SafeFuture diff --git a/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerV1JsonRpcClient.kt b/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerV1JsonRpcClient.kt index fb56e609..dc768cb8 100644 --- a/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerV1JsonRpcClient.kt +++ b/jvm-libs/linea/clients/linea-state-manager/src/main/kotlin/build/linea/clients/StateManagerV1JsonRpcClient.kt @@ -22,7 +22,7 @@ import java.net.URI class StateManagerV1JsonRpcClient( private val rpcClient: JsonRpcV2Client, private val zkStateManagerVersion: String, - private val log: Logger = LogManager.getLogger(StateManagerV1JsonRpcClient::class.java) + private val log: Logger = LogManager.getLogger(StateManagerV1JsonRpcClient::class.java), ) : StateManagerClientV1 { companion object { @@ -32,7 +32,7 @@ class StateManagerV1JsonRpcClient( maxInflightRequestsPerClient: UInt, requestRetry: RequestRetryConfig, zkStateManagerVersion: String, - logger: Logger = LogManager.getLogger(StateManagerV1JsonRpcClient::class.java) + logger: Logger = LogManager.getLogger(StateManagerV1JsonRpcClient::class.java), ): StateManagerV1JsonRpcClient { return StateManagerV1JsonRpcClient( rpcClient = rpcClientFactory.createJsonRpcV2Client( @@ -40,9 +40,9 @@ class StateManagerV1JsonRpcClient( maxInflightRequestsPerClient = maxInflightRequestsPerClient, retryConfig = requestRetry, log = logger, - shallRetryRequestsClientBasePredicate = { it is Err } + shallRetryRequestsClientBasePredicate = { it is Err }, ), - zkStateManagerVersion = zkStateManagerVersion + zkStateManagerVersion = zkStateManagerVersion, ) } } @@ -52,7 +52,7 @@ class StateManagerV1JsonRpcClient( .makeRequest( method = "rollup_getZkEVMBlockNumber", params = emptyList(), - resultMapper = { ULong.fromHexString(it as String) } + resultMapper = { ULong.fromHexString(it as String) }, ) } @@ -64,20 +64,20 @@ class StateManagerV1JsonRpcClient( "endBlockNumber", blockInterval.endBlockNumber.toLong(), "zkStateManagerVersion", - zkStateManagerVersion - ) + zkStateManagerVersion, + ), ) return rpcClient .makeRequest( method = "rollup_getZkEVMStateMerkleProofV0", params = params, - resultMapper = ::parseZkEVMStateMerkleProofResponse + resultMapper = ::parseZkEVMStateMerkleProofResponse, ) } override fun rollupGetStateMerkleProofWithTypedError( - blockInterval: BlockInterval + blockInterval: BlockInterval, ): SafeFuture>> { return rollupGetStateMerkleProof(blockInterval) .handleComposed { result, th -> @@ -94,17 +94,17 @@ class StateManagerV1JsonRpcClient( } private fun mapErrorResponse( - jsonRpcErrorResponse: JsonRpcErrorResponseException + jsonRpcErrorResponse: JsonRpcErrorResponseException, ): ErrorResponse { val errorType = try { StateManagerErrorType.valueOf( - jsonRpcErrorResponse.rpcErrorMessage.substringBefore('-').trim() + jsonRpcErrorResponse.rpcErrorMessage.substringBefore('-').trim(), ) } catch (_: Exception) { log.error( "State manager found unrecognised JSON-RPC response error: {}", - jsonRpcErrorResponse.rpcErrorMessage + jsonRpcErrorResponse.rpcErrorMessage, ) StateManagerErrorType.UNKNOWN } @@ -113,21 +113,21 @@ class StateManagerV1JsonRpcClient( errorType, listOfNotNull( jsonRpcErrorResponse.rpcErrorMessage, - jsonRpcErrorResponse.rpcErrorData?.toString() + jsonRpcErrorResponse.rpcErrorData?.toString(), ) - .joinToString(": ") + .joinToString(": "), ) } private fun parseZkEVMStateMerkleProofResponse( - result: Any? + result: Any?, ): GetZkEVMStateMerkleProofResponse { result as JsonNode return GetZkEVMStateMerkleProofResponse( zkStateManagerVersion = result.get("zkStateManagerVersion").asText(), zkStateMerkleProof = result.get("zkStateMerkleProof") as ArrayNode, zkParentStateRootHash = result.get("zkParentStateRootHash").asText().decodeHex(), - zkEndStateRootHash = result.get("zkEndStateRootHash").asText().decodeHex() + zkEndStateRootHash = result.get("zkEndStateRootHash").asText().decodeHex(), ) } } diff --git a/jvm-libs/linea/clients/linea-state-manager/src/test/kotlin/build/linea/clients/StateManagerV1JsonRpcClientTest.kt b/jvm-libs/linea/clients/linea-state-manager/src/test/kotlin/build/linea/clients/StateManagerV1JsonRpcClientTest.kt index 82f3e405..b51aa63d 100644 --- a/jvm-libs/linea/clients/linea-state-manager/src/test/kotlin/build/linea/clients/StateManagerV1JsonRpcClientTest.kt +++ b/jvm-libs/linea/clients/linea-state-manager/src/test/kotlin/build/linea/clients/StateManagerV1JsonRpcClientTest.kt @@ -46,8 +46,8 @@ class StateManagerV1JsonRpcClientTest { .willReturn( ok() .withHeader("Content-type", "application/json") - .withBody(response.toByteArray()) - ) + .withBody(response.toByteArray()), + ), ) } @@ -65,9 +65,9 @@ class StateManagerV1JsonRpcClientTest { maxRetries = 2u, timeout = 2.seconds, 10.milliseconds, - 1u + 1u, ), - zkStateManagerVersion = "0.1.2" + zkStateManagerVersion = "0.1.2", ) } @@ -99,7 +99,7 @@ class StateManagerV1JsonRpcClientTest { "zkStateManagerVersion": "$zkStateManagerVersion" } } - """ + """, ) assertThat(stateManagerClient.rollupGetStateMerkleProofWithTypedError(BlockInterval(50UL, 100UL))) @@ -110,9 +110,9 @@ class StateManagerV1JsonRpcClientTest { zkStateManagerVersion = zkStateManagerVersion, zkStateMerkleProof = zkStateMerkleProof, zkParentStateRootHash = zkParentStateRootHash.decodeHex(), - zkEndStateRootHash = zkEndStateRootHash.decodeHex() - ) - ) + zkEndStateRootHash = zkEndStateRootHash.decodeHex(), + ), + ), ) } @@ -127,7 +127,7 @@ class StateManagerV1JsonRpcClientTest { "code":"-32600", "message":"BLOCK_MISSING_IN_CHAIN - block 1 is missing" } - }""" + }""", ) assertThat(stateManagerClient.rollupGetStateMerkleProofWithTypedError(BlockInterval(50UL, 100UL))) @@ -136,9 +136,9 @@ class StateManagerV1JsonRpcClientTest { Err( ErrorResponse( StateManagerErrorType.BLOCK_MISSING_IN_CHAIN, - "BLOCK_MISSING_IN_CHAIN - block 1 is missing" - ) - ) + "BLOCK_MISSING_IN_CHAIN - block 1 is missing", + ), + ), ) } @@ -166,9 +166,9 @@ class StateManagerV1JsonRpcClientTest { Err( ErrorResponse( StateManagerErrorType.UNSUPPORTED_VERSION, - "UNSUPPORTED_VERSION: {requestedVersion=0.1.2, supportedVersion=0.0.1-dev-3e607237}" - ) - ) + "UNSUPPORTED_VERSION: {requestedVersion=0.1.2, supportedVersion=0.0.1-dev-3e607237}", + ), + ), ) } @@ -184,13 +184,13 @@ class StateManagerV1JsonRpcClientTest { "message":"BRA_BRA_BRA_SOME_UNKNOWN_ERROR", "data": {"xyz": "1234", "abc": 100} } - }""" + }""", ) assertThat(stateManagerClient.rollupGetStateMerkleProofWithTypedError(BlockInterval(50L, 100L))) .succeedsWithin(5.seconds.toJavaDuration()) .isEqualTo( - Err(ErrorResponse(StateManagerErrorType.UNKNOWN, """BRA_BRA_BRA_SOME_UNKNOWN_ERROR: {xyz=1234, abc=100}""")) + Err(ErrorResponse(StateManagerErrorType.UNKNOWN, """BRA_BRA_BRA_SOME_UNKNOWN_ERROR: {xyz=1234, abc=100}""")), ) } diff --git a/jvm-libs/linea/core/client-interface/src/main/kotlin/build/linea/clients/Client.kt b/jvm-libs/linea/core/client-interface/src/main/kotlin/build/linea/clients/Client.kt index 6b0c3d15..12ef9e7b 100644 --- a/jvm-libs/linea/core/client-interface/src/main/kotlin/build/linea/clients/Client.kt +++ b/jvm-libs/linea/core/client-interface/src/main/kotlin/build/linea/clients/Client.kt @@ -14,7 +14,7 @@ interface ClientError class ClientException( override val message: String, - val errorType: ClientError? + val errorType: ClientError?, ) : RuntimeException(errorType?.let { "errorType=$it $message" } ?: message) diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Block.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Block.kt index c77fa291..9eab7762 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Block.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Block.kt @@ -25,7 +25,7 @@ data class BlockData( val nonce: ULong, val baseFeePerGas: ULong? = null, // Optional field for EIP-1559 blocks val transactions: List = emptyList(), // List of transaction hashes - val ommers: List = emptyList() // List of uncle block hashes + val ommers: List = emptyList(), // List of uncle block hashes ) { companion object { // companion object to allow static extension functions @@ -67,12 +67,12 @@ data class BlockData( if (nonce != other.nonce) return false if (baseFeePerGas != other.baseFeePerGas) return false if (!transactions.zip(other.transactions).all { (thisTx, otherTx) -> - when { - thisTx is ByteArray && otherTx is ByteArray -> thisTx.contentEquals(otherTx) - thisTx is Transaction && otherTx is Transaction -> thisTx == otherTx - else -> false + when { + thisTx is ByteArray && otherTx is ByteArray -> thisTx.contentEquals(otherTx) + thisTx is Transaction && otherTx is Transaction -> thisTx == otherTx + else -> false + } } - } ) { return false } @@ -144,7 +144,7 @@ data class BlockData( data class BlockHeaderSummary( val number: ULong, val hash: ByteArray, - val timestamp: Instant + val timestamp: Instant, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockInterval.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockInterval.kt index d683f977..228a89d8 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockInterval.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockInterval.kt @@ -19,14 +19,14 @@ interface BlockInterval { companion object { operator fun invoke( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): BlockInterval { return BlockIntervalData(startBlockNumber, endBlockNumber) } operator fun invoke( startBlockNumber: Number, - endBlockNumber: Number + endBlockNumber: Number, ): BlockInterval { assert(startBlockNumber.toLong() >= 0 && endBlockNumber.toLong() >= 0) { "startBlockNumber=${startBlockNumber.toLong()} and " + @@ -41,7 +41,7 @@ interface BlockInterval { */ fun between( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): BlockInterval { return BlockIntervalData(startBlockNumber, endBlockNumber) } @@ -55,7 +55,7 @@ interface BlockInterval { */ data class BlockIntervalData( override val startBlockNumber: ULong, - override val endBlockNumber: ULong + override val endBlockNumber: ULong, ) : BlockInterval { init { require(startBlockNumber <= endBlockNumber) { @@ -69,12 +69,12 @@ fun List.toBlockIntervalsString(): String { separator = ", ", prefix = "[", postfix = "]$size", - transform = BlockInterval::intervalString + transform = BlockInterval::intervalString, ) } fun List.filterOutWithEndBlockNumberBefore( - endBlockNumberInclusive: ULong + endBlockNumberInclusive: ULong, ): List { return this.filter { int -> int.endBlockNumber > endBlockNumberInclusive } } @@ -97,7 +97,7 @@ fun assertConsecutiveIntervals(intervals: List) { */ data class BlockIntervals( val startingBlockNumber: ULong, - val upperBoundaries: List + val upperBoundaries: List, ) { // This default constructor is to avoid the parse error when deserializing constructor() : this(0UL, listOf()) @@ -121,6 +121,6 @@ fun List.toBlockIntervals(): BlockIntervals { require(isNotEmpty()) { "BlockIntervals list must not be empty" } return BlockIntervals( startingBlockNumber = first().startBlockNumber, - upperBoundaries = map { it.endBlockNumber } + upperBoundaries = map { it.endBlockNumber }, ) } diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockNumberAndHash.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockNumberAndHash.kt index 21eed090..e6664650 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockNumberAndHash.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockNumberAndHash.kt @@ -4,7 +4,7 @@ import linea.kotlin.encodeHex data class BlockNumberAndHash( val number: ULong, - val hash: ByteArray + val hash: ByteArray, ) { override fun equals(other: Any?): Boolean { if (this === other) return true diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockParameter.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockParameter.kt index 6e072177..058f477b 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockParameter.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/BlockParameter.kt @@ -40,11 +40,12 @@ sealed interface BlockParameter { LATEST("latest"), EARLIEST("earliest"), SAFE("safe"), - FINALIZED("finalized"); + FINALIZED("finalized"), + ; override fun getTag(): String = value override fun getNumber(): ULong = throw UnsupportedOperationException( - "getNumber isn't supposed to be called on a block tag!" + "getNumber isn't supposed to be called on a block tag!", ) companion object { @@ -52,7 +53,7 @@ sealed interface BlockParameter { fun fromString(value: String): Tag = kotlin.runCatching { Tag.valueOf(value.uppercase()) } .getOrElse { throw IllegalArgumentException( - "BlockParameter Tag=$value is invalid. Valid values: ${Tag.entries.joinToString(", ")}" + "BlockParameter Tag=$value is invalid. Valid values: ${Tag.entries.joinToString(", ")}", ) } } diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/CommonDomainFunctions.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/CommonDomainFunctions.kt index 8839b27b..620b148e 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/CommonDomainFunctions.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/CommonDomainFunctions.kt @@ -7,7 +7,7 @@ import java.math.BigInteger object CommonDomainFunctions { fun blockIntervalString( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): String { return "[$startBlockNumber..$endBlockNumber]${endBlockNumber - startBlockNumber + 1uL}" } diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/EthLog.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/EthLog.kt index 15fcd378..abc5e64e 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/EthLog.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/EthLog.kt @@ -11,7 +11,7 @@ data class EthLog( val blockNumber: ULong, val address: ByteArray, val data: ByteArray, - val topics: List + val topics: List, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -61,7 +61,7 @@ data class EthLog( data class EthLogEvent( val event: E, - val log: EthLog + val log: EthLog, ) : Comparable> { override fun compareTo(other: EthLogEvent): Int { return when { diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/FeeHistory.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/FeeHistory.kt index 956f6400..bec912d8 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/FeeHistory.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/FeeHistory.kt @@ -6,7 +6,7 @@ data class FeeHistory( val reward: List>, val gasUsedRatio: List, val baseFeePerBlobGas: List, - val blobGasUsedRatio: List + val blobGasUsedRatio: List, ) { fun blocksRange(): ClosedRange { return oldestBlock..oldestBlock + ((reward.size - 1).toUInt()) diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/RetryConfig.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/RetryConfig.kt index 47a5216f..9470e0aa 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/RetryConfig.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/RetryConfig.kt @@ -7,7 +7,7 @@ data class RetryConfig( val maxRetries: UInt? = null, val timeout: Duration? = null, val backoffDelay: Duration = 100.milliseconds, - val failuresWarningThreshold: UInt = 0u + val failuresWarningThreshold: UInt = 0u, ) { val isRetryDisabled = maxRetries == 0u || timeout == 0.milliseconds val isRetryEnabled: Boolean = !isRetryDisabled @@ -30,12 +30,12 @@ data class RetryConfig( val noRetries = RetryConfig(maxRetries = 0u) fun endlessRetry( backoffDelay: Duration, - failuresWarningThreshold: UInt + failuresWarningThreshold: UInt, ) = RetryConfig( maxRetries = null, timeout = null, backoffDelay = backoffDelay, - failuresWarningThreshold = failuresWarningThreshold + failuresWarningThreshold = failuresWarningThreshold, ) } } diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Transaction.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Transaction.kt index 35fdc783..d82039ec 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Transaction.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/Transaction.kt @@ -9,7 +9,8 @@ enum class TransactionType(private val typeValue: Int) { ACCESS_LIST(1), EIP1559(2), BLOB(3), // Not supported by Linea atm, but here for completeness - DELEGATE_CODE(4); // Not supported by Linea atm, but here for completeness + DELEGATE_CODE(4), // Not supported by Linea atm, but here for completeness + ; val serializedType: Byte get() = typeValue.toByte() @@ -36,8 +37,8 @@ enum class TransactionType(private val typeValue: Int) { ?: throw IllegalArgumentException( String.format( "Unsupported transaction type %x", - serializedTypeValue - ) + serializedTypeValue, + ), ) } @@ -65,7 +66,7 @@ data class Transaction( val gasPrice: ULong?, // null for EIP-1559 transactions val maxFeePerGas: ULong? = null, // null for EIP-1559 transactions val maxPriorityFeePerGas: ULong? = null, // null for non EIP-1559 transactions - val accessList: List? // null non for EIP-2930 transactions + val accessList: List?, // null non for EIP-2930 transactions ) { companion object { // companion object to allow static extension functions @@ -140,7 +141,7 @@ data class Transaction( data class AccessListEntry( val address: ByteArray, - val storageKeys: List + val storageKeys: List, ) { override fun toString(): String { diff --git a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/gas/GasPriceCaps.kt b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/gas/GasPriceCaps.kt index bd1d0256..50c32ca2 100644 --- a/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/gas/GasPriceCaps.kt +++ b/jvm-libs/linea/core/domain-models/src/main/kotlin/linea/domain/gas/GasPriceCaps.kt @@ -6,7 +6,7 @@ data class GasPriceCaps( val maxPriorityFeePerGasCap: ULong, val maxFeePerGasCap: ULong, val maxFeePerBlobGasCap: ULong, - val maxBaseFeePerGasCap: ULong? = null + val maxBaseFeePerGasCap: ULong? = null, ) { override fun toString(): String { return "maxPriorityFeePerGasCap=${maxPriorityFeePerGasCap.toGWei()} GWei," + diff --git a/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/BlockIntervalsTest.kt b/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/BlockIntervalsTest.kt index 4fff9aff..40130a25 100644 --- a/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/BlockIntervalsTest.kt +++ b/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/BlockIntervalsTest.kt @@ -12,7 +12,7 @@ class BlockIntervalsTest { val expected = listOf( BlockIntervalData(11u, 21u), BlockIntervalData(22u, 27u), - BlockIntervalData(28u, 35u) + BlockIntervalData(28u, 35u), ) Assertions.assertTrue(expected == blockIntervals.toIntervalList()) } @@ -22,7 +22,7 @@ class BlockIntervalsTest { val intervals = listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(20UL, 29UL), - BlockIntervalData(10UL, 19UL) + BlockIntervalData(10UL, 19UL), ) val exception = assertThrows { @@ -39,8 +39,8 @@ class BlockIntervalsTest { listOf( BlockIntervalData(0UL, 9UL), BlockIntervalData(11UL, 19UL), - BlockIntervalData(20UL, 29UL) - ) + BlockIntervalData(20UL, 29UL), + ), ) } @@ -51,8 +51,8 @@ class BlockIntervalsTest { listOf( BlockIntervalData(0UL, 11UL), BlockIntervalData(10UL, 19UL), - BlockIntervalData(20UL, 29UL) - ) + BlockIntervalData(20UL, 29UL), + ), ) } diff --git a/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/EthLogTest.kt b/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/EthLogTest.kt index 19510efe..22d1fca8 100644 --- a/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/EthLogTest.kt +++ b/jvm-libs/linea/core/domain-models/src/test/kotlin/linea/domain/EthLogTest.kt @@ -13,7 +13,7 @@ class EthLogTest { blockNumber = 123UL, address = byteArrayOf(7, 8, 9), data = byteArrayOf(10, 11, 12), - topics = listOf(byteArrayOf(13, 14), byteArrayOf(15, 16)) + topics = listOf(byteArrayOf(13, 14), byteArrayOf(15, 16)), ) private val ethLog2 = ethLog1.copy(blockNumber = 124UL) private val ethLog3 = ethLog1.copy(blockNumber = 123UL, logIndex = 3UL) diff --git a/jvm-libs/linea/core/domain-models/src/test/kotlin/net/consensys/linea/FeeHistoryTest.kt b/jvm-libs/linea/core/domain-models/src/test/kotlin/net/consensys/linea/FeeHistoryTest.kt index 3352a3b7..f2a94db3 100644 --- a/jvm-libs/linea/core/domain-models/src/test/kotlin/net/consensys/linea/FeeHistoryTest.kt +++ b/jvm-libs/linea/core/domain-models/src/test/kotlin/net/consensys/linea/FeeHistoryTest.kt @@ -14,7 +14,7 @@ class FeeHistoryTest { reward = listOf(listOf(1uL), listOf(2uL), listOf(3uL)), gasUsedRatio = listOf(0.1, 0.2, 0.3), baseFeePerBlobGas = listOf(1uL, 2uL, 3uL, 4uL), - blobGasUsedRatio = listOf(0.1, 0.2, 0.3) + blobGasUsedRatio = listOf(0.1, 0.2, 0.3), ) assertThat(feeHistory.blocksRange()).isEqualTo(100uL..102uL) } diff --git a/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/BlockFactory.kt b/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/BlockFactory.kt index 6015bf41..8803d6e6 100644 --- a/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/BlockFactory.kt +++ b/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/BlockFactory.kt @@ -23,7 +23,7 @@ fun createBlock( extraData: ByteArray = ByteArrayExt.random32(), baseFeePerGas: ULong = 7UL, transactionsRoot: ByteArray = ByteArrayExt.random32(), - transactions: List = emptyList() + transactions: List = emptyList(), ): Block { return Block( number = number, @@ -44,7 +44,7 @@ fun createBlock( nonce = 0UL, baseFeePerGas = baseFeePerGas, transactions = transactions, - ommers = emptyList() + ommers = emptyList(), ) } @@ -76,12 +76,12 @@ class EthGetBlockResponseDTO( val size: ULong, val totalDifficulty: ULong, val transactions: List, - val uncles: List = emptyList() + val uncles: List = emptyList(), ) fun Block?.toEthGetBlockResponse( size: ULong = 10UL * 1024UL, - totalDifficulty: ULong = this?.difficulty ?: 0UL + totalDifficulty: ULong = this?.difficulty ?: 0UL, ): EthGetBlockResponseDTO? { if (this == null) return null return EthGetBlockResponseDTO( @@ -104,7 +104,7 @@ fun Block?.toEthGetBlockResponse( sha3Uncles = this.ommersHash, size = size, totalDifficulty = totalDifficulty, - transactions = emptyList() + transactions = emptyList(), ) } @@ -128,6 +128,6 @@ fun Block.toBlockWithRandomTxHashes(): BlockWithTxHashes { nonce = nonce, baseFeePerGas = baseFeePerGas, transactions = transactions.map { Random.nextBytes(32) }, - ommers = emptyList() + ommers = emptyList(), ) } diff --git a/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/TransactionFactory.kt b/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/TransactionFactory.kt index 9226c16b..ba6ec4c6 100644 --- a/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/TransactionFactory.kt +++ b/jvm-libs/linea/core/domain-models/src/testFixtures/kotlin/linea/domain/TransactionFactory.kt @@ -29,7 +29,7 @@ object TransactionFactory { v: ULong? = null, chainId: ULong? = null, // Optional field for EIP-155 transactions gasPrice: ULong? = 3UL.gwei, // null for EIP-1559 transactions - accessList: List? = null // null non for EIP-2930 transactions + accessList: List? = null, // null non for EIP-2930 transactions ): Transaction { return createTransaction( type = TransactionType.FRONTIER, @@ -46,7 +46,7 @@ object TransactionFactory { gasPrice = gasPrice, maxFeePerGas = null, maxPriorityFeePerGas = null, - accessList = accessList + accessList = accessList, ) } @@ -62,7 +62,7 @@ object TransactionFactory { chainId: ULong = 1337UL, // Optional field for EIP-155 transactions maxFeePerGas: ULong? = 3UL.gwei, // null for EIP-1559 transactions maxPriorityFeePerGas: ULong? = 2UL.gwei, // null for non EIP-1559 transactions - accessList: List? = null // null non for EIP-2930 transactions + accessList: List? = null, // null non for EIP-2930 transactions ): Transaction = createTransaction( type = TransactionType.EIP1559, nonce = nonce, @@ -78,7 +78,7 @@ object TransactionFactory { gasPrice = null, maxFeePerGas = maxFeePerGas, maxPriorityFeePerGas = maxPriorityFeePerGas, - accessList = accessList + accessList = accessList, ) fun createTransaction( @@ -96,7 +96,7 @@ object TransactionFactory { gasPrice: ULong? = null, // null for EIP-1559 transactions maxFeePerGas: ULong? = 3UL.gwei, // null for EIP-1559 transactions maxPriorityFeePerGas: ULong? = 2UL.gwei, // null for non EIP-1559 transactions - accessList: List? = null // null non for EIP-2930 transactions + accessList: List? = null, // null non for EIP-2930 transactions ): Transaction { val signatureArgs = listOfNotNull(r, s, v) require(signatureArgs.let { it.size == 3 || it.isEmpty() }) { @@ -118,7 +118,7 @@ object TransactionFactory { gasPrice = gasPrice, maxFeePerGas = maxFeePerGas, maxPriorityFeePerGas = maxPriorityFeePerGas, - accessList = accessList + accessList = accessList, ) eR = sig.r eS = sig.s @@ -146,12 +146,12 @@ object TransactionFactory { gasPrice = gasPrice, maxFeePerGas = maxFeePerGas, maxPriorityFeePerGas = maxPriorityFeePerGas, - accessList = accessList + accessList = accessList, ) } fun Transaction.computeSignature( - keyPair: KeyPair = defaltSecp256k1 + keyPair: KeyPair = defaltSecp256k1, ): SECPSignature { return computeSignature( type = type, @@ -165,7 +165,7 @@ object TransactionFactory { maxFeePerGas = maxFeePerGas, maxPriorityFeePerGas = maxPriorityFeePerGas, accessList = accessList, - keyPair = keyPair + keyPair = keyPair, ) } @@ -181,7 +181,7 @@ object TransactionFactory { maxFeePerGas: ULong?, maxPriorityFeePerGas: ULong?, accessList: List?, - keyPair: KeyPair = defaltSecp256k1 + keyPair: KeyPair = defaltSecp256k1, ): SECPSignature { val besuType = type.toBesu() return org.hyperledger.besu.ethereum.core.Transaction.builder() @@ -200,7 +200,7 @@ object TransactionFactory { val accList = accessList?.map { entry -> org.hyperledger.besu.datatypes.AccessListEntry( Address.wrap(Bytes.wrap(entry.address)), - entry.storageKeys.map { Bytes32.wrap(it) } + entry.storageKeys.map { Bytes32.wrap(it) }, ) } ?: emptyList() accessList(accList) @@ -213,7 +213,7 @@ object TransactionFactory { fun calcV( transactionType: TransactionType, signature: SECPSignature, - chainId: ULong? + chainId: ULong?, ): ULong? { if (transactionType != TransactionType.FRONTIER) { // EIP-2718 typed transaction, use yParity: diff --git a/jvm-libs/linea/core/long-running-service/src/main/kotlin/net/consensys/zkevm/PeriodicPollingService.kt b/jvm-libs/linea/core/long-running-service/src/main/kotlin/net/consensys/zkevm/PeriodicPollingService.kt index c747a8f1..9acfdce2 100644 --- a/jvm-libs/linea/core/long-running-service/src/main/kotlin/net/consensys/zkevm/PeriodicPollingService.kt +++ b/jvm-libs/linea/core/long-running-service/src/main/kotlin/net/consensys/zkevm/PeriodicPollingService.kt @@ -7,7 +7,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture abstract class PeriodicPollingService( private val vertx: Vertx, private val pollingIntervalMs: Long, - private val log: Logger + private val log: Logger, ) : LongRunningService { private var timerId: Long? = null diff --git a/jvm-libs/linea/core/long-running-service/src/test/kotlin/net/consensys/zkevm/PeriodicPollingServiceTest.kt b/jvm-libs/linea/core/long-running-service/src/test/kotlin/net/consensys/zkevm/PeriodicPollingServiceTest.kt index 3fde0abe..2fde0bcf 100644 --- a/jvm-libs/linea/core/long-running-service/src/test/kotlin/net/consensys/zkevm/PeriodicPollingServiceTest.kt +++ b/jvm-libs/linea/core/long-running-service/src/test/kotlin/net/consensys/zkevm/PeriodicPollingServiceTest.kt @@ -56,7 +56,7 @@ class PeriodicPollingServiceTest { .untilAsserted { verify(log, atLeastOnce()).error( eq("Error polling: errorMessage={}"), - eq("java.lang.IllegalStateException: Test error") + eq("java.lang.IllegalStateException: Test error"), ) } testContext.completeNow() @@ -78,7 +78,7 @@ class PeriodicPollingServiceTest { .untilAsserted { verify(log, atLeastOnce()).error( eq("Error polling: errorMessage={}"), - eq("java.lang.IllegalStateException: Throw test") + eq("java.lang.IllegalStateException: Throw test"), ) } testContext.completeNow() @@ -112,7 +112,7 @@ class PeriodicPollingServiceTest { assertThat(actionCallCount.get()).isGreaterThanOrEqualTo(5) verify(log, times(2)).error( eq("Error polling: errorMessage={}"), - eq("java.lang.IllegalStateException: Test error") + eq("java.lang.IllegalStateException: Test error"), ) } testContext.completeNow() @@ -146,7 +146,7 @@ class PeriodicPollingServiceTest { assertThat(actionCallCount.get()).isGreaterThanOrEqualTo(5) verify(log, times(2)).error( eq("Error polling: errorMessage={}"), - eq("java.lang.IllegalStateException: Throw test") + eq("java.lang.IllegalStateException: Throw test"), ) } testContext.completeNow() @@ -157,7 +157,7 @@ class PeriodicPollingServiceTest { @Timeout(3, timeUnit = TimeUnit.SECONDS) fun `ticks shouldn't run concurrently if execution is longer than polling interval`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { val pollingInterval = 5.milliseconds.inWholeMilliseconds val numberOfInvocations = AtomicInteger(0) @@ -196,7 +196,7 @@ class PeriodicPollingServiceTest { @Test @Timeout(3, timeUnit = TimeUnit.SECONDS) fun `periodicPollingService start should be idempotent`( - testContext: VertxTestContext + testContext: VertxTestContext, ) { val pollingInterval = 60.milliseconds.inWholeMilliseconds val mockVertx = mock() @@ -221,7 +221,7 @@ class PeriodicPollingServiceTest { @Timeout(3, timeUnit = TimeUnit.SECONDS) fun `periodicPollingService stop should be idempotent`( vertx: Vertx, - testContext: VertxTestContext + testContext: VertxTestContext, ) { val log: Logger = Mockito.spy(LogManager.getLogger(PollingService::class.java)) val pollingService = PollingService(vertx, pollingInterval, log) @@ -252,11 +252,11 @@ class PollingService( private val vertx: Vertx, pollingInterval: Long, private val log: Logger, - val mockAction: (_: Unit) -> SafeFuture = { SafeFuture.completedFuture(Unit) } + val mockAction: (_: Unit) -> SafeFuture = { SafeFuture.completedFuture(Unit) }, ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = pollingInterval, - log = log + log = log, ) { override fun action(): SafeFuture { val future = SafeFuture() diff --git a/jvm-libs/linea/core/metrics/src/main/kotlin/net/consensys/linea/metrics/MetricsFacade.kt b/jvm-libs/linea/core/metrics/src/main/kotlin/net/consensys/linea/metrics/MetricsFacade.kt index a62b0688..23f823ca 100644 --- a/jvm-libs/linea/core/metrics/src/main/kotlin/net/consensys/linea/metrics/MetricsFacade.kt +++ b/jvm-libs/linea/core/metrics/src/main/kotlin/net/consensys/linea/metrics/MetricsFacade.kt @@ -13,7 +13,8 @@ enum class LineaMetricsCategory { BLOB, CONFLATION, GAS_PRICE_CAP, - TX_EXCLUSION_API; + TX_EXCLUSION_API, + ; override fun toString(): String { return this.name.replace('_', '.').lowercase() @@ -41,14 +42,14 @@ interface MetricsFacade { name: String, description: String, measurementSupplier: Supplier, - tags: List = emptyList() + tags: List = emptyList(), ) fun createCounter( category: LineaMetricsCategory? = null, name: String, description: String, - tags: List = emptyList() + tags: List = emptyList(), ): Counter fun createHistogram( @@ -57,14 +58,14 @@ interface MetricsFacade { description: String, tags: List = emptyList(), isRatio: Boolean = false, - baseUnit: String? = null + baseUnit: String? = null, ): Histogram fun createSimpleTimer( category: LineaMetricsCategory? = null, name: String, description: String, - tags: List = emptyList() + tags: List = emptyList(), ): TimerCapture fun createDynamicTagTimer( @@ -73,7 +74,7 @@ interface MetricsFacade { description: String, tagKey: String, tagValueExtractorOnError: Function, - tagValueExtractor: Function + tagValueExtractor: Function, ): TimerCapture } diff --git a/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracesCounters.kt b/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracesCounters.kt index 7ef68e8d..59580ae4 100644 --- a/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracesCounters.kt +++ b/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracesCounters.kt @@ -15,7 +15,7 @@ interface TracesCounters { abstract class TracesCountersImpl internal constructor( private val countersMap: Map, - private val modules: List + private val modules: List, ) : TracesCounters { init { require(countersMap.size == modules.size && countersMap.keys.containsAll(modules)) { @@ -65,7 +65,7 @@ private fun add(tc1: TracesCounters, tc2: TracesCounters): Map String object TracesFiles { @@ -14,7 +14,7 @@ object TracesFiles { blockNumber: ULong, blockHash: Bytes32, tracesEngineVersion: String, - tracesFileExtension: String + tracesFileExtension: String, ): String { return "$blockNumber-${blockHash.toHexString().lowercase()}.v$tracesEngineVersion.$tracesFileExtension" } diff --git a/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracingModule.kt b/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracingModule.kt index b3c58035..a0d82a41 100644 --- a/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracingModule.kt +++ b/jvm-libs/linea/core/traces/src/main/kotlin/net/consensys/linea/traces/TracingModule.kt @@ -59,7 +59,8 @@ enum class TracingModuleV2 : TracingModule { BLOCK_KECCAK, BLOCK_L1_SIZE, BLOCK_L2_L1_LOGS, - BLOCK_TRANSACTIONS; + BLOCK_TRANSACTIONS, + ; companion object { val evmModules: Set = setOf( @@ -92,7 +93,7 @@ enum class TracingModuleV2 : TracingModule { STP, TRM, TXN_DATA, - WCP + WCP, ) } } diff --git a/jvm-libs/linea/core/traces/src/test/kotlin/net/consensys/linea/traces/TracesCountersTest.kt b/jvm-libs/linea/core/traces/src/test/kotlin/net/consensys/linea/traces/TracesCountersTest.kt index 7a3c3866..0e5bbee2 100644 --- a/jvm-libs/linea/core/traces/src/test/kotlin/net/consensys/linea/traces/TracesCountersTest.kt +++ b/jvm-libs/linea/core/traces/src/test/kotlin/net/consensys/linea/traces/TracesCountersTest.kt @@ -63,7 +63,7 @@ class TracesCountersTest { @Test fun empty_counters() { val tracesCountersV2 = TracesCountersV2( - TracingModuleV2.entries.associateWith { 0u } + TracingModuleV2.entries.associateWith { 0u }, ) assertThat(tracesCountersV2).isEqualTo(TracesCountersV2.EMPTY_TRACES_COUNT) } diff --git a/jvm-libs/linea/core/traces/src/testFixtures/kotlin/net/consensys/linea/traces/EvmTracesTestHelper.kt b/jvm-libs/linea/core/traces/src/testFixtures/kotlin/net/consensys/linea/traces/EvmTracesTestHelper.kt index a9ada656..a3133a86 100644 --- a/jvm-libs/linea/core/traces/src/testFixtures/kotlin/net/consensys/linea/traces/EvmTracesTestHelper.kt +++ b/jvm-libs/linea/core/traces/src/testFixtures/kotlin/net/consensys/linea/traces/EvmTracesTestHelper.kt @@ -5,11 +5,11 @@ import kotlin.random.nextUInt fun fakeTracesCountersV2( defaultValue: UInt?, - moduleValue: Map = emptyMap() + moduleValue: Map = emptyMap(), ): TracesCountersV2 { return TracesCountersV2( TracingModuleV2.entries.associateWith { moduleValue[it] ?: defaultValue ?: Random.nextUInt(0u, UInt.MAX_VALUE) - } + }, ) } diff --git a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/DynamicTagTimerCapture.kt b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/DynamicTagTimerCapture.kt index 3a352a28..5dd3a124 100644 --- a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/DynamicTagTimerCapture.kt +++ b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/DynamicTagTimerCapture.kt @@ -23,7 +23,7 @@ class DynamicTagTimerCapture : AbstractTimerCapture, TimerCapture { constructor(meterRegistry: MeterRegistry, name: String) : super(meterRegistry, name) constructor( meterRegistry: MeterRegistry, - timerBuilder: Timer.Builder + timerBuilder: Timer.Builder, ) : super(meterRegistry, timerBuilder) override fun setDescription(description: String): DynamicTagTimerCapture { @@ -33,7 +33,7 @@ class DynamicTagTimerCapture : AbstractTimerCapture, TimerCapture { override fun setTag(tagKey: String, tagValue: String): DynamicTagTimerCapture { throw NoSuchMethodException( - "If you need to set both value and key, please use ${SimpleTimerCapture::class.qualifiedName}" + "If you need to set both value and key, please use ${SimpleTimerCapture::class.qualifiedName}", ) } @@ -53,7 +53,7 @@ class DynamicTagTimerCapture : AbstractTimerCapture, TimerCapture { } fun setTagValueExtractorOnError( - onErrorExtractor: Function + onErrorExtractor: Function, ): DynamicTagTimerCapture { this.extractorOnError = onErrorExtractor return this diff --git a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacade.kt b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacade.kt index d2d5abd7..142f3be0 100644 --- a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacade.kt +++ b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacade.kt @@ -16,13 +16,13 @@ import io.micrometer.core.instrument.Timer as MicrometerTimer class MicrometerMetricsFacade( private val registry: MeterRegistry, - private val metricsPrefix: String? = null + private val metricsPrefix: String? = null, ) : MetricsFacade { companion object { private val validBaseUnits = listOf( "seconds", "minutes", - "hours" + "hours", ) fun requireValidMicrometerName(name: String) { @@ -50,7 +50,7 @@ class MicrometerMetricsFacade( name: String, description: String, measurementSupplier: Supplier, - tags: List + tags: List, ) { if (category != null) requireValidMicrometerName(category.toString()) requireValidMicrometerName(name) @@ -70,7 +70,7 @@ class MicrometerMetricsFacade( category: LineaMetricsCategory?, name: String, description: String, - tags: List + tags: List, ): Counter { if (category != null) requireValidMicrometerName(category.toString()) requireValidMicrometerName(name) @@ -92,7 +92,7 @@ class MicrometerMetricsFacade( description: String, tags: List, isRatio: Boolean, - baseUnit: String? + baseUnit: String?, ): Histogram { if (category != null) requireValidMicrometerName(category.toString()) requireValidMicrometerName(name) @@ -118,7 +118,7 @@ class MicrometerMetricsFacade( category: LineaMetricsCategory?, name: String, description: String, - tags: List + tags: List, ): TimerCapture { if (category != null) requireValidMicrometerName(category.toString()) requireValidMicrometerName(name) @@ -141,7 +141,7 @@ class MicrometerMetricsFacade( description: String, tagKey: String, tagValueExtractorOnError: Function, - tagValueExtractor: Function + tagValueExtractor: Function, ): TimerCapture { if (category != null) requireValidMicrometerName(category.toString()) requireValidMicrometerName(name) diff --git a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/SimpleTimerCapture.kt b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/SimpleTimerCapture.kt index 416c6a5e..51665bf1 100644 --- a/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/SimpleTimerCapture.kt +++ b/jvm-libs/linea/metrics/micrometer/src/main/kotlin/net/consensys/linea/metrics/micrometer/SimpleTimerCapture.kt @@ -17,7 +17,7 @@ class SimpleTimerCapture : AbstractTimerCapture, TimerCapture { constructor(meterRegistry: MeterRegistry, name: String) : super(meterRegistry, name) constructor( meterRegistry: MeterRegistry, - timerBuilder: Timer.Builder + timerBuilder: Timer.Builder, ) : super(meterRegistry, timerBuilder) override fun setDescription(description: String): SimpleTimerCapture { diff --git a/jvm-libs/linea/metrics/micrometer/src/test/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacadeTest.kt b/jvm-libs/linea/metrics/micrometer/src/test/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacadeTest.kt index 39df4fcb..207dc8ae 100644 --- a/jvm-libs/linea/metrics/micrometer/src/test/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacadeTest.kt +++ b/jvm-libs/linea/metrics/micrometer/src/test/kotlin/net/consensys/linea/metrics/micrometer/MicrometerMetricsFacadeTest.kt @@ -31,7 +31,7 @@ class MicrometerMetricsFacadeTest { name = "some.metric", description = "This is a test metric", measurementSupplier = { metricMeasureValue }, - tags = expectedTags + tags = expectedTags, ) metricMeasureValue = 13L val createdGauge = meterRegistry.find("linea.test.batch.some.metric").gauge() @@ -50,7 +50,7 @@ class MicrometerMetricsFacadeTest { category = LineaMetricsCategory.BATCH, name = "some.metric", description = "This is a test metric", - tags = expectedTags + tags = expectedTags, ) val createdCounter = meterRegistry.find("linea.test.batch.some.metric").counter() assertThat(createdCounter!!.count()).isEqualTo(0.0) @@ -76,14 +76,14 @@ class MicrometerMetricsFacadeTest { name = "some.metric", description = "This is a test metric", tags = expectedTags, - baseUnit = "seconds" + baseUnit = "seconds", ) val createdHistogram = meterRegistry.find("linea.test.batch.some.metric").summary() assertThat(createdHistogram).isNotNull assertThat(createdHistogram!!.id.description).isEqualTo("This is a test metric") assertThat(createdHistogram.id.tags).isEqualTo( - listOf(ImmutableTag("key1", "value1"), ImmutableTag("key2", "value2")) + listOf(ImmutableTag("key1", "value1"), ImmutableTag("key2", "value2")), ) assertThat(createdHistogram.id.baseUnit).isEqualTo("seconds") assertThat(createdHistogram.count()).isEqualTo(0L) @@ -115,7 +115,7 @@ class MicrometerMetricsFacadeTest { val timer = metricsFacade.createSimpleTimer( name = "some.timer.metric", description = "This is a test metric", - tags = expectedTags + tags = expectedTags, ) timer.captureTime(::mockTimer) @@ -140,7 +140,7 @@ class MicrometerMetricsFacadeTest { name = "some.dynamictag.timer.metric", description = "This is a test metric", tagKey = "key", - tagValueExtractorOnError = { "unfound_key" } + tagValueExtractorOnError = { "unfound_key" }, ) { "value" } @@ -166,7 +166,7 @@ class MicrometerMetricsFacadeTest { name = "some.gauge.metric", description = "This is a test metric", measurementSupplier = { metricMeasureValue }, - tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")) + tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")), ) val createdGauge = meterRegistry.find("some.gauge.metric").gauge() assertThat(createdGauge).isNotNull @@ -179,7 +179,7 @@ class MicrometerMetricsFacadeTest { metricsFacade.createCounter( name = "some.counter.metric", description = "This is a test metric", - tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")) + tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")), ) val createdCounter = meterRegistry.find("some.counter.metric").counter() assertThat(createdCounter).isNotNull @@ -193,7 +193,7 @@ class MicrometerMetricsFacadeTest { name = "some.histogram.metric", description = "This is a test metric", tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")), - baseUnit = "seconds" + baseUnit = "seconds", ) val createdHistogram = meterRegistry.find("some.histogram.metric").summary() assertThat(createdHistogram).isNotNull @@ -206,7 +206,7 @@ class MicrometerMetricsFacadeTest { val timer = metricsFacade.createSimpleTimer( name = "some.timer.metric", description = "This is a test metric", - tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")) + tags = listOf(Tag("key1", "value1"), Tag("key2", "value2")), ) timer.captureTime {} val createdTimer = meterRegistry.find("some.timer.metric").timer() @@ -221,7 +221,7 @@ class MicrometerMetricsFacadeTest { name = "some.dynamictag.timer.metric", description = "This is a test metric", tagKey = "key", - tagValueExtractorOnError = { "unfound_key" } + tagValueExtractorOnError = { "unfound_key" }, ) { "value" } diff --git a/jvm-libs/linea/testing/file-system/src/main/kotlin/net/consensys/linea/testing/filesystem/Files.kt b/jvm-libs/linea/testing/file-system/src/main/kotlin/net/consensys/linea/testing/filesystem/Files.kt index a05d3596..0b480cf5 100644 --- a/jvm-libs/linea/testing/file-system/src/main/kotlin/net/consensys/linea/testing/filesystem/Files.kt +++ b/jvm-libs/linea/testing/file-system/src/main/kotlin/net/consensys/linea/testing/filesystem/Files.kt @@ -12,7 +12,7 @@ import java.nio.file.Paths fun findPathTo( targetFileOrDir: String, lookupDir: Path = Paths.get("").toAbsolutePath(), - lookupParentDir: Boolean = true + lookupParentDir: Boolean = true, ): Path? { var current: Path = lookupDir var keepSearching = true @@ -36,7 +36,7 @@ fun findPathTo( fun getPathTo( targetFileOrDir: String, lookupDir: Path = Paths.get("").toAbsolutePath(), - lookupParentDir: Boolean = true + lookupParentDir: Boolean = true, ): Path { return findPathTo(targetFileOrDir, lookupDir, lookupParentDir) ?: throw IllegalArgumentException("Could not find $targetFileOrDir in path: $lookupDir or its parent directories") diff --git a/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/ProverResponsesFileLoader.kt b/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/ProverResponsesFileLoader.kt index 473aaf77..d5973c2a 100644 --- a/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/ProverResponsesFileLoader.kt +++ b/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/ProverResponsesFileLoader.kt @@ -32,7 +32,7 @@ fun loadAggregations(aggregationsDir: String): List { fun loadBlobs( blobsDir: String, - firstBlockStartBlockTime: Instant + firstBlockStartBlockTime: Instant, ): List { return loadProverResponses(blobsDir) { BlobCompressionProofJsonResponse.fromJsonString(it).toDomainObject() @@ -40,7 +40,7 @@ fun loadBlobs( .let { compressionProofs -> createBlobRecords( compressionProofs = compressionProofs, - firstBlockStartBlockTime = firstBlockStartBlockTime + firstBlockStartBlockTime = firstBlockStartBlockTime, ) } .sortedBy { it.startBlockNumber } @@ -48,7 +48,7 @@ fun loadBlobs( fun loadBlobsAndAggregations( blobsResponsesDir: String, - aggregationsResponsesDir: String + aggregationsResponsesDir: String, ): Pair, List> { val aggregations = loadAggregations(aggregationsResponsesDir) val firstAggregationBlockTime = aggregations.first().let { agg -> @@ -63,7 +63,7 @@ fun loadBlobsAndAggregationsSortedAndGrouped( blobsResponsesDir: String, aggregationsResponsesDir: String, numberOfAggregations: Int? = null, - extraBlobsWithoutAggregation: Int = 0 + extraBlobsWithoutAggregation: Int = 0, ): List { var (blobs, aggregations) = loadBlobsAndAggregations(blobsResponsesDir, aggregationsResponsesDir) @@ -76,13 +76,13 @@ fun loadBlobsAndAggregationsSortedAndGrouped( data class AggregationAndBlobs( val aggregation: Aggregation?, - val blobs: List + val blobs: List, ) fun groupBlobsToAggregations( aggregations: List, blobs: List, - extraBlobsWithoutAggregation: Int + extraBlobsWithoutAggregation: Int, ): List { val aggBlobs = aggregations.map { agg -> AggregationAndBlobs(agg, blobs.filter { it.startBlockNumber in agg.blocksRange }) @@ -97,7 +97,7 @@ fun groupBlobsToAggregations( throw IllegalStateException( "Not enough blobs without aggregation: " + "blobsWithoutAggregation=${blobsWithoutAgg.size} " + - "requestedBlobsWithoutAggregation=$extraBlobsWithoutAggregation" + "requestedBlobsWithoutAggregation=$extraBlobsWithoutAggregation", ) } diff --git a/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/SubmissionTestHelper.kt b/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/SubmissionTestHelper.kt index c88ee216..75f96e22 100644 --- a/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/SubmissionTestHelper.kt +++ b/jvm-libs/linea/testing/l1-blob-and-proof-submission/src/main/kotlin/net/consensys/linea/testing/submission/SubmissionTestHelper.kt @@ -19,17 +19,17 @@ fun assertTxSuccess( submissionType: String, l1Web3jClient: Web3j, timeout: Duration = 1.minutes, - log: Logger = LogManager.getLogger("linea.testing.submission") + log: Logger = LogManager.getLogger("linea.testing.submission"), ) { l1Web3jClient.waitForTxReceipt( txHash = txHash, timeout = timeout, - log = log + log = log, ).also { txReceipt -> if (txReceipt.status != "0x1") { throw RuntimeException( "submission of $submissionType=${interval.intervalString()}" + - " failed on L1. receipt=$txReceipt" + " failed on L1. receipt=$txReceipt", ) } } @@ -40,7 +40,7 @@ fun assertTxsSuccess( submissionType: String, l1Web3jClient: Web3j, timeout: Duration = 1.minutes, - log: Logger = LogManager.getLogger("linea.testing.submission") + log: Logger = LogManager.getLogger("linea.testing.submission"), ) { SafeFuture.supplyAsync { txsAndInterval.forEach { (txHash, interval) -> @@ -62,7 +62,7 @@ fun submitBlobs( blobChunksSize: Int = 9, awaitForPreviousTxBeforeSubmittingNext: Boolean = false, l1Web3jClient: Web3j, - log: Logger + log: Logger, ): List>> { require(blobChunksSize in 1..9) { "blobChunksSize must be between 1..9" } @@ -76,7 +76,7 @@ fun submitBlobs( "submitting blobs: aggregation={} blobsChunk={} txHash={}", agg?.intervalString(), blobsLogInfo, - txHash + txHash, ) if (awaitForPreviousTxBeforeSubmittingNext) { log.debug("waiting for blobsChunk={} txHash={} to be mined", blobsLogInfo, txHash) @@ -97,7 +97,7 @@ fun submitBlobsAndAggregationsAndWaitExecution( blobChunksMaxSize: Int = 9, l1Web3jClient: Web3j, waitTimeout: Duration = 2.minutes, - log: Logger = LogManager.getLogger("linea.testing.submission") + log: Logger = LogManager.getLogger("linea.testing.submission"), ) { val blobSubmissions = submitBlobs( contractClientForBlobSubmission, @@ -105,7 +105,7 @@ fun submitBlobsAndAggregationsAndWaitExecution( blobChunksMaxSize, awaitForPreviousTxBeforeSubmittingNext = false, l1Web3jClient = l1Web3jClient, - log = log + log = log, ) assertTxsSuccess( @@ -114,12 +114,12 @@ fun submitBlobsAndAggregationsAndWaitExecution( }, submissionType = "blobs", l1Web3jClient = l1Web3jClient, - timeout = waitTimeout + timeout = waitTimeout, ) log.info( "blob={} txHash={} executed on L1", blobSubmissions.last().second.last().intervalString(), - blobSubmissions.last().first + blobSubmissions.last().first, ) val submissions = aggregationsAndBlobs @@ -132,12 +132,12 @@ fun submitBlobsAndAggregationsAndWaitExecution( aggregationLastBlob = aggBlobs.last(), parentL1RollingHash = parentAgg?.aggregationProof?.l1RollingHash ?: ByteArray(32), parentL1RollingHashMessageNumber = parentAgg?.aggregationProof?.l1RollingHashMessageNumber ?: 0L, - gasPriceCaps = null + gasPriceCaps = null, ).get() log.info( "submitting aggregation={} txHash={}", aggregation.intervalString(), - txHash + txHash, ) txHash to aggregation } @@ -146,12 +146,12 @@ fun submitBlobsAndAggregationsAndWaitExecution( txsAndInterval = submissions, submissionType = "aggregation", l1Web3jClient = l1Web3jClient, - timeout = waitTimeout + timeout = waitTimeout, ) log.info( "aggregation={} txHash={} executed on L1", submissions.last().second.intervalString(), - submissions.last().first + submissions.last().first, ) } diff --git a/jvm-libs/linea/web3j-extensions/src/integrationTest/kotlin/net/consensys/linea/web3j/EthFeeHistoryBlobExtendedIntTest.kt b/jvm-libs/linea/web3j-extensions/src/integrationTest/kotlin/net/consensys/linea/web3j/EthFeeHistoryBlobExtendedIntTest.kt index 77244b28..40cdd6a7 100644 --- a/jvm-libs/linea/web3j-extensions/src/integrationTest/kotlin/net/consensys/linea/web3j/EthFeeHistoryBlobExtendedIntTest.kt +++ b/jvm-libs/linea/web3j-extensions/src/integrationTest/kotlin/net/consensys/linea/web3j/EthFeeHistoryBlobExtendedIntTest.kt @@ -13,7 +13,7 @@ class EthFeeHistoryBlobExtendedIntTest { web3jBlobExtended.ethFeeHistoryWithBlob( blockCount = 5, newestBlock = DefaultBlockParameter.valueOf("latest"), - rewardPercentiles = listOf(15.0) + rewardPercentiles = listOf(15.0), ).sendAsync() .thenApply { response -> assertThat(response).isNotNull diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthCallWithInformativeReverts.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthCallWithInformativeReverts.kt index 91a108b1..9bc2ca4c 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthCallWithInformativeReverts.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthCallWithInformativeReverts.kt @@ -13,7 +13,7 @@ typealias SmartContractErrors = Map fun getRevertReason( error: Response.Error?, - smartContractErrors: SmartContractErrors + smartContractErrors: SmartContractErrors, ): String? { val errorDataString = error?.data ?: "" return if (errorDataString.length > 11) { @@ -27,7 +27,7 @@ fun getRevertReason( private fun getErrorMessage( ethCall: EthCall, - smartContractErrors: SmartContractErrors + smartContractErrors: SmartContractErrors, ): String { val revertReason = getRevertReason(ethCall.error, smartContractErrors) @@ -37,7 +37,7 @@ private fun getErrorMessage( fun Web3j.informativeEthCall( tx: Transaction, - smartContractErrors: SmartContractErrors + smartContractErrors: SmartContractErrors, ): SafeFuture { return SafeFuture .of(this.ethCall(tx, DefaultBlockParameterName.LATEST).sendAsync()) diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthFeeHistoryBlobExtended.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthFeeHistoryBlobExtended.kt index 40b125cb..d33f4877 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthFeeHistoryBlobExtended.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthFeeHistoryBlobExtended.kt @@ -31,7 +31,7 @@ class EthFeeHistoryBlobExtended : Response, val gasUsedRatio: List, val baseFeePerBlobGas: List, - val blobGasUsedRatio: List + val blobGasUsedRatio: List, ) { constructor() : this( oldestBlock = "", @@ -39,7 +39,7 @@ class EthFeeHistoryBlobExtended : Response + rewardPercentiles: List, ): Request<*, EthFeeHistoryBlobExtended> { return Request( "eth_feeHistory", listOf( Numeric.encodeQuantity(BigInteger.valueOf(blockCount.toLong())), newestBlock.value, - rewardPercentiles + rewardPercentiles, ), this.web3jService, - EthFeeHistoryBlobExtended::class.java + EthFeeHistoryBlobExtended::class.java, ) } } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthGetBlockToLineaBlockMappers.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthGetBlockToLineaBlockMappers.kt index 802fcf13..872c68c0 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthGetBlockToLineaBlockMappers.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/EthGetBlockToLineaBlockMappers.kt @@ -24,23 +24,23 @@ fun mapToDomainWithTxHashes(web3jBlock: EthBlock.Block): BlockWithTxHashes { } fun mapFullTxDataToDomain( - web3jBlock: EthBlock.Block + web3jBlock: EthBlock.Block, ): List { if (web3jBlock.transactions.isNotEmpty() && web3jBlock.transactions[0] !is EthBlock.TransactionObject) { throw IllegalArgumentException( "Expected to be have full EthBlock.TransactionObject." + - "Got just transaction hashes." + "Got just transaction hashes.", ) } return web3jBlock.transactions.map { (it as EthBlock.TransactionObject).toDomain() } } fun mapTxHashToByteArray( - web3jBlock: EthBlock.Block + web3jBlock: EthBlock.Block, ): List { if (web3jBlock.transactions.isNotEmpty() && web3jBlock.transactions[0] !is EthBlock.TransactionHash) { throw IllegalArgumentException( - "Expected to be have EthBlock.TransactionHash. Got instance of ${web3jBlock.transactions[0]::class.java}" + "Expected to be have EthBlock.TransactionHash. Got instance of ${web3jBlock.transactions[0]::class.java}", ) } return web3jBlock.transactions.map { (it as EthBlock.TransactionHash).get().decodeHex() } @@ -66,7 +66,7 @@ fun mapToDomain(web3jBlock: EthBlock.Block, txsMapper: (EthBlock.Block) mixHash = web3jBlock.mixHash.decodeHex(), baseFeePerGas = web3jBlock.baseFeePerGas?.toULong(), // Optional field for EIP-1559 blocks ommers = web3jBlock.uncles.map { it.decodeHex() }, // List of uncle block hashes - transactions = txsMapper(web3jBlock) // List of transactions + transactions = txsMapper(web3jBlock), // List of transactions ) return block } @@ -86,7 +86,7 @@ fun EthBlock.TransactionObject.toDomain(): Transaction { val accessList = this.accessList?.map { accessListEntry -> AccessListEntry( accessListEntry.address.decodeHex(), - accessListEntry.storageKeys.map { it.decodeHex() } + accessListEntry.storageKeys.map { it.decodeHex() }, ) } @@ -114,7 +114,7 @@ fun EthBlock.TransactionObject.toDomain(): Transaction { gasPrice = gasPrice, // Optional field for EIP-1559 transactions maxFeePerGas = maxFeePerGas, // Optional field for EIP-1559 transactions maxPriorityFeePerGas = maxPriorityFeePerGas, // Optional field for EIP-1559 transactions, - accessList = accessList + accessList = accessList, ) return domainTx } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ExtendedWeb3J.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ExtendedWeb3J.kt index 771ad29f..83542100 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ExtendedWeb3J.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ExtendedWeb3J.kt @@ -40,7 +40,7 @@ class ExtendedWeb3JImpl(override val web3jClient: Web3j) : ExtendedWeb3J { return web3jClient .ethGetBlockByNumber( blockParameter.toWeb3j(), - true + true, ) .sendAsync() .toSafeFuture() @@ -56,15 +56,15 @@ class ExtendedWeb3JImpl(override val web3jClient: Web3j) : ExtendedWeb3J { } override fun ethGetBlockTimestampByNumber( - blockNumber: Long + blockNumber: Long, ): SafeFuture { return SafeFuture.of( web3jClient .ethGetBlockByNumber( DefaultBlockParameter.valueOf(BigInteger.valueOf(blockNumber)), - false + false, ) - .sendAsync() + .sendAsync(), ) .thenCompose { response -> if (response.hasError()) { diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/RequestHelper.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/RequestHelper.kt index 0b30fe2b..cb96622c 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/RequestHelper.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/RequestHelper.kt @@ -8,15 +8,15 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture fun rejectOnJsonRpcError( rpcMethod: String, - response: Resp + response: Resp, ): SafeFuture where Resp : Response<*> { return if (response.hasError()) { SafeFuture.failedFuture( RuntimeException( "$rpcMethod failed with JsonRpcError " + - "code=${response.error.code} message=${response.error.message} data=${response.error.data}" - ) + "code=${response.error.code} message=${response.error.message} data=${response.error.data}", + ), ) } else { SafeFuture.completedFuture(response) @@ -24,7 +24,7 @@ fun rejectOnJsonRpcError( } fun Request<*, Resp>.requestAsync( - mapperFn: (Resp) -> T + mapperFn: (Resp) -> T, ): SafeFuture where Resp : Response<*> { return this.sendAsync() diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/Web3JFactory.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/Web3JFactory.kt index 3c74fea9..a382f650 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/Web3JFactory.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/Web3JFactory.kt @@ -16,7 +16,7 @@ fun createWeb3jHttpClient( pollingInterval: Duration = 500.milliseconds, executorService: ScheduledExecutorService = Async.defaultExecutorService(), requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): Web3j { return Web3j.build( HttpService( @@ -24,10 +24,10 @@ fun createWeb3jHttpClient( okHttpClientBuilder( logger = log, requestResponseLogLevel = requestResponseLogLevel, - failuresLogLevel = failuresLogLevel - ).build() + failuresLogLevel = failuresLogLevel, + ).build(), ), pollingInterval.inWholeMilliseconds, - executorService + executorService, ) } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/Eip4844EthCall.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/Eip4844EthCall.kt index 8275dcb0..81a1646f 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/Eip4844EthCall.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/Eip4844EthCall.kt @@ -32,7 +32,7 @@ class Eip4844Transaction( @Suppress("Unused") @JsonProperty("blobVersionedHashes") @JsonSerialize(contentUsing = ByteArrayToHexSerializer::class) - val blobVersionedHashes: List = computeVersionedHashesFromBlobs(blobs) + val blobVersionedHashes: List = computeVersionedHashesFromBlobs(blobs), ) : Transaction(from, nonce, gasPrice, gasLimit, to, value, data, chainId, maxPriorityFeePerGas, maxFeePerGas) { @Suppress("Unused") val maxFeePerBlobGas: String? = _maxFeePerBlobGas?.let { Numeric.encodeQuantity(it) } @@ -54,7 +54,7 @@ class Eip4844Transaction( gasLimit: BigInteger?, blobVersionedHashes: List = computeVersionedHashesFromBlobs(blobs), maxPriorityFeePerGas: BigInteger? = null, - maxFeePerGas: BigInteger? = null + maxFeePerGas: BigInteger? = null, ): Eip4844Transaction { return Eip4844Transaction( from = from, @@ -69,7 +69,7 @@ class Eip4844Transaction( maxFeePerGas = maxFeePerGas, _maxFeePerBlobGas = maxFeePerBlobGas, blobs = blobs, - blobVersionedHashes = blobVersionedHashes + blobVersionedHashes = blobVersionedHashes, ) } } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/EthLog.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/EthLog.kt index c39ed499..4ca7154f 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/EthLog.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/EthLog.kt @@ -15,6 +15,6 @@ fun Log.toDomain(): EthLog { blockNumber = this.blockNumber.toULong(), address = this.address.decodeHex(), data = this.data.decodeHex(), - topics = this.topics.map(String::decodeHex) + topics = this.topics.map(String::decodeHex), ) } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/FeeHistoryExtensions.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/FeeHistoryExtensions.kt index 4eaab016..9a99e61d 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/FeeHistoryExtensions.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/domain/FeeHistoryExtensions.kt @@ -11,7 +11,7 @@ fun EthFeeHistory.FeeHistory.toLineaDomain(): FeeHistory { reward = reward.map { it.map { it.toULong() } }, gasUsedRatio = gasUsedRatio.map { it }, baseFeePerBlobGas = listOf(0uL), - blobGasUsedRatio = listOf(0.0) + blobGasUsedRatio = listOf(0.0), ) } fun EthFeeHistory.FeeHistory.blocksRange(): ClosedRange { diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClient.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClient.kt index b3f38d5c..943efd9b 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClient.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClient.kt @@ -20,7 +20,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture * Request retries is responsibility of another class */ class Web3jEthApiClient( - val web3jClient: Web3j + val web3jClient: Web3j, ) : EthApiClient { override fun findBlockByNumber(blockParameter: BlockParameter): SafeFuture { @@ -30,7 +30,7 @@ class Web3jEthApiClient( } override fun findBlockByNumberWithoutTransactionsData( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { return web3jClient .ethGetBlockByNumber(blockParameter.toWeb3j(), false) @@ -41,12 +41,15 @@ class Web3jEthApiClient( fromBlock: BlockParameter, toBlock: BlockParameter, address: String, - topics: List + topics: List, ): SafeFuture> { val ethFilter = EthFilter( - /*fromBlock*/ fromBlock.toWeb3j(), - /*toBlock*/ toBlock.toWeb3j(), - /*address*/ address + /*fromBlock*/ + fromBlock.toWeb3j(), + /*toBlock*/ + toBlock.toWeb3j(), + /*address*/ + address, ).apply { topics.forEach { addSingleTopic(it) } } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientFactory.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientFactory.kt index 1ba10f16..83365c5d 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientFactory.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientFactory.kt @@ -23,7 +23,7 @@ import kotlin.time.Duration.Companion.milliseconds fun createEthApiClient( web3jClient: Web3j, requestRetryConfig: RetryConfig?, - vertx: Vertx? + vertx: Vertx?, ): EthApiClient { if (requestRetryConfig?.isRetryEnabled == true && vertx == null) { throw IllegalArgumentException("Vertx instance is required when request retry is enabled") @@ -34,7 +34,7 @@ fun createEthApiClient( Web3jEthApiClientWithRetries( vertx = vertx!!, ethApiClient = ethApiClient, - requestRetryConfig = requestRetryConfig + requestRetryConfig = requestRetryConfig, ) } else { Web3jEthApiClient(web3jClient) @@ -62,7 +62,7 @@ fun createEthApiClient( requestResponseLogLevel: Level = Level.TRACE, failuresLogLevel: Level = Level.DEBUG, requestRetryConfig: RetryConfig?, - vertx: Vertx? + vertx: Vertx?, ): EthApiClient { val web3jClient = createWeb3jHttpClient(rpcUrl, log, pollingInterval, executorService, requestResponseLogLevel, failuresLogLevel) diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientWithRetries.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientWithRetries.kt index 4909d6cf..5254b681 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientWithRetries.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/ethapi/Web3jEthApiClientWithRetries.kt @@ -13,18 +13,18 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class Web3jEthApiClientWithRetries( val vertx: Vertx, val ethApiClient: EthApiClient, - val requestRetryConfig: RetryConfig + val requestRetryConfig: RetryConfig, ) : EthApiClient { private fun retry( - fn: () -> SafeFuture + fn: () -> SafeFuture, ): SafeFuture { return AsyncRetryer.retry( vertx = vertx, backoffDelay = requestRetryConfig.backoffDelay, timeout = requestRetryConfig.timeout, maxRetries = requestRetryConfig.maxRetries?.toInt(), - action = fn + action = fn, ) } @@ -33,7 +33,7 @@ class Web3jEthApiClientWithRetries( } override fun findBlockByNumberWithoutTransactionsData( - blockParameter: BlockParameter + blockParameter: BlockParameter, ): SafeFuture { return retry { ethApiClient.findBlockByNumberWithoutTransactionsData(blockParameter) } } @@ -42,7 +42,7 @@ class Web3jEthApiClientWithRetries( fromBlock: BlockParameter, toBlock: BlockParameter, address: String, - topics: List + topics: List, ): SafeFuture> { return retry { ethApiClient.getLogs(fromBlock, toBlock, address, topics) } } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/AtomicContractEIP1559GasProvider.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/AtomicContractEIP1559GasProvider.kt index c6a9e4fd..5700ef4a 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/AtomicContractEIP1559GasProvider.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/AtomicContractEIP1559GasProvider.kt @@ -4,7 +4,7 @@ import org.web3j.tx.gas.ContractEIP1559GasProvider data class EIP1559GasFees( val maxPriorityFeePerGas: ULong, - val maxFeePerGas: ULong + val maxFeePerGas: ULong, ) interface AtomicContractEIP1559GasProvider : ContractEIP1559GasProvider { diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP1559GasProvider.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP1559GasProvider.kt index 2fc96697..dbfbbbe7 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP1559GasProvider.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP1559GasProvider.kt @@ -19,7 +19,7 @@ class EIP1559GasProvider(private val web3jClient: Web3j, private val config: Con val gasLimit: ULong, val maxFeePerGasCap: ULong, val feeHistoryBlockCount: UInt, - val feeHistoryRewardPercentile: Double + val feeHistoryRewardPercentile: Double, ) private val chainId: Long = web3jClient.ethChainId().send().chainId.toLong() @@ -34,7 +34,7 @@ class EIP1559GasProvider(private val web3jClient: Web3j, private val config: Con .ethFeeHistory( config.feeHistoryBlockCount.toInt(), DefaultBlockParameterName.LATEST, - listOf(config.feeHistoryRewardPercentile) + listOf(config.feeHistoryRewardPercentile), ) .sendAsync() .thenApply { @@ -46,7 +46,7 @@ class EIP1559GasProvider(private val web3jClient: Web3j, private val config: Con maxPriorityFeePerGas = config.maxFeePerGasCap log.warn( "Estimated miner tip of $maxPriorityFeePerGas exceeds configured max " + - "fee per gas of ${config.maxFeePerGasCap} returning cap instead!" + "fee per gas of ${config.maxFeePerGasCap} returning cap instead!", ) } @@ -57,17 +57,17 @@ class EIP1559GasProvider(private val web3jClient: Web3j, private val config: Con if (maxFeePerGas > 0uL && maxPriorityFeePerGas > 0uL) { feesCache = EIP1559GasFees( maxPriorityFeePerGas = maxPriorityFeePerGas, - maxFeePerGas = min(maxFeePerGas, config.maxFeePerGasCap) + maxFeePerGas = min(maxFeePerGas, config.maxFeePerGasCap), ) log.debug( "New fees estimation: fees={} l2Blocks={}", feeHistoryResponse.feeHistory.blocksRange().toIntervalString(), - feesCache + feesCache, ) } else { feesCache = EIP1559GasFees( maxPriorityFeePerGas = 0uL, - maxFeePerGas = config.maxFeePerGasCap + maxFeePerGas = config.maxFeePerGasCap, ) } } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP4844GasProvider.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP4844GasProvider.kt index 729ee20f..dfcf0987 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP4844GasProvider.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/EIP4844GasProvider.kt @@ -4,7 +4,7 @@ import org.web3j.tx.gas.ContractEIP1559GasProvider data class EIP4844GasFees( val eip1559GasFees: EIP1559GasFees, - val maxFeePerBlobGas: ULong + val maxFeePerBlobGas: ULong, ) interface EIP4844GasProvider : ContractEIP1559GasProvider { diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/StaticGasProvider.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/StaticGasProvider.kt index 09cc4536..fbc95ba0 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/StaticGasProvider.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/gas/StaticGasProvider.kt @@ -12,7 +12,7 @@ class StaticGasProvider( private val maxFeePerGas: ULong = 22uL.gwei, private val maxPriorityFeePerGas: ULong = 20uL.gwei, private val maxFeePerBlobGas: ULong = 1000uL.gwei, - private val gasLimit: ULong = 30_000_000uL + private val gasLimit: ULong = 30_000_000uL, ) : AtomicContractEIP1559GasProvider, EIP4844GasProvider { override fun getEIP1559GasFees(): EIP1559GasFees { return EIP1559GasFees(maxPriorityFeePerGas, maxFeePerGas) diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/okhttp/OkHttpClientLogging.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/okhttp/OkHttpClientLogging.kt index 60a3fca0..d725c416 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/okhttp/OkHttpClientLogging.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/okhttp/OkHttpClientLogging.kt @@ -13,7 +13,7 @@ import org.apache.logging.log4j.Logger import org.web3j.protocol.http.HttpService class OkHttpMinimalJsonRpcLoggerInterceptor( - val logger: JsonRpcRequestResponseLogger = MinimalInLineJsonRpcLogger(LogManager.getLogger(HttpService::class.java)) + val logger: JsonRpcRequestResponseLogger = MinimalInLineJsonRpcLogger(LogManager.getLogger(HttpService::class.java)), ) : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() @@ -37,7 +37,7 @@ class OkHttpMinimalJsonRpcLoggerInterceptor( endpoint = endpoint, responseStatusCode = response.code, requestBody = requestBody, - responseBody = responseBody + responseBody = responseBody, ) }.onFailure { e -> logger.logResponse( @@ -45,7 +45,7 @@ class OkHttpMinimalJsonRpcLoggerInterceptor( responseStatusCode = null, requestBody = requestBody, responseBody = "", - failureCause = e + failureCause = e, ) } .getOrThrow() @@ -57,7 +57,7 @@ fun okHttpClientBuilder( // we make a lot of eth_call request that fail by design, having DEBUG/WARN level is too noisy // ideally we should manage methods individually, but don't have time for that now requestResponseLogLevel: Level = Level.TRACE, - failuresLogLevel: Level = Level.DEBUG + failuresLogLevel: Level = Level.DEBUG, ): OkHttpClient.Builder { val httpClientBuilder = OkHttpClient.Builder() httpClientBuilder.addInterceptor( @@ -66,9 +66,9 @@ fun okHttpClientBuilder( logger, requestResponseLogLevel = requestResponseLogLevel, failuresLogLevel = failuresLogLevel, - maskEndpoint = ::maskEndpointPath - ) - ) + maskEndpoint = ::maskEndpointPath, + ), + ), ) return httpClientBuilder } diff --git a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/transactionmanager/AsyncFriendlyTransactionManager.kt b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/transactionmanager/AsyncFriendlyTransactionManager.kt index 448044a8..9b736bd1 100644 --- a/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/transactionmanager/AsyncFriendlyTransactionManager.kt +++ b/jvm-libs/linea/web3j-extensions/src/main/kotlin/linea/web3j/transactionmanager/AsyncFriendlyTransactionManager.kt @@ -36,7 +36,7 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { constructor( web3j: Web3j, txSignService: TxSignService, - chainId: Long + chainId: Long, ) : super(web3j, txSignService, chainId) { this.web3j = web3j resetNonce().get() @@ -50,8 +50,8 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { constructor( web3j: Web3j, credentials: Credentials, - transactionReceiptProcessor: TransactionReceiptProcessor - ) : super(web3j, credentials, /*chainId*/-1, transactionReceiptProcessor) { + transactionReceiptProcessor: TransactionReceiptProcessor, + ) : super(web3j, credentials, -1, transactionReceiptProcessor) { this.web3j = web3j resetNonce().get() } @@ -60,7 +60,7 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { web3j: Web3j, credentials: Credentials, chainId: Long, - transactionReceiptProcessor: TransactionReceiptProcessor + transactionReceiptProcessor: TransactionReceiptProcessor, ) : super(web3j, credentials, chainId, transactionReceiptProcessor) { this.web3j = web3j resetNonce().get() @@ -73,7 +73,7 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { return web3j.ethGetTransactionCount( fromAddress, - blockParameter + blockParameter, ) .requestAsync { setNonce(it.transactionCount) } } @@ -100,7 +100,7 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { function: Function, encodedData: String, weiValue: BigInteger, - transactionSent: EthSendTransaction + transactionSent: EthSendTransaction, ): RemoteFunctionCall { return RemoteFunctionCall(function) { val receipt = processResponse(transactionSent) @@ -114,9 +114,9 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { receipt.transactionHash, receipt.status, if (receipt.gasUsedRaw != null) receipt.gasUsed.toString() else "unknown", - RevertReasonExtractor.extractRevertReason(receipt, encodedData, web3j, true, weiValue) + RevertReasonExtractor.extractRevertReason(receipt, encodedData, web3j, true, weiValue), ), - receipt + receipt, ) } receipt @@ -133,19 +133,19 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { to: String, value: BigInteger, data: String, - maxFeePerBlobGas: BigInteger + maxFeePerBlobGas: BigInteger, ): RawTransaction { return RawTransaction.createTransaction( - /*blobs*/ blobs, - /*chainId*/ chainId, - /*nonce*/ nonce, - /*maxPriorityFeePerGas*/ maxPriorityFeePerGas, - /*maxFeePerGas*/ maxFeePerGas, - /*gasLimit*/ gasLimit, - /*to*/ to, - /*value*/ value, - /*data*/ data, - /*maxFeePerBlobGas*/ maxFeePerBlobGas + blobs, + chainId, + nonce, + maxPriorityFeePerGas, + maxFeePerGas, + gasLimit, + to, + value, + data, + maxFeePerBlobGas, ) } @@ -157,17 +157,17 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { gasLimit: BigInteger, to: String, value: BigInteger, - data: String + data: String, ): RawTransaction { return RawTransaction.createTransaction( - /*chainId*/ chainId, - /*nonce*/ nonce, - /*gasLimit*/ gasLimit, - /*to*/ to, - /*value*/ value, - /*data*/ data, - /*maxPriorityFeePerGas*/ maxPriorityFeePerGas, - /*maxFeePerGas*/ maxFeePerGas + chainId, + nonce, + gasLimit, + to, + value, + data, + maxPriorityFeePerGas, + maxFeePerGas, ) } @@ -177,15 +177,15 @@ class AsyncFriendlyTransactionManager : RawTransactionManager { gasLimit: BigInteger, to: String, value: BigInteger, - data: String + data: String, ): RawTransaction { return RawTransaction.createTransaction( - /*nonce*/ nonce, - /*gasPrice*/ gasPrice, - /*gasLimit*/ gasLimit, - /*to*/ to, - /*value*/ value, - /*data*/ data + nonce, + gasPrice, + gasLimit, + to, + value, + data, ) } } diff --git a/jvm-libs/linea/web3j-extensions/src/test/kotlin/linea/web3j/EthGetBlockToLineaBlockMapperTest.kt b/jvm-libs/linea/web3j-extensions/src/test/kotlin/linea/web3j/EthGetBlockToLineaBlockMapperTest.kt index d00beb47..1bd8714c 100644 --- a/jvm-libs/linea/web3j-extensions/src/test/kotlin/linea/web3j/EthGetBlockToLineaBlockMapperTest.kt +++ b/jvm-libs/linea/web3j-extensions/src/test/kotlin/linea/web3j/EthGetBlockToLineaBlockMapperTest.kt @@ -51,7 +51,7 @@ class EthGetBlockToLineaBlockMapperTest { "r": "0x1fa31b9272cc67174efb129c2fd2ec5afda122503745beb22bd26e48a42240bb", "s": "0x248c9cdf9352b4a379577c5b44bcb25a5350dc6722fd7b2aec40e193f670e4f4" } - """.trimIndent() + """.trimIndent(), ) val domainTx = txWeb3j.toDomain() @@ -71,8 +71,8 @@ class EthGetBlockToLineaBlockMapperTest { chainId = 0x539UL, maxFeePerGas = 0xeUL, maxPriorityFeePerGas = 0x0UL, - accessList = emptyList() - ) + accessList = emptyList(), + ), ) domainTx.toBesu().also { besuTx -> @@ -86,10 +86,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(besuTx.value).isEqualTo(Wei.of(0x0L)) assertThat(besuTx.payload).isEqualTo(Bytes.fromHexString("0x60806040523480156200001157600080fd5b506200001c")) assertThat(besuTx.signature.r).isEqualTo( - "0x1fa31b9272cc67174efb129c2fd2ec5afda122503745beb22bd26e48a42240bb".toBigIntegerFromHex() + "0x1fa31b9272cc67174efb129c2fd2ec5afda122503745beb22bd26e48a42240bb".toBigIntegerFromHex(), ) assertThat(besuTx.signature.s).isEqualTo( - "0x248c9cdf9352b4a379577c5b44bcb25a5350dc6722fd7b2aec40e193f670e4f4".toBigIntegerFromHex() + "0x248c9cdf9352b4a379577c5b44bcb25a5350dc6722fd7b2aec40e193f670e4f4".toBigIntegerFromHex(), ) assertThat(besuTx.signature.recId).isEqualTo(0) assertThat(besuTx.chainId.getOrNull()).isEqualTo(0x539L) @@ -118,7 +118,7 @@ class EthGetBlockToLineaBlockMapperTest { "v": "0x1ce2e", "value": "0x186a0" } - """.trimIndent() + """.trimIndent(), ) val domainTx = txWeb3j.toDomain() assertThat(domainTx).isEqualTo( @@ -137,8 +137,8 @@ class EthGetBlockToLineaBlockMapperTest { chainId = 0xe705UL, maxFeePerGas = null, maxPriorityFeePerGas = null, - accessList = null - ) + accessList = null, + ), ) domainTx.toBesu().also { besuTx -> assertThat(besuTx.type).isEqualTo(org.hyperledger.besu.datatypes.TransactionType.FRONTIER) @@ -149,10 +149,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(besuTx.value).isEqualTo(Wei.of(0x186a0L)) assertThat(besuTx.payload).isEqualTo(Bytes.EMPTY) assertThat(besuTx.signature.r).isEqualTo( - "0xdf28597129341d5d345c9043c7d0b0a22be82cac13988cfc1d8cbdaf3ab3f35b".toBigIntegerFromHex() + "0xdf28597129341d5d345c9043c7d0b0a22be82cac13988cfc1d8cbdaf3ab3f35b".toBigIntegerFromHex(), ) assertThat(besuTx.signature.s).isEqualTo( - "0x3189b2ff80d8f728d6fb7503b46734ee77a60a42db01d0b09db10bdc9d5caa44".toBigIntegerFromHex() + "0x3189b2ff80d8f728d6fb7503b46734ee77a60a42db01d0b09db10bdc9d5caa44".toBigIntegerFromHex(), ) assertThat(besuTx.signature.recId).isEqualTo(1) assertThat(besuTx.chainId.getOrNull()).isEqualTo(0xe705L) @@ -193,7 +193,7 @@ class EthGetBlockToLineaBlockMapperTest { "r": "0x4f24ed24207bec8591c8172584dc3b57cdf3ee96afbd5e63905a90a704ff33f0", "s": "0x6277bb9d2614843a4791ff2c192e70876438ec940c39d92deb504591b83dfeb3" } - """.trimIndent() + """.trimIndent(), ) val domainTx = txWeb3j.toDomain() @@ -218,11 +218,11 @@ class EthGetBlockToLineaBlockMapperTest { address = "0x8d97689c9818892b700e27f316cc3e41e17fbeb9".decodeHex(), listOf( "0x0000000000000000000000000000000000000000000000000000000000000000".decodeHex(), - "0x0000000000000000000000000000000000000000000000000000000000000001".decodeHex() - ) - ) - ) - ) + "0x0000000000000000000000000000000000000000000000000000000000000001".decodeHex(), + ), + ), + ), + ), ) domainTx.toBesu().also { besuTx -> @@ -233,10 +233,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(besuTx.value).isEqualTo(Wei.of(0x2386f26fc10000L)) assertThat(besuTx.payload).isEqualTo(Bytes.EMPTY) assertThat(besuTx.signature.r).isEqualTo( - "0x4f24ed24207bec8591c8172584dc3b57cdf3ee96afbd5e63905a90a704ff33f0".toBigIntegerFromHex() + "0x4f24ed24207bec8591c8172584dc3b57cdf3ee96afbd5e63905a90a704ff33f0".toBigIntegerFromHex(), ) assertThat(besuTx.signature.s).isEqualTo( - "0x6277bb9d2614843a4791ff2c192e70876438ec940c39d92deb504591b83dfeb3".toBigIntegerFromHex() + "0x6277bb9d2614843a4791ff2c192e70876438ec940c39d92deb504591b83dfeb3".toBigIntegerFromHex(), ) assertThat(besuTx.signature.recId).isEqualTo(1) assertThat(besuTx.type).isEqualTo(org.hyperledger.besu.datatypes.TransactionType.ACCESS_LIST) @@ -250,7 +250,7 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(accessList.get(0).storageKeys) .containsExactly( Bytes32.fromHexString("0x0000000000000000000000000000000000000000000000000000000000000000"), - Bytes32.fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001") + Bytes32.fromHexString("0x0000000000000000000000000000000000000000000000000000000000000001"), ) } } @@ -279,7 +279,7 @@ class EthGetBlockToLineaBlockMapperTest { "r": "0xc57273f9ba15320937d5d9dfd1dc0b18d1e678b34bd3a4bfd29a63e11a856292", "s": "0x7aa875a64835ecc5f9ac1a9fe3ab38d2a62bb3643a2597ab585a5607641a0c57" } - """.trimIndent() + """.trimIndent(), ) val domainTx = txWeb3j.toDomain() @@ -299,8 +299,8 @@ class EthGetBlockToLineaBlockMapperTest { chainId = 0x539UL, maxFeePerGas = null, maxPriorityFeePerGas = null, - accessList = emptyList() - ) + accessList = emptyList(), + ), ) domainTx.toBesu().also { besuTx -> @@ -312,10 +312,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(besuTx.value).isEqualTo(Wei.of(0x2386f26fc10000L)) assertThat(besuTx.payload).isEqualTo(Bytes.EMPTY) assertThat(besuTx.signature.r).isEqualTo( - "0xc57273f9ba15320937d5d9dfd1dc0b18d1e678b34bd3a4bfd29a63e11a856292".toBigIntegerFromHex() + "0xc57273f9ba15320937d5d9dfd1dc0b18d1e678b34bd3a4bfd29a63e11a856292".toBigIntegerFromHex(), ) assertThat(besuTx.signature.s).isEqualTo( - "0x7aa875a64835ecc5f9ac1a9fe3ab38d2a62bb3643a2597ab585a5607641a0c57".toBigIntegerFromHex() + "0x7aa875a64835ecc5f9ac1a9fe3ab38d2a62bb3643a2597ab585a5607641a0c57".toBigIntegerFromHex(), ) assertThat(besuTx.signature.recId).isEqualTo(1) assertThat(besuTx.chainId.getOrNull()).isEqualTo(0x539L) @@ -356,7 +356,7 @@ class EthGetBlockToLineaBlockMapperTest { "maxFeePerGas": "0x1017dff7", "maxPriorityFeePerGas": "0x1017df87" } - """.trimIndent() + """.trimIndent(), ) val txDomain = txWeb3j.toDomain() @@ -378,8 +378,8 @@ class EthGetBlockToLineaBlockMapperTest { chainId = 0x539UL, maxFeePerGas = 0x1017dff7UL, maxPriorityFeePerGas = 0x1017df87UL, - accessList = emptyList() - ) + accessList = emptyList(), + ), ) txDomain.toBesu().also { txBesu -> @@ -391,10 +391,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(txBesu.value).isEqualTo(Wei.of(0x2386f26fc10000L)) assertThat(txBesu.payload).isEqualTo(Bytes.fromHexString(input)) assertThat(txBesu.signature.r).isEqualTo( - "0xeb4f70991ea4f14d23efb32591da3621d551406fd32bdfdd78bb677dec13160a".toBigIntegerFromHex() + "0xeb4f70991ea4f14d23efb32591da3621d551406fd32bdfdd78bb677dec13160a".toBigIntegerFromHex(), ) assertThat(txBesu.signature.s).isEqualTo( - "0x783aaa89f73ef7535924da8fd5f12e15cae1a0811c4c4746d1c23abff1eacddf".toBigIntegerFromHex() + "0x783aaa89f73ef7535924da8fd5f12e15cae1a0811c4c4746d1c23abff1eacddf".toBigIntegerFromHex(), ) assertThat(txBesu.signature.recId).isEqualTo(1) assertThat(txBesu.chainId.getOrNull()).isEqualTo(0x539L) @@ -433,7 +433,7 @@ class EthGetBlockToLineaBlockMapperTest { "r": "0xf7afccb560d0c52bea021ba522a27dbd6c3aba3512dd2d3b2f476ed8dd87d5f7", "s": "0x5f47f6ddcf1c216eb33eb69db553d682de34c78f5a5ab97905a428c2182f32e" } - """.trimIndent() + """.trimIndent(), ) val txDomain = txWeb3j.toDomain() @@ -453,8 +453,8 @@ class EthGetBlockToLineaBlockMapperTest { gasPrice = null, maxFeePerGas = 0xeUL, maxPriorityFeePerGas = 0UL, - accessList = emptyList() - ) + accessList = emptyList(), + ), ) txDomain.toBesu().let { txBesu -> @@ -466,10 +466,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(txBesu.value).isEqualTo(Wei.ZERO) assertThat(txBesu.payload).isEqualTo(Bytes.fromHexString(input)) assertThat(txBesu.signature.r).isEqualTo( - "0xf7afccb560d0c52bea021ba522a27dbd6c3aba3512dd2d3b2f476ed8dd87d5f7".toBigIntegerFromHex() + "0xf7afccb560d0c52bea021ba522a27dbd6c3aba3512dd2d3b2f476ed8dd87d5f7".toBigIntegerFromHex(), ) assertThat(txBesu.signature.s).isEqualTo( - "0x5f47f6ddcf1c216eb33eb69db553d682de34c78f5a5ab97905a428c2182f32e".toBigIntegerFromHex() + "0x5f47f6ddcf1c216eb33eb69db553d682de34c78f5a5ab97905a428c2182f32e".toBigIntegerFromHex(), ) assertThat(txBesu.signature.recId).isEqualTo(1) assertThat(txBesu.chainId.getOrNull()).isEqualTo(0x539L) @@ -502,7 +502,7 @@ class EthGetBlockToLineaBlockMapperTest { "v": "0x1b", "value": "0x0" } - """.trimIndent() + """.trimIndent(), ) val domainTx = txWeb3j.toDomain() assertThat(domainTx).isEqualTo( @@ -522,8 +522,8 @@ class EthGetBlockToLineaBlockMapperTest { chainId = null, maxFeePerGas = null, maxPriorityFeePerGas = null, - accessList = null - ) + accessList = null, + ), ) domainTx.toBesu().also { besuTx -> assertThat(besuTx.type).isEqualTo(org.hyperledger.besu.datatypes.TransactionType.FRONTIER) @@ -534,10 +534,10 @@ class EthGetBlockToLineaBlockMapperTest { assertThat(besuTx.value).isEqualTo(Wei.of(0x0)) assertThat(besuTx.payload).isEqualTo(Bytes.fromHexString(input)) assertThat(besuTx.signature.r).isEqualTo( - "0x98cf46978ebd95f2f61780c767b1ad392beaa11b68f0e310728f5be8296e752a".toBigIntegerFromHex() + "0x98cf46978ebd95f2f61780c767b1ad392beaa11b68f0e310728f5be8296e752a".toBigIntegerFromHex(), ) assertThat(besuTx.signature.s).isEqualTo( - "0x1c621c3046755e5600d73b83a0c28676b02a7dff6b89f76b02f5eddd7817854".toBigIntegerFromHex() + "0x1c621c3046755e5600d73b83a0c28676b02a7dff6b89f76b02f5eddd7817854".toBigIntegerFromHex(), ) assertThat(besuTx.signature.recId).isEqualTo(0) assertThat(besuTx.chainId.getOrNull()).isNull() diff --git a/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/Eip4844TransactionTest.kt b/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/Eip4844TransactionTest.kt index ca5754e7..48399780 100644 --- a/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/Eip4844TransactionTest.kt +++ b/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/Eip4844TransactionTest.kt @@ -29,7 +29,7 @@ class Eip4844TransactionTest { maxFeePerGas = BigInteger.valueOf(8), _maxFeePerBlobGas = BigInteger.valueOf(9), blobs = listOf(Blob(blobByteArray)), - blobVersionedHashes = listOf("0x010657f37554c781402a22917dee2f75def7ab966d7b770905398eba3c444014".decodeHex()) + blobVersionedHashes = listOf("0x010657f37554c781402a22917dee2f75def7ab966d7b770905398eba3c444014".decodeHex()), ) val serializedBlob = Numeric.toHexString(blobByteArray) diff --git a/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/FeeHistoryExtensionsTest.kt b/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/FeeHistoryExtensionsTest.kt index bc090f42..213d7812 100644 --- a/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/FeeHistoryExtensionsTest.kt +++ b/jvm-libs/linea/web3j-extensions/src/test/kotlin/net/consensys/linea/web3j/FeeHistoryExtensionsTest.kt @@ -23,8 +23,8 @@ class FeeHistoryExtensionsTest { reward = listOf(listOf("ba1", "ba2").map { it.toULong(16) }), gasUsedRatio = listOf(0.25), baseFeePerBlobGas = listOf(0uL), - blobGasUsedRatio = listOf(0.0) - ) + blobGasUsedRatio = listOf(0.0), + ), ) } @@ -36,8 +36,8 @@ class FeeHistoryExtensionsTest { this.setReward( listOf( listOf("0xba1", "0xba2"), - listOf("0xbb1", "0xbb2") - ) + listOf("0xbb1", "0xbb2"), + ), ) this.gasUsedRatio = listOf(0.25, 0.75) } @@ -48,12 +48,12 @@ class FeeHistoryExtensionsTest { baseFeePerGas = listOf("a1", "a2", "a3").map { it.toULong(16) }, reward = listOf( listOf("ba1", "ba2").map { it.toULong(16) }, - listOf("bb1", "bb2").map { it.toULong(16) } + listOf("bb1", "bb2").map { it.toULong(16) }, ), gasUsedRatio = listOf(0.25, 0.75), baseFeePerBlobGas = listOf(0uL), - blobGasUsedRatio = listOf(0.0) - ) + blobGasUsedRatio = listOf(0.0), + ), ) } } diff --git a/jvm-libs/linea/web3j-extensions/src/testFixtures/kotlin/linea/web3j/Pollers.kt b/jvm-libs/linea/web3j-extensions/src/testFixtures/kotlin/linea/web3j/Pollers.kt index 57a0859f..c8b5d23b 100644 --- a/jvm-libs/linea/web3j-extensions/src/testFixtures/kotlin/linea/web3j/Pollers.kt +++ b/jvm-libs/linea/web3j-extensions/src/testFixtures/kotlin/linea/web3j/Pollers.kt @@ -21,7 +21,7 @@ fun Web3j.waitForTxReceipt( expectedStatus: String? = null, timeout: Duration = 5.seconds, pollingInterval: Duration = 500.milliseconds, - log: Logger = LogManager.getLogger("linea.web3j.waitForTxReceipt") + log: Logger = LogManager.getLogger("linea.web3j.waitForTxReceipt"), ): TransactionReceipt { val waitLimit = System.currentTimeMillis() + timeout.inWholeMilliseconds log.debug("polling tx receipt txHash=$txHash") @@ -38,7 +38,7 @@ fun Web3j.waitForTxReceipt( if (expectedStatus != null && receipt.status != expectedStatus) { throw RuntimeException( "Transaction status does not match expected status: " + - "txHash=$txHash, expected=$expectedStatus, actual=${receipt.status}" + "txHash=$txHash, expected=$expectedStatus, actual=${receipt.status}", ) } return receipt diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ArrayParameter.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ArrayParameter.java index 6cfc0108..f336ae58 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ArrayParameter.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ArrayParameter.java @@ -206,4 +206,3 @@ public class ArrayParameter extends Parameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/BatchMint.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/BatchMint.java index e42fdd0d..d1389a06 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/BatchMint.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/BatchMint.java @@ -233,4 +233,3 @@ public class BatchMint extends MethodAndParameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallContractReference.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallContractReference.java index bab7ff5c..ae2793cd 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallContractReference.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallContractReference.java @@ -221,4 +221,3 @@ public class CallContractReference extends Contract { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallExistingContract.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallExistingContract.java index 15f9e74b..03477ad0 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallExistingContract.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CallExistingContract.java @@ -221,4 +221,3 @@ public class CallExistingContract extends Contract { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Context.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Context.java index e724c126..14d7be1c 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Context.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Context.java @@ -300,4 +300,3 @@ public class Context { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Contract.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Contract.java index 4095f4d9..27fc2eec 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Contract.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Contract.java @@ -159,4 +159,3 @@ public class Contract { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ContractCall.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ContractCall.java index bb3baed7..d787f232 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ContractCall.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ContractCall.java @@ -221,4 +221,3 @@ public class ContractCall extends Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CreateContract.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CreateContract.java index efd0199d..9245696c 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CreateContract.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/CreateContract.java @@ -238,4 +238,3 @@ public class CreateContract extends Contract { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/GenericCall.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/GenericCall.java index 2a31d218..fbac0e61 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/GenericCall.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/GenericCall.java @@ -258,4 +258,3 @@ public class GenericCall extends MethodAndParameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/MethodAndParameter.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/MethodAndParameter.java index d86b5020..c0d4fe51 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/MethodAndParameter.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/MethodAndParameter.java @@ -189,4 +189,3 @@ public class MethodAndParameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Mint.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Mint.java index f72ca581..f2c3bdfa 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Mint.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Mint.java @@ -223,4 +223,3 @@ public class Mint extends MethodAndParameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Parameter.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Parameter.java index 9a0ef50e..72597613 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Parameter.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Parameter.java @@ -156,4 +156,3 @@ public class Parameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Request.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Request.java index a27e0133..415e24a7 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Request.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Request.java @@ -302,4 +302,3 @@ public class Request { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/RoundRobinMoneyTransfer.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/RoundRobinMoneyTransfer.java index d4256ac4..75067f8a 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/RoundRobinMoneyTransfer.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/RoundRobinMoneyTransfer.java @@ -221,4 +221,3 @@ public class RoundRobinMoneyTransfer extends Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Scenario.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Scenario.java index 72896cb4..fbca4328 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Scenario.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/Scenario.java @@ -165,4 +165,3 @@ public class Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ScenarioDefinition.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ScenarioDefinition.java index c4a8b8d0..39bbaa68 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ScenarioDefinition.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/ScenarioDefinition.java @@ -216,4 +216,3 @@ public class ScenarioDefinition { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithPayload.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithPayload.java index 2a230eba..b1abf4d7 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithPayload.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithPayload.java @@ -295,4 +295,3 @@ public class SelfTransactionWithPayload extends Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithRandomPayload.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithRandomPayload.java index 42abd7df..269ffc1f 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithRandomPayload.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SelfTransactionWithRandomPayload.java @@ -295,4 +295,3 @@ public class SelfTransactionWithRandomPayload extends Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SimpleParameter.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SimpleParameter.java index 8ef85b68..ac238662 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SimpleParameter.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/SimpleParameter.java @@ -221,4 +221,3 @@ public class SimpleParameter extends Parameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/TransferOwnership.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/TransferOwnership.java index 84f6cbe8..ac2d4f30 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/TransferOwnership.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/TransferOwnership.java @@ -198,4 +198,3 @@ public class TransferOwnership extends MethodAndParameter { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/UnderPricedTransaction.java b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/UnderPricedTransaction.java index e8456a15..d156a35e 100644 --- a/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/UnderPricedTransaction.java +++ b/testing-tools/app/src/main/java/net/consensys/zkevm/load/swagger/UnderPricedTransaction.java @@ -196,4 +196,3 @@ public class UnderPricedTransaction extends Scenario { return JSON.getGson().toJson(this); } } - diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/LineaEstimateGasResponse.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/LineaEstimateGasResponse.kt index 1ed40c02..048e3ca4 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/LineaEstimateGasResponse.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/LineaEstimateGasResponse.kt @@ -24,7 +24,7 @@ class LineaEstimateGasResponse : Response>, - walletListMap: Map> + walletListMap: Map>, ) { walletListMap.forEach { (k: Wallet, v: List) -> if (txs.containsKey(k)) { @@ -178,7 +178,7 @@ class TestExecutor(request: String, pk: String) { @Throws(IOException::class, InterruptedException::class) private fun prepareContracts( contracts: List?, - chainId: Int + chainId: Int, ): Map { val contractAdresses: MutableMap = HashMap() for (contract in contracts!!) { @@ -188,7 +188,7 @@ class TestExecutor(request: String, pk: String) { "[CONTRACT] contract {} created with address {} and owner {}", contract.name, contractAdresses[contract.name], - sourceWallet + sourceWallet, ) } return contractAdresses @@ -199,12 +199,18 @@ class TestExecutor(request: String, pk: String) { return when (scenario) { is RoundRobinMoneyTransfer -> { val transactionForEstimation = Transaction.createEtherTransaction( - /* from = */ sourceWallet.address, - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ Numeric.prependHexPrefix(sourceWallet.address), - /* value = */ RoundRobinMoneyTransfer.valueToTransfer + /* from = */ + sourceWallet.address, + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + Numeric.prependHexPrefix(sourceWallet.address), + /* value = */ + RoundRobinMoneyTransfer.valueToTransfer, ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) @@ -214,20 +220,27 @@ class TestExecutor(request: String, pk: String) { chainId = chainId, gasPerCall = gasLimit, gasPricePerCall = gasPrice, - valuePerCall = RoundRobinMoneyTransfer.valueToTransfer + valuePerCall = RoundRobinMoneyTransfer.valueToTransfer, ) } is SelfTransactionWithPayload -> { if (scenario.wallet == NEW) { val transactionForEstimation = Transaction( - /* from = */ sourceWallet.address, - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ Numeric.prependHexPrefix(sourceWallet.address), - /* value = */ null, - /* data = */ Numeric.toHexString(scenario.payload.toByteArray()) + /* from = */ + sourceWallet.address, + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + Numeric.prependHexPrefix(sourceWallet.address), + /* value = */ + null, + /* data = */ + Numeric.toHexString(scenario.payload.toByteArray()), ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) @@ -237,7 +250,7 @@ class TestExecutor(request: String, pk: String) { nbTransferPerWallets = scenario.nbTransfers, chainId = chainId, gasPerCall = gasLimit, - gasPricePerCall = gasPrice + gasPricePerCall = gasPrice, ) } else { java.util.Map.of(-1, sourceWallet) @@ -248,13 +261,20 @@ class TestExecutor(request: String, pk: String) { if (scenario.wallet == NEW) { val payload = Util.generateRandomPayloadOfSize(scenario.payloadSize) val transactionForEstimation = Transaction( - /* from = */ sourceWallet.address, - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ Numeric.prependHexPrefix(sourceWallet.address), - /* value = */ null, - /* data = */ Numeric.toHexString(payload.toByteArray()) + /* from = */ + sourceWallet.address, + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + Numeric.prependHexPrefix(sourceWallet.address), + /* value = */ + null, + /* data = */ + Numeric.toHexString(payload.toByteArray()), ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) @@ -264,7 +284,7 @@ class TestExecutor(request: String, pk: String) { nbTransferPerWallets = scenario.nbTransfers, chainId = chainId, gasPerCall = gasLimit, - gasPricePerCall = gasPrice + gasPricePerCall = gasPrice, ) } else { java.util.Map.of(-1, sourceWallet) @@ -280,7 +300,7 @@ class TestExecutor(request: String, pk: String) { nbTransferPerWallets = scenario.contract.nbCalls(), chainId = chainId, gasPerCall = scenario.gasLimit(), - gasPricePerCall = gasPrice + gasPricePerCall = gasPrice, ) } else { java.util.Map.of() @@ -298,7 +318,7 @@ class TestExecutor(request: String, pk: String) { scenario: Scenario?, chainId: Int, walletMap: Map, - contractAddresses: Map + contractAddresses: Map, ): Map> { return when (scenario) { is RoundRobinMoneyTransfer -> { @@ -310,7 +330,7 @@ class TestExecutor(request: String, pk: String) { scenario.payload, chainId, walletMap, - scenario.nbTransfers + scenario.nbTransfers, ) } @@ -319,7 +339,7 @@ class TestExecutor(request: String, pk: String) { scenario.payloadSize, chainId, walletMap, - scenario.nbTransfers + scenario.nbTransfers, ) } @@ -336,7 +356,7 @@ class TestExecutor(request: String, pk: String) { payloadSize: Int, chainId: Int, walletMap: Map, - nbTransfers: Int + nbTransfers: Int, ): Map> { return walletsFunding.generateTxWithRandomPayload(walletMap, payloadSize, chainId, nbTransfers) } @@ -346,7 +366,7 @@ class TestExecutor(request: String, pk: String) { payload: String, chainId: Int, walletMap: Map, - nbTransfers: Int + nbTransfers: Int, ): Map> { return walletsFunding.generateTxsWithPayload(walletMap, payload, chainId, nbTransfers) } @@ -356,7 +376,7 @@ class TestExecutor(request: String, pk: String) { call: ContractCall, chainId: Int, contractAddresses: Map, - walletMap: Map + walletMap: Map, ): Map> { return when (val contractType = call.contract) { is CallExistingContract -> { @@ -364,7 +384,7 @@ class TestExecutor(request: String, pk: String) { call.wallet(sourceWallet, walletMap), contractType.contractAddress, contractType.methodAndParameters, - chainId + chainId, ) } @@ -372,7 +392,7 @@ class TestExecutor(request: String, pk: String) { prepareContractCreation( call.wallet(sourceWallet, walletMap), contractType, - chainId + chainId, ) } @@ -382,7 +402,7 @@ class TestExecutor(request: String, pk: String) { call.wallet(sourceWallet, walletMap), address!!, contractType.methodAndParameters, - chainId + chainId, ) } @@ -395,49 +415,48 @@ class TestExecutor(request: String, pk: String) { wallet: Wallet, contractAddress: String, methodAndParameters: MethodAndParameter?, - chainId: Int - ): - Map> { + chainId: Int, + ): Map> { return when (methodAndParameters) { is GenericCall -> { val encodedFunction = smartContractCalls.genericCall( methodAndParameters.methodName, - methodAndParameters.parameters + methodAndParameters.parameters, ) smartContractCalls.getRequests( contractAddress, wallet, encodedFunction, methodAndParameters.nbOfTimes, - chainId + chainId, ) } is Mint -> { val encodedFunction = smartContractCalls.mint( methodAndParameters.address, - methodAndParameters.amount.toLong() + methodAndParameters.amount.toLong(), ) smartContractCalls.getRequests( contractAddress, wallet, encodedFunction, methodAndParameters.nbOfTimes, - chainId + chainId, ) } is BatchMint -> { val encodedFunction = smartContractCalls.batchMint( methodAndParameters.address, - methodAndParameters.amount.toLong() + methodAndParameters.amount.toLong(), ) smartContractCalls.getRequests( contractAddress, wallet, encodedFunction, methodAndParameters.nbOfTimes, - chainId + chainId, ) } @@ -449,7 +468,7 @@ class TestExecutor(request: String, pk: String) { wallet, encodedFunction, methodAndParameters.nbOfTimes, - chainId + chainId, ) } @@ -461,18 +480,17 @@ class TestExecutor(request: String, pk: String) { private fun prepareContractCreation( wallet: Wallet, contract: CreateContract, - chainId: Int - ): - Map> { + chainId: Int, + ): Map> { return java.util.Map.of( wallet, listOf( smartContractCalls.getCreateContractTransaction( wallet, contract.byteCode, - chainId - ) - ) + chainId, + ), + ), ) } @@ -481,7 +499,7 @@ class TestExecutor(request: String, pk: String) { NoSuchAlgorithmException::class, NoSuchProviderException::class, IOException::class, - InterruptedException::class + InterruptedException::class, ) private fun prepareWallets( nbWallets: Int, @@ -489,7 +507,7 @@ class TestExecutor(request: String, pk: String) { chainId: Int, gasPerCall: BigInteger, gasPricePerCall: BigInteger, - valuePerCall: BigInteger = BigInteger.ZERO + valuePerCall: BigInteger = BigInteger.ZERO, ): Map { val wallets: Map = createWallets(nbWallets) executionDetails.addInitialization( @@ -500,8 +518,8 @@ class TestExecutor(request: String, pk: String) { chainId = chainId, gasPerCall = gasPerCall, gasPricePerCall = gasPricePerCall, - valuePerCall = valuePerCall - ) + valuePerCall = valuePerCall, + ), ) return wallets } @@ -510,13 +528,13 @@ class TestExecutor(request: String, pk: String) { private fun generateTxs( nbTransferPerWallets: Int, wallets: Map, - chainId: Int + chainId: Int, ): Map> { return walletsFunding.generateTransactions( wallets, RoundRobinMoneyTransfer.valueToTransfer, nbTransferPerWallets, - chainId + chainId, ) } } diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/WalletsFunding.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/WalletsFunding.kt index a30c0684..15acf7b1 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/WalletsFunding.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/WalletsFunding.kt @@ -17,7 +17,7 @@ import java.util.function.Consumer class WalletsFunding( private val ethConnection: EthConnection, - private val sourceOfFundsWallet: Wallet + private val sourceOfFundsWallet: Wallet, ) { @Throws(IOException::class) @@ -25,14 +25,14 @@ class WalletsFunding( wallets: Map, payloadSize: Int, chainId: Int, - nbTransfers: Int + nbTransfers: Int, ): Map> { val payload = Util.generateRandomPayloadOfSize(payloadSize) return generateTxsWithPayload( wallets = wallets, payLoad = payload, chainId = chainId, - nbTransfers = nbTransfers + nbTransfers = nbTransfers, ) } @@ -40,7 +40,7 @@ class WalletsFunding( wallets: Map, payLoad: String, chainId: Int, - nbTransfers: Int + nbTransfers: Int, ): MutableMap> { val result: MutableMap> = HashMap() @@ -48,31 +48,44 @@ class WalletsFunding( val txs = ArrayList() for (i in 0 until nbTransfers) { val transactionForEstimation = Transaction( - /* from = */ sourceWallet.address, - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ Numeric.prependHexPrefix(sourceWallet.address), - /* value = */ null, - /* data = */ payLoad + /* from = */ + sourceWallet.address, + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + Numeric.prependHexPrefix(sourceWallet.address), + /* value = */ + null, + /* data = */ + payLoad, ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) val rawTransaction = RawTransaction.createTransaction( - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ gasPrice, - /* gasLimit = */ gasLimit, - /* to = */ Numeric.prependHexPrefix(sourceWallet.address), - /* value = */ BigInteger.ZERO, - /* data = */ payLoad + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + gasPrice, + /* gasLimit = */ + gasLimit, + /* to = */ + Numeric.prependHexPrefix(sourceWallet.address), + /* value = */ + BigInteger.ZERO, + /* data = */ + payLoad, ) txs.add( TransactionDetail( sourceWallet.id, sourceWallet.theoreticalNonceValue, - ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId) - ) + ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId), + ), ) sourceWallet.incrementTheoreticalNonce() @@ -86,7 +99,7 @@ class WalletsFunding( @Throws(IOException::class) fun generateUnderPricedTxs( wallets: Map, - chainId: Int + chainId: Int, ): Map> { val gasUnderPriced = ethConnection.ethGasPrice().multiply(BigInteger.valueOf(80)) .divide(BigInteger.valueOf(100)) @@ -100,14 +113,14 @@ class WalletsFunding( costPerCall, Numeric.prependHexPrefix(sourceWallet.address), BigInteger.ZERO, - null + null, ) result[sourceWallet] = listOf( TransactionDetail( sourceWallet.id, sourceWallet.theoreticalNonceValue, - ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId) - ) + ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId), + ), ) sourceWallet.incrementTheoreticalNonce() } @@ -123,7 +136,7 @@ class WalletsFunding( chainId: Int, gasPerCall: BigInteger, gasPricePerCall: BigInteger, - valuePerCall: BigInteger + valuePerCall: BigInteger, ): Map> { val balance = ethConnection.getBalance(sourceWallet) logger.info("[FUNDING] source of funds balance is {}.", balance) @@ -137,7 +150,7 @@ class WalletsFunding( logger.debug( "[FUNDING] gas price is {}, transferred amount is {}.", gasPricePerCall, - transferredAmount + transferredAmount, ) val fundingTransfers: ArrayList = ArrayList() for ((_, value) in wallets) { @@ -148,28 +161,28 @@ class WalletsFunding( gasPrice = gasPricePerCall, gasLimit = EthConnection.SIMPLE_TX_PRICE, initialAmount = transferredAmount, - chainId = chainId + chainId = chainId, ) fundingTransfers.add( TransactionDetail( sourceOfFundsWallet.id, nonce, - rawTx - ) + rawTx, + ), ) val res = rawTx.send() logger.debug( "[FUNDING] Transfer fund transaction sent for nonce:{}, hash:{}, {}.", nonce, res.transactionHash, - if (res.error != null) " error:" + res.error.message else "no error" + if (res.error != null) " error:" + res.error.message else "no error", ) nonce = nonce.add(BigInteger.ONE) } logger.info("[FUNDING] Waiting for fund transfer.") while (ethConnection.ethGetTransactionCount( sourceOfFundsWallet.encodedAddress(), - DefaultBlockParameterName.LATEST + DefaultBlockParameterName.LATEST, ) < nonce ) { Thread.sleep(10) @@ -186,14 +199,14 @@ class WalletsFunding( gasPrice: BigInteger, gasLimit: BigInteger, initialAmount: BigInteger, - chainId: Int + chainId: Int, ): Request<*, EthSendTransaction> { val rawTransaction = RawTransaction.createEtherTransaction( nonce, gasPrice, gasLimit, Numeric.prependHexPrefix(toAddress), - initialAmount + initialAmount, ) return ethConnection.ethSendRawTransaction(rawTransaction, wallet, chainId) } @@ -203,7 +216,7 @@ class WalletsFunding( wallets: Map, valueToTransfer: BigInteger, nbTransactions: Int, - chainId: Int + chainId: Int, ): Map> { // check wallet balance, it helps to ensure wallets exist. wallets.values.forEach(Consumer { a: Wallet? -> ethConnection.getBalance(a!!) }) @@ -215,7 +228,7 @@ class WalletsFunding( valueToTransfer, nbTransactions, initialNoncePerWallet, - chainId + chainId, ) } @@ -230,9 +243,8 @@ class WalletsFunding( value: BigInteger, nbTransactions: Int, initialNoncePerWallet: Map>, - chainId: Int - ): - Map> { + chainId: Int, + ): Map> { val transactions: MutableMap> = HashMap() val gasPrice = ethConnection.ethGasPrice() for ((wallet) in initialNoncePerWallet) { @@ -249,14 +261,14 @@ class WalletsFunding( gasPrice, EthConnection.SIMPLE_TX_PRICE, value, - chainId + chainId, ) transactions[wallet]!!.add( TransactionDetail( walletId, nonce, - rawTransaction - ) + rawTransaction, + ), ) wallet.incrementTheoreticalNonce() } @@ -268,13 +280,13 @@ class WalletsFunding( wallets: Map, wallet: Wallet, walletId: Int, - i: Int + i: Int, ): String { val walletDestinationId = (walletId + i + 1) % wallets.size logger.debug( "[TRANSFER] preparing transactions from wallet {} to wallet {}", wallet, - walletDestinationId + walletDestinationId, ) return wallets[walletDestinationId]!!.address } diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/EthConnectionImpl.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/EthConnectionImpl.kt index 524c3f36..29763b42 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/EthConnectionImpl.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/EthConnectionImpl.kt @@ -55,7 +55,7 @@ class EthConnectionImpl(url: String?) : EthConnection { override fun ethSendRawTransaction( rawTransaction: RawTransaction?, sourceWallet: Wallet, - chainId: Int + chainId: Int, ): Request<*, EthSendTransaction> { val signedMessage = TransactionEncoder.signMessage(rawTransaction, chainId.toLong(), sourceWallet.credentials) val hexValue = Numeric.toHexString(signedMessage) @@ -64,7 +64,7 @@ class EthConnectionImpl(url: String?) : EthConnection { override fun ethGetTransactionCount( sourceOfFundsAddress: String?, - defaultBlockParameterName: DefaultBlockParameterName? + defaultBlockParameterName: DefaultBlockParameterName?, ): BigInteger { return web3.ethGetTransactionCount(sourceOfFundsAddress, defaultBlockParameterName).send().transactionCount } @@ -92,10 +92,10 @@ class EthConnectionImpl(url: String?) : EthConnection { val lineaEstimateGasResponseRequest = Request( "linea_estimateGas", listOf( - transaction + transaction, ), httpService, - LineaEstimateGasResponse::class.java + LineaEstimateGasResponse::class.java, ) return httpService.send(lineaEstimateGasResponseRequest, LineaEstimateGasResponse::class.java) } @@ -122,7 +122,8 @@ class EthConnectionImpl(url: String?) : EthConnection { Collectors.toMap( { (key): Map.Entry> -> key }, Function>, BigInteger> { (key, value): - Map.Entry> -> + Map.Entry>, + -> val sorted = value.stream().sorted { s: TransactionDetail, t: TransactionDetail -> 1 * s.nonce.compareTo(t.nonce) } .toList() @@ -131,8 +132,8 @@ class EthConnectionImpl(url: String?) : EthConnection { } else { sendAllTransactions(sorted[0], sorted.subList(1, sorted.size)) } - } - ) + }, + ), ) } @@ -154,9 +155,9 @@ class EthConnectionImpl(url: String?) : EthConnection { walletId, res.id, transaction.nonce, - res.transactionHash + res.transactionHash, ) - if (transaction.expectedOutcome == EXPECTED_OUTCOME.SUCCESS) { + if (transaction.expectedOutcome == ExpectedOutcome.SUCCESS) { succeeded.add(transaction.nonce) } else { failed.add(transaction.nonce) @@ -168,13 +169,13 @@ class EthConnectionImpl(url: String?) : EthConnection { transaction.nonce, res.transactionHash, walletId, - res.error.message + res.error.message, ) failed.add(transaction.nonce) } return@map Tuple2>( transaction, - Optional.of(res) + Optional.of(res), ) } catch (e: IOException) { logger.error("Error while sending transaction " + transaction.ethSendTransactionRequest.id) @@ -192,9 +193,9 @@ class EthConnectionImpl(url: String?) : EthConnection { first.walletId, res.id, first.nonce, - res.transactionHash + res.transactionHash, ) - if (first.expectedOutcome == EXPECTED_OUTCOME.SUCCESS) { + if (first.expectedOutcome == ExpectedOutcome.SUCCESS) { succeeded.add(first.nonce) } else { failed.add(first.nonce) @@ -206,7 +207,7 @@ class EthConnectionImpl(url: String?) : EthConnection { res.id, res.transactionHash, first.walletId, - res.error.message + res.error.message, ) failed.add(first.nonce) } @@ -217,21 +218,21 @@ class EthConnectionImpl(url: String?) : EthConnection { list.stream().collect( Collectors.toMap( { t: Tuple2> -> t.component1().nonce }, - { t: Tuple2> -> getTransactionHash(t) } - ) - ) + { t: Tuple2> -> getTransactionHash(t) }, + ), + ), ) logger.info( "Wallet id: {}, number of transaction sent attempt:{}, succeeded:{}, failed:{}.", first.walletId, succeeded.size + failed.size, succeeded.size, - failed.size + failed.size, ) logger.info( "Wallet id: {}, number of transaction hash:{}.", first.walletId, - nonceToHash.values.stream().filter { v: String -> !v.startsWith("noTransactionHash") }.count() + nonceToHash.values.stream().filter { v: String -> !v.startsWith("noTransactionHash") }.count(), ) return if (failed.isEmpty()) { succeeded.stream().max { obj: BigInteger, `val`: BigInteger? -> obj.compareTo(`val`) }.get() @@ -264,7 +265,7 @@ class EthConnectionImpl(url: String?) : EthConnection { "{} walets used to send {} requests in {}s. Waiting for their completion.", transactions.size, transactions.values.stream().mapToInt { v: List -> v.size }.sum(), - Instant.now().epochSecond - startTime.epochSecond + Instant.now().epochSecond - startTime.epochSecond, ) return targetNoncePerWallets } @@ -272,7 +273,7 @@ class EthConnectionImpl(url: String?) : EthConnection { override fun getEthGetBlockByNumber(blockId: Long): EthBlock { return web3.ethGetBlockByNumber( DefaultBlockParameter.valueOf(BigInteger.valueOf(blockId)), - true + true, ).send() } @@ -287,7 +288,7 @@ class EthConnectionImpl(url: String?) : EthConnection { try { val ethGetTransactionCount = ethGetTransactionCount( encodedAddress, - DefaultBlockParameterName.LATEST + DefaultBlockParameterName.LATEST, ) return ethGetTransactionCount } catch (e: SocketTimeoutException) { @@ -320,14 +321,14 @@ interface EthConnection { fun ethSendRawTransaction( rawTransaction: RawTransaction?, sourceWallet: Wallet, - chainId: Int + chainId: Int, ): Request<*, EthSendTransaction> fun getBalance(sourceWallet: Wallet): BigInteger? fun getNonce(encodedAddress: String?): BigInteger fun ethGetTransactionCount( sourceOfFundsAddress: String?, - defaultBlockParameterName: DefaultBlockParameterName? + defaultBlockParameterName: DefaultBlockParameterName?, ): BigInteger fun estimateGas(transaction: Transaction): BigInteger diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/SmartContractCalls.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/SmartContractCalls.kt index f13633b0..e881ba72 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/SmartContractCalls.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/SmartContractCalls.kt @@ -72,7 +72,7 @@ class SmartContractCalls(private val ethConnection: EthConnection) { fun batchMint(addressesInput: List, inputAmount: Long): String { @Suppress("DEPRECATION") val addresses = DynamicArray( - addressesInput.stream().map { address: String? -> Address(address) }.toList() + addressesInput.stream().map { address: String? -> Address(address) }.toList(), ) val amount = Uint256(BigInteger.valueOf(inputAmount)) val function = Function("batchMint", listOf(addresses, amount), emptyList()) @@ -84,7 +84,7 @@ class SmartContractCalls(private val ethConnection: EthConnection) { sourceWallet: Wallet, contractCode: CreateContract, chainId: Int, - details: ExecutionDetails + details: ExecutionDetails, ): String { val contractCreationTx = getCreateContractTransaction(sourceWallet, contractCode.byteCode, chainId) @@ -96,9 +96,9 @@ class SmartContractCalls(private val ethConnection: EthConnection) { // maybe transaction receipt is not directly present, we may have to retry. var attempt = 0 while (( - !transactionReceipt.transactionReceipt.isPresent || - transactionReceipt.transactionReceipt.get().contractAddress == null - ) && + !transactionReceipt.transactionReceipt.isPresent || + transactionReceipt.transactionReceipt.get().contractAddress == null + ) && attempt < 3 ) { transactionReceipt = ethConnection.ethGetTransactionReceipt(receipt.transactionHash).send() @@ -117,28 +117,40 @@ class SmartContractCalls(private val ethConnection: EthConnection) { fun getCreateContractTransaction( sourceWallet: Wallet, contractCode: String?, - chainId: Int + chainId: Int, ): TransactionDetail { val nonce = sourceWallet.theoreticalNonceValue sourceWallet.incrementTheoreticalNonce() val transactionForEstimation = Transaction( - /* from = */ sourceWallet.address, - /* nonce = */ nonce, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ null, - /* value = */ null, - /* data = */ contractCode + /* from = */ + sourceWallet.address, + /* nonce = */ + nonce, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + null, + /* value = */ + null, + /* data = */ + contractCode, ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) val rawTransaction = RawTransaction.createContractTransaction( - /* nonce = */ nonce, - /* gasPrice = */ gasPrice, - /* gasLimit = */ gasLimit, - /* value = */ BigInteger.ZERO, - /* init = */ contractCode + /* nonce = */ + nonce, + /* gasPrice = */ + gasPrice, + /* gasLimit = */ + gasLimit, + /* value = */ + BigInteger.ZERO, + /* init = */ + contractCode, ) val contractCreationTx = ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId) return TransactionDetail(sourceWallet.id, nonce, contractCreationTx) @@ -150,35 +162,46 @@ class SmartContractCalls(private val ethConnection: EthConnection) { sourceWallet: Wallet, encodedFunction: String, txCount: Int, - chainId: Int - ): - Map> { + chainId: Int, + ): Map> { val txs: MutableList = ArrayList() for (i in 0 until txCount) { val transactionForEstimation = Transaction( - /* from = */ sourceWallet.address, - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ null, - /* gasLimit = */ null, - /* to = */ contractAddress, - /* value = */ null, - /* data = */ encodedFunction + /* from = */ + sourceWallet.address, + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + null, + /* gasLimit = */ + null, + /* to = */ + contractAddress, + /* value = */ + null, + /* data = */ + encodedFunction, ) val (gasPrice, gasLimit) = ethConnection.estimateGasPriceAndLimit(transactionForEstimation) val rawTransaction = RawTransaction.createTransaction( - /* nonce = */ sourceWallet.theoreticalNonceValue, - /* gasPrice = */ gasPrice, - /* gasLimit = */ gasLimit, - /* to = */ contractAddress, - /* data = */ encodedFunction + /* nonce = */ + sourceWallet.theoreticalNonceValue, + /* gasPrice = */ + gasPrice, + /* gasLimit = */ + gasLimit, + /* to = */ + contractAddress, + /* data = */ + encodedFunction, ) txs.add( TransactionDetail( sourceWallet.id, sourceWallet.theoreticalNonceValue, - ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId) - ) + ethConnection.ethSendRawTransaction(rawTransaction, sourceWallet, chainId), + ), ) sourceWallet.incrementTheoreticalNonce() } diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/TransactionDetail.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/TransactionDetail.kt index eacfa1b8..838d3083 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/TransactionDetail.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/TransactionDetail.kt @@ -8,12 +8,12 @@ class TransactionDetail( val walletId: Int, val nonce: BigInteger, @Transient val ethSendTransactionRequest: Request<*, EthSendTransaction>, - val expectedOutcome: EXPECTED_OUTCOME = EXPECTED_OUTCOME.SUCCESS + val expectedOutcome: ExpectedOutcome = ExpectedOutcome.SUCCESS, ) { var hash: String? = null } -enum class EXPECTED_OUTCOME { +enum class ExpectedOutcome { // TODO: NOT_EXECUTED should be used for non profitable or underpriced transactions. FAILED, SUCCESS, NOT_EXECUTED } diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/Wallet.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/Wallet.kt index e7c0ee76..3e5ee503 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/Wallet.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/Wallet.kt @@ -10,7 +10,7 @@ data class Wallet( val credentials: Credentials, val id: Int, @Transient val theoreticalNonce: AtomicReference, - var initialNonce: BigInteger? + var initialNonce: BigInteger?, ) { val address: String = credentials.address @@ -20,7 +20,7 @@ data class Wallet( Credentials.create(privateKey), id, AtomicReference(initialNonce), - initialNonce + initialNonce, ) fun encodedAddress(): String { diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/Request.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/Request.kt index 3bbf2c27..7de3a796 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/Request.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/Request.kt @@ -18,7 +18,7 @@ class Request(val id: Int, val name: String, val calls: List fromJson.id!!, fromJson.name ?: "", fromJson.calls!!.map { c -> translate(c) }.toList(), - translate(fromJson.context) + translate(fromJson.context), ) } @@ -44,7 +44,7 @@ class Request(val id: Int, val name: String, val calls: List EthConnection.SIMPLE_TX_PRICE } else { BigInteger.valueOf(transaction.price!!.toLong()) - } + }, ) } @@ -59,7 +59,7 @@ class Request(val id: Int, val name: String, val calls: List EthConnection.SIMPLE_TX_PRICE } else { BigInteger.valueOf(transaction.price!!.toLong()) - } + }, ) } @@ -100,50 +100,49 @@ class Request(val id: Int, val name: String, val calls: List private fun createContract(contract: net.consensys.zkevm.load.swagger.CreateContract) = CreateContract(contract.name ?: "null", contract.byteCode, contract.gasLimit) - private fun translate(methodAndParameters: net.consensys.zkevm.load.swagger.MethodAndParameter): - MethodAndParameter { - return when (methodAndParameters.type) { + private fun translate(methodAndParams: net.consensys.zkevm.load.swagger.MethodAndParameter): MethodAndParameter { + return when (methodAndParams.type) { "GenericCall" -> { - methodAndParameters as net.consensys.zkevm.load.swagger.GenericCall + methodAndParams as net.consensys.zkevm.load.swagger.GenericCall GenericCall( - methodAndParameters.numberOfTimes, - methodAndParameters.methodName!!, - methodAndParameters.price!!, - methodAndParameters.parameters?.map { p -> translate(p) }?.toList()!! + methodAndParams.numberOfTimes, + methodAndParams.methodName!!, + methodAndParams.price!!, + methodAndParams.parameters?.map { p -> translate(p) }?.toList()!!, ) } "Mint" -> { - methodAndParameters as net.consensys.zkevm.load.swagger.Mint + methodAndParams as net.consensys.zkevm.load.swagger.Mint Mint( - methodAndParameters.numberOfTimes, - methodAndParameters.address ?: "self", - methodAndParameters.amount - ?: 0 + methodAndParams.numberOfTimes, + methodAndParams.address ?: "self", + methodAndParams.amount + ?: 0, ) } "BatchMint" -> { - methodAndParameters as net.consensys.zkevm.load.swagger.BatchMint + methodAndParams as net.consensys.zkevm.load.swagger.BatchMint BatchMint( - methodAndParameters.numberOfTimes, - methodAndParameters.address + methodAndParams.numberOfTimes, + methodAndParams.address ?: listOf("self"), - methodAndParameters.amount ?: 0 + methodAndParams.amount ?: 0, ) } "TransferOwnership" -> { - methodAndParameters as TransferOwnership + methodAndParams as TransferOwnership TransferOwnerShip( - methodAndParameters.numberOfTimes, - methodAndParameters.destinationAddress - ?: "self" + methodAndParams.numberOfTimes, + methodAndParams.destinationAddress + ?: "self", ) } else -> { - throw UnsupportedOperationException(methodAndParameters.toJson()) + throw UnsupportedOperationException(methodAndParams.toJson()) } } } @@ -171,7 +170,7 @@ class Request(val id: Int, val name: String, val calls: List context?.chainId!!, context.contracts?.map { c -> createContract(c) }?.toList() ?: listOf(), context.url!!, - context.nbOfExecutions!! + context.nbOfExecutions!!, ) } } diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithPayload.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithPayload.kt index 039b666c..840dc4ba 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithPayload.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithPayload.kt @@ -7,7 +7,7 @@ class SelfTransactionWithPayload( val nbWallets: Int, val nbTransfers: Int, val payload: String, - val price: BigInteger + val price: BigInteger, ) : Scenario { override fun wallet(): String { return wallet diff --git a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithRandomPayload.kt b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithRandomPayload.kt index 3b1d913f..31dd954c 100644 --- a/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithRandomPayload.kt +++ b/testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/model/inner/SelfTransactionWithRandomPayload.kt @@ -7,7 +7,7 @@ class SelfTransactionWithRandomPayload( val nbWallets: Int, val nbTransfers: Int, val payloadSize: Int, - val price: BigInteger + val price: BigInteger, ) : Scenario { override fun wallet(): String { return wallet diff --git a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/WalletsFundingTest.kt b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/WalletsFundingTest.kt index e3c78fae..982c72a0 100644 --- a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/WalletsFundingTest.kt +++ b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/WalletsFundingTest.kt @@ -2,7 +2,7 @@ package net.consensys.zkevm.load import net.consensys.zkevm.load.model.DummyEthConnection import net.consensys.zkevm.load.model.DummyWalletL1State -import net.consensys.zkevm.load.model.EXPECTED_OUTCOME +import net.consensys.zkevm.load.model.ExpectedOutcome import net.consensys.zkevm.load.model.Wallet import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test @@ -27,14 +27,14 @@ class WalletsFundingTest { mapOf(-1 to sourceWallet, 1 to wallet1, 2 to wallet2), 100, 1944, - 1 + 1, ) assertEquals(3, txs.size) assertEquals(1, txs[wallet1]?.size) assertEquals(1, txs[wallet1]?.get(0)?.walletId) assertEquals(200, txs[wallet1]?.get(0)?.ethSendTransactionRequest?.params?.get(0).toString().length) assertEquals(null, txs[wallet1]?.get(0)?.hash) // not set as not send yet - assertEquals(EXPECTED_OUTCOME.SUCCESS, txs[wallet1]?.get(0)?.expectedOutcome) // move to NOT_EXECUTED ? + assertEquals(ExpectedOutcome.SUCCESS, txs[wallet1]?.get(0)?.expectedOutcome) // move to NOT_EXECUTED ? assertEquals(BigInteger.valueOf(1000), txs[wallet1]?.get(0)?.nonce) assertEquals(BigInteger.valueOf(1001), sourceWallet.theoreticalNonceValue) } @@ -50,7 +50,7 @@ class WalletsFundingTest { 1944, BigInteger.valueOf(2500), BigInteger.valueOf(2500), - BigInteger.valueOf(1) + BigInteger.valueOf(1), ) assertEquals(1, txs.size) @@ -66,7 +66,7 @@ class WalletsFundingTest { mapOf(0 to wallet1, 1 to wallet2), BigInteger.TWO, 2, - 1944 + 1944, ) assertEquals(2, txs.size) @@ -77,7 +77,7 @@ class WalletsFundingTest { fun timeout_waitForTransactions() { assertFailsWith( "should time out", - block = { walletsFunding.waitForTransactions(mapOf(sourceWallet to BigInteger.ONE), 1L) } + block = { walletsFunding.waitForTransactions(mapOf(sourceWallet to BigInteger.ONE), 1L) }, ) } diff --git a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/DummyEthConnection.kt b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/DummyEthConnection.kt index d4f47a19..e64309f7 100644 --- a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/DummyEthConnection.kt +++ b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/DummyEthConnection.kt @@ -40,7 +40,7 @@ class DummyEthConnection : EthConnection { override fun ethSendRawTransaction( rawTransaction: RawTransaction?, sourceWallet: Wallet, - chainId: Int + chainId: Int, ): Request<*, EthSendTransaction> { wallets.get(sourceWallet.encodedAddress())?.wallet?.initialNonce = wallets.get(sourceWallet.encodedAddress())?.wallet?.initialNonce?.add(BigInteger.ONE) @@ -49,7 +49,7 @@ class DummyEthConnection : EthConnection { "eth_sendRawTransaction", Arrays.asList(rawTransaction?.transaction?.data), web3Service, - EthSendTransaction::class.java + EthSendTransaction::class.java, ) } @@ -63,7 +63,7 @@ class DummyEthConnection : EthConnection { override fun ethGetTransactionCount( sourceOfFundsAddress: String?, - defaultBlockParameterName: DefaultBlockParameterName? + defaultBlockParameterName: DefaultBlockParameterName?, ): BigInteger { return wallets.get(sourceOfFundsAddress)?.wallet?.initialNonce!! } @@ -114,7 +114,7 @@ class DummyWeb3jService : Web3jService { override fun ?> subscribe( request: Request<*, out Response<*>>?, unsubscribeMethod: String?, - responseType: Class? + responseType: Class?, ): Flowable { TODO("Not yet implemented") } diff --git a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/SmartContractCallsTest.kt b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/SmartContractCallsTest.kt index 10662b99..77c09ecd 100644 --- a/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/SmartContractCallsTest.kt +++ b/testing-tools/app/src/test/kotlin/net/consensys/zkevm/load/model/SmartContractCallsTest.kt @@ -21,8 +21,8 @@ class SmartContractCallsTest { "mint", listOf( SimpleParameter(DEFAULT_ADDRESS, "Address"), - SimpleParameter("1", "Uint256") - ) + SimpleParameter("1", "Uint256"), + ), ) assertEquals(MINT_ENCODED, callFunction) } @@ -42,7 +42,7 @@ class SmartContractCallsTest { sourceWallet, MINT_ENCODED, 10, - 1944 + 1944, ) assertEquals(1, requests.size) assertEquals(10, requests.get(sourceWallet)?.size) diff --git a/testing-tools/app/src/test/kotlin/swagger/TestJson.kt b/testing-tools/app/src/test/kotlin/swagger/TestJson.kt index fcc10b7d..dad0e65f 100644 --- a/testing-tools/app/src/test/kotlin/swagger/TestJson.kt +++ b/testing-tools/app/src/test/kotlin/swagger/TestJson.kt @@ -17,7 +17,7 @@ class TestJson { """ {"privateKey":"${wallet.privateKey}","credentials":{"ecKeyPair":{"privateKey":${wallet.credentials.ecKeyPair.privateKey},"publicKey":${wallet.credentials.ecKeyPair.publicKey}},"address":"${wallet.credentials.address}"},"id":0,"initialNonce":0,"address":"${wallet.address}"} """.trimIndent(), - JSON.createGson().create().toJson(wallet) + JSON.createGson().create().toJson(wallet), ) } } diff --git a/transaction-decoder-tool/src/test/kotlin/linea/test/BlockEncodingValidator.kt b/transaction-decoder-tool/src/test/kotlin/linea/test/BlockEncodingValidator.kt index 299f4388..9af88ac5 100644 --- a/transaction-decoder-tool/src/test/kotlin/linea/test/BlockEncodingValidator.kt +++ b/transaction-decoder-tool/src/test/kotlin/linea/test/BlockEncodingValidator.kt @@ -29,7 +29,7 @@ class BlockEncodingValidator( val compressorVersion: BlobCompressorVersion = BlobCompressorVersion.V1_2, val decompressorVersion: BlobDecompressorVersion = BlobDecompressorVersion.V1_2_0, val blobSizeLimitBytes: UInt = BLOB_COMPRESSOR_SIZE, - val log: Logger = LogManager.getLogger(BlockEncodingValidator::class.java) + val log: Logger = LogManager.getLogger(BlockEncodingValidator::class.java), ) : PeriodicPollingService(vertx, pollingIntervalMs = 1.milliseconds.inWholeMilliseconds, log = log) { val compressor = GoBackedBlobCompressor.getInstance(compressorVersion, blobSizeLimitBytes.toInt()) @@ -55,7 +55,7 @@ class BlockEncodingValidator( if (unMatchingBlocks.isEmpty()) { log.info( "all blocks encoding/decoding match: blocks={}", - CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number) + CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number), ) } else { unMatchingBlocks.forEach { (expected, actual) -> @@ -63,7 +63,7 @@ class BlockEncodingValidator( "block encoding/decoding mismatch: block={} \nexpected={} \nactual={}", expected.header.number, expected, - actual + actual, ) } } @@ -82,7 +82,7 @@ class BlockEncodingValidator( } log.info( "compression validation blocks={} started", - CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number) + CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number), ) val besuBlocks = blocks.map { it.toBesu() } val originalBlockInterval = CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number) @@ -98,7 +98,7 @@ class BlockEncodingValidator( assertThat(decompressedBlocks.size).isEqualTo(besuBlocks.size) .withFailMessage( // this can happen if not all blocks fit into compressor limit - "originalBlocks=$originalBlockInterval decompressedBlocks.size=${decompressedBlocks.size} != " + "originalBlocks=$originalBlockInterval decompressedBlocks.size=${decompressedBlocks.size} != ", ) decompressedBlocks.zip(besuBlocks).forEach { (decompressed, original) -> runCatching { @@ -108,7 +108,7 @@ class BlockEncodingValidator( "Decompressed block={} does not match: error={}", original.header.number, it.message, - it + it, ) } } @@ -117,7 +117,7 @@ class BlockEncodingValidator( highestValidatedBlockNumber.set(highestValidatedBlockNumber.get().coerceAtLeast(blocks.last().number)) log.info( "compression validation blocks={} finished", - originalBlockInterval + originalBlockInterval, ) } } @@ -136,7 +136,7 @@ fun ConcurrentLinkedQueue.pull(elementsLimit: Int): List { fun assertBlock( decompressedBlock: org.hyperledger.besu.ethereum.core.Block, originalBlock: org.hyperledger.besu.ethereum.core.Block, - log: Logger = LogManager.getLogger("test.assert.Block") + log: Logger = LogManager.getLogger("test.assert.Block"), ) { // on decompression, the hash is placed as parentHash because besu recomputes the hash // but custom decoder overrides hash calculation to use parentHash @@ -152,7 +152,7 @@ fun assertBlock( originalTx, decompressedTx, - originalTx.encoded() + originalTx.encoded(), ) runCatching { assertThat(decompressedTx.type).isEqualTo(originalTx.type) @@ -173,7 +173,7 @@ fun assertBlock( fail( "Transaction does not match: block=${originalBlock.header.number} " + "txIndex=$index error=${th.message} origTxRlp=${originalTx.encoded()}", - th + th, ) } } diff --git a/transaction-decoder-tool/src/test/kotlin/linea/test/BlocksFetcher.kt b/transaction-decoder-tool/src/test/kotlin/linea/test/BlocksFetcher.kt index 97d6e28a..3c0aab05 100644 --- a/transaction-decoder-tool/src/test/kotlin/linea/test/BlocksFetcher.kt +++ b/transaction-decoder-tool/src/test/kotlin/linea/test/BlocksFetcher.kt @@ -18,11 +18,11 @@ class BlocksFetcher( val web3j: Web3j, val vertx: Vertx = Vertx.vertx(), val pollingChuckSize: UInt = 100U, - val log: Logger = LogManager.getLogger(BlocksFetcher::class.java) + val log: Logger = LogManager.getLogger(BlocksFetcher::class.java), ) { fun fetchBlocks( startBlockNumber: ULong, - endBlockNumber: ULong + endBlockNumber: ULong, ): SafeFuture> { return (startBlockNumber..endBlockNumber).toList() .map { blockNumber -> @@ -52,7 +52,7 @@ class BlocksFetcher( startBlockNumber: ULong, endBlockNumber: ULong? = null, chunkSize: UInt = pollingChuckSize, - consumer: (List) -> SafeFuture<*> + consumer: (List) -> SafeFuture<*>, ): SafeFuture<*> { val lastBlockFetched = AtomicLong(startBlockNumber.toLong() - 1) return AsyncRetryer.retry( @@ -63,7 +63,7 @@ class BlocksFetcher( }, stopRetriesOnErrorPredicate = { it is Exception - } + }, ) { val start = (lastBlockFetched.get() + 1).toULong() val end = (start + chunkSize - 1U).coerceAtMost(endBlockNumber ?: ULong.MAX_VALUE) diff --git a/transaction-decoder-tool/src/test/kotlin/linea/test/FetchAndValidationRunner.kt b/transaction-decoder-tool/src/test/kotlin/linea/test/FetchAndValidationRunner.kt index 66c7c9a7..c4caabd9 100644 --- a/transaction-decoder-tool/src/test/kotlin/linea/test/FetchAndValidationRunner.kt +++ b/transaction-decoder-tool/src/test/kotlin/linea/test/FetchAndValidationRunner.kt @@ -13,14 +13,14 @@ import java.util.concurrent.atomic.AtomicReference class FetchAndValidationRunner( val vertx: Vertx = Vertx.vertx(), val rpcUrl: String, - val log: Logger = LogManager.getLogger(FetchAndValidationRunner::class.java) + val log: Logger = LogManager.getLogger(FetchAndValidationRunner::class.java), ) { val web3j: Web3j = createWeb3jHttpClient( rpcUrl = rpcUrl, // executorService = vertx.nettyEventLoopGroup(), log = LogManager.getLogger("test.client.web3j"), requestResponseLogLevel = Level.DEBUG, - failuresLogLevel = Level.ERROR + failuresLogLevel = Level.ERROR, ) val validator = BlockEncodingValidator(vertx = vertx, log = log).also { it.start() } val blocksFetcher = BlocksFetcher(web3j, log = log) @@ -45,17 +45,17 @@ class FetchAndValidationRunner( startBlockNumber: ULong, endBlockNumber: ULong? = null, chuckSize: UInt = 100U, - rlpEncodingDecodingOnly: Boolean = false + rlpEncodingDecodingOnly: Boolean = false, ): SafeFuture<*> { targetEndBlockNumber.set(endBlockNumber) return blocksFetcher.consumeBlocks( startBlockNumber = startBlockNumber, endBlockNumber = endBlockNumber, - chunkSize = chuckSize + chunkSize = chuckSize, ) { blocks -> log.info( "got blocks: {}", - CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number) + CommonDomainFunctions.blockIntervalString(blocks.first().number, blocks.last().number), ) if (rlpEncodingDecodingOnly) { validator.validateRlpEncodingDecoding(blocks) diff --git a/transaction-decoder-tool/src/test/kotlin/linea/test/MainRunner.kt b/transaction-decoder-tool/src/test/kotlin/linea/test/MainRunner.kt index 3aec047f..6544aaae 100644 --- a/transaction-decoder-tool/src/test/kotlin/linea/test/MainRunner.kt +++ b/transaction-decoder-tool/src/test/kotlin/linea/test/MainRunner.kt @@ -27,14 +27,14 @@ fun main() { FetchAndValidationRunner( rpcUrl = rpcUrl, vertx = vertx, - log = LogManager.getLogger("test.validator") + log = LogManager.getLogger("test.validator"), ) configureLoggers( listOf( "linea.rlp" to Level.TRACE, "test.client.web3j" to Level.TRACE, - "test.validator" to Level.INFO - ) + "test.validator" to Level.INFO, + ), ) // Sepolia Blocks @@ -48,7 +48,7 @@ fun main() { endBlockNumber = startBlockNumber + 1U, // endBlockNumber = startBlockNumber + 0u, chuckSize = 1_000U, - rlpEncodingDecodingOnly = false + rlpEncodingDecodingOnly = false, ).get(2, TimeUnit.MINUTES) }.onFailure { error -> fetcherAndValidate.log.error("Error fetching and validating blocks", error) diff --git a/transaction-exclusion-api/app/src/integrationTest/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionAppTest.kt b/transaction-exclusion-api/app/src/integrationTest/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionAppTest.kt index 370a46b8..8a51297b 100644 --- a/transaction-exclusion-api/app/src/integrationTest/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionAppTest.kt +++ b/transaction-exclusion-api/app/src/integrationTest/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionAppTest.kt @@ -42,23 +42,23 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { host = "localhost", port = 5432, username = "postgres", - password = Masked("postgres") + password = Masked("postgres"), ), write = DbConnectionConfig( host = "localhost", port = 5432, username = "postgres", - password = Masked("postgres") + password = Masked("postgres"), ), cleanup = DbCleanupConfig( pollingInterval = Duration.parse("PT60S"), - storagePeriod = Duration.parse("P7D") + storagePeriod = Duration.parse("P7D"), ), persistenceRetry = PersistenceRetryConfig( backoffDelay = Duration.parse("PT5S"), - timeout = Duration.parse("PT20S") + timeout = Duration.parse("PT20S"), ), - schema = databaseName + schema = databaseName, ) private lateinit var requestSpecification: RequestSpecification @@ -71,11 +71,11 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { api = ApiConfig( port = 0, // port will be assigned under os observabilityPort = 0, // port will be assigned under os - numberOfVerticles = 1 + numberOfVerticles = 1, ), database = dbConfig, - dataQueryableWindowSinceRejectedTimestamp = Duration.parse("P7D") - ) + dataQueryableWindowSinceRejectedTimestamp = Duration.parse("P7D"), + ), ) app.start().get() @@ -128,7 +128,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "jsonrpc": "2.0", "id": 123, "result": {"status":"SAVED","txHash":"0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350ad7"} - }""" + }""", ) } @@ -168,7 +168,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "jsonrpc": "2.0", "id": 124, "result": {"status":"SAVED","txHash":"0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350ad7"} - }""" + }""", ) // Send the get request for the rejected transaction @@ -195,7 +195,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "timestamp": "$rejectionTimeStamp", "blockNumber": "0x2710" } - }""" + }""", ) } @@ -229,7 +229,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "jsonrpc": "2.0", "id": 124, "result": {"status":"SAVED","txHash":"0x583eb047887cc72f93ead08f389a2cd84440f3322bc4b191803d5adb0a167525"} - }""" + }""", ) // Send the get request for the rejected contract deployment tx @@ -255,7 +255,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "reasonMessage": "Transaction 0x583eb047887cc72f93ead08f389a2cd84440f3322bc4b191803d5adb0a167525 line count for module HUB=2119318 is above the limit 2097152", "timestamp": "$rejectionTimeStamp" } - }""" + }""", ) } @@ -294,7 +294,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "jsonrpc": "2.0", "id": 124, "result": {"status":"DUPLICATE_ALREADY_SAVED_BEFORE","txHash":"0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350ad7"} - }""" + }""", ) } @@ -319,7 +319,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "jsonrpc": "2.0", "id": 124, "result": null - }""" + }""", ) } @@ -347,7 +347,7 @@ class TransactionExclusionAppTest : CleanDbTestSuiteParallel() { "code": -32602, "message": "Missing [timestamp,overflows] from the given request params" } - }""" + }""", ) } } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionApp.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionApp.kt index 8e3472c3..d966b660 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionApp.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionApp.kt @@ -30,12 +30,12 @@ data class DbConnectionConfig( val host: String, val port: Int, val username: String, - val password: Masked + val password: Masked, ) data class DbCleanupConfig( val pollingInterval: Duration, - val storagePeriod: Duration + val storagePeriod: Duration, ) data class DatabaseConfig( @@ -46,19 +46,19 @@ data class DatabaseConfig( val schema: String = "linea_transaction_exclusion", val readPoolSize: Int = 10, val readPipeliningLimit: Int = 10, - val transactionalPoolSize: Int = 10 + val transactionalPoolSize: Int = 10, ) data class AppConfig( val api: ApiConfig, val database: DatabaseConfig, - val dataQueryableWindowSinceRejectedTimestamp: Duration + val dataQueryableWindowSinceRejectedTimestamp: Duration, ) data class PersistenceRetryConfig( val maxRetries: Int? = null, val backoffDelay: Duration = 1.seconds.toJavaDuration(), - val timeout: Duration? = 20.seconds.toJavaDuration() + val timeout: Duration? = 20.seconds.toJavaDuration(), ) class TransactionExclusionApp(config: AppConfig) { @@ -88,49 +88,49 @@ class TransactionExclusionApp(config: AppConfig) { schema = config.database.schema, transactionalPoolSize = config.database.transactionalPoolSize, readPipeliningLimit = config.database.readPipeliningLimit, - skipMigration = true + skipMigration = true, ) this.sqlWriteClient = initDb( connectionConfig = config.database.write, schema = config.database.schema, transactionalPoolSize = config.database.transactionalPoolSize, - readPipeliningLimit = config.database.readPipeliningLimit + readPipeliningLimit = config.database.readPipeliningLimit, ) this.rejectedTransactionsRepository = RetryingRejectedTransactionsPostgresDao( delegate = RejectedTransactionsPostgresDao( readConnection = this.sqlReadClient, - writeConnection = this.sqlWriteClient + writeConnection = this.sqlWriteClient, ), persistenceRetryer = PersistenceRetryer( vertx = vertx, config = PersistenceRetryer.Config( backoffDelay = config.database.persistenceRetry.backoffDelay.toKotlinDuration(), maxRetries = config.database.persistenceRetry.maxRetries, - timeout = config.database.persistenceRetry.timeout?.toKotlinDuration() - ) - ) + timeout = config.database.persistenceRetry.timeout?.toKotlinDuration(), + ), + ), ) this.transactionExclusionService = TransactionExclusionServiceV1Impl( config = TransactionExclusionServiceV1Impl.Config( - config.dataQueryableWindowSinceRejectedTimestamp.toKotlinDuration() + config.dataQueryableWindowSinceRejectedTimestamp.toKotlinDuration(), ), repository = this.rejectedTransactionsRepository, - metricsFacade = this.micrometerMetricsFacade + metricsFacade = this.micrometerMetricsFacade, ) this.rejectedTransactionCleanupService = RejectedTransactionCleanupService( config = RejectedTransactionCleanupService.Config( pollingInterval = config.database.cleanup.pollingInterval.toKotlinDuration(), - storagePeriod = config.database.cleanup.storagePeriod.toKotlinDuration() + storagePeriod = config.database.cleanup.storagePeriod.toKotlinDuration(), ), repository = this.rejectedTransactionsRepository, - vertx = this.vertx + vertx = this.vertx, ) this.api = Api( configs = config.api, vertx = vertx, metricsFacade = MicrometerMetricsFacade(meterRegistry), - transactionExclusionService = transactionExclusionService + transactionExclusionService = transactionExclusionService, ) } @@ -157,7 +157,7 @@ class TransactionExclusionApp(config: AppConfig) { schema: String, transactionalPoolSize: Int, readPipeliningLimit: Int, - skipMigration: Boolean = false + skipMigration: Boolean = false, ): SqlClient { val dbVersion = "3" if (!skipMigration) { @@ -167,7 +167,7 @@ class TransactionExclusionApp(config: AppConfig) { database = schema, target = dbVersion, username = connectionConfig.username, - password = connectionConfig.password.value + password = connectionConfig.password.value, ) } return Db.vertxSqlClient( @@ -178,7 +178,7 @@ class TransactionExclusionApp(config: AppConfig) { username = connectionConfig.username, password = connectionConfig.password.value, maxPoolSize = transactionalPoolSize, - pipeliningLimit = readPipeliningLimit + pipeliningLimit = readPipeliningLimit, ) } } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppCli.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppCli.kt index ce0f08b1..5d97d06d 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppCli.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppCli.kt @@ -22,7 +22,7 @@ import java.util.concurrent.Callable synopsisHeading = "%n", descriptionHeading = "%nDescription:%n%n", optionListHeading = "%nOptions:%n", - footerHeading = "%n" + footerHeading = "%n", ) class TransactionExclusionAppCli internal constructor(private val errorWriter: PrintWriter, private val startAction: StartAction) : diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppMain.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppMain.kt index 5668e163..814c69ac 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppMain.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/TransactionExclusionAppMain.kt @@ -28,7 +28,7 @@ class TransactionExclusionAppMain { // Messages in App.stop won't appear in the logs Configurator.shutdown(LogManager.getContext() as LoggerContext) } - } + }, ) app.start() } catch (t: Throwable) { diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/Api.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/Api.kt index 6d90e43f..1bdfb0f3 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/Api.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/Api.kt @@ -16,14 +16,14 @@ data class ApiConfig( val port: Int = 0, val observabilityPort: Int = 0, val numberOfVerticles: Int = 0, - val path: String = "/" + val path: String = "/", ) class Api( private val configs: ApiConfig, private val vertx: Vertx, private val metricsFacade: MetricsFacade, - private val transactionExclusionService: TransactionExclusionServiceV1 + private val transactionExclusionService: TransactionExclusionServiceV1, ) { private var jsonRpcServerId: String? = null private var observabilityServerId: String? = null @@ -40,12 +40,12 @@ class Api( mapOf( ApiMethod.LINEA_SAVE_REJECTED_TRANSACTION_V1.method to SaveRejectedTransactionRequestHandlerV1( - transactionExclusionService = transactionExclusionService + transactionExclusionService = transactionExclusionService, ), ApiMethod.LINEA_GET_TRANSACTION_EXCLUSION_STATUS_V1.method to GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionService = transactionExclusionService - ) + transactionExclusionService = transactionExclusionService, + ), ) val messageHandler: JsonRpcMessageHandler = @@ -62,8 +62,8 @@ class Api( ObservabilityServer( ObservabilityServer.Config( "transaction-exclusion-api", - configs.observabilityPort - ) + configs.observabilityPort, + ), ) var httpServer: HttpJsonRpcServer? = null return vertx @@ -74,7 +74,7 @@ class Api( httpServer = it } }, - DeploymentOptions().setInstances(numberOfVerticles) + DeploymentOptions().setInstances(numberOfVerticles), ) .compose { verticleId: String -> jsonRpcServerId = verticleId @@ -88,7 +88,7 @@ class Api( fun stop(): Future<*> { return Future.all( this.jsonRpcServerId?.let { vertx.undeploy(it) } ?: Future.succeededFuture(null), - this.observabilityServerId?.let { vertx.undeploy(it) } ?: Future.succeededFuture(null) + this.observabilityServerId?.let { vertx.undeploy(it) } ?: Future.succeededFuture(null), ) } } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ApiMethod.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ApiMethod.kt index 78e88e47..98fdfb81 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ApiMethod.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ApiMethod.kt @@ -2,5 +2,5 @@ package net.consensys.linea.transactionexclusion.app.api enum class ApiMethod(val method: String) { LINEA_SAVE_REJECTED_TRANSACTION_V1("linea_saveRejectedTransactionV1"), - LINEA_GET_TRANSACTION_EXCLUSION_STATUS_V1("linea_getTransactionExclusionStatusV1") + LINEA_GET_TRANSACTION_EXCLUSION_STATUS_V1("linea_getTransactionExclusionStatusV1"), } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParser.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParser.kt index 2624629c..5718f846 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParser.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParser.kt @@ -36,13 +36,13 @@ object ArgumentParser { try { return TransactionDecoder.decodeOpaqueBytes( Bytes.wrap(rlp), - EncodingContext.BLOCK_BODY + EncodingContext.BLOCK_BODY, ).run { TransactionInfo( hash = this.hash.toArray(), to = if (this.to.isPresent) this.to.get().toArray() else null, from = this.sender.toArray(), - nonce = this.nonce.toULong() + nonce = this.nonce.toULong(), ) } } catch (ex: Exception) { @@ -61,7 +61,7 @@ object ArgumentParser { fun getReasonMessage(reasonMessage: String): String { if (reasonMessage.length > MAX_REASON_MESSAGE_STR_LEN) { throw IllegalArgumentException( - "Reason message should not be more than $MAX_REASON_MESSAGE_STR_LEN characters: $reasonMessage" + "Reason message should not be more than $MAX_REASON_MESSAGE_STR_LEN characters: $reasonMessage", ) } return reasonMessage diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersV1.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersV1.kt index 899b4157..7caf69c6 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersV1.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersV1.kt @@ -28,8 +28,8 @@ private fun validateIsMapOrListParams(request: JsonRpcRequest): Result) { @@ -68,7 +68,7 @@ class SaveRejectedTransactionRequestHandlerV1( if (this.isNotEmpty()) { throw IllegalArgumentException( "Missing ${this.joinToString(",", "[", "]") { it.paramName }} " + - "from the given request params" + "from the given request params", ) } } @@ -83,11 +83,11 @@ class SaveRejectedTransactionRequestHandlerV1( private fun parseListParamsToRejectedTransaction(requestListParams: List): RejectedTransaction { if (requestListParams.size != 1) { throw IllegalArgumentException( - "The given request params list should have one argument" + "The given request params list should have one argument", ) } else if (requestListParams.first() !is Map<*, *>) { throw IllegalArgumentException( - "The argument in the request params list should be an object" + "The argument in the request params list should be an object", ) } return parseMapParamsToRejectedTransaction(requestListParams[0] as Map<*, *>) @@ -96,7 +96,7 @@ class SaveRejectedTransactionRequestHandlerV1( override fun invoke( user: User?, request: JsonRpcRequest, - requestJson: JsonObject + requestJson: JsonObject, ): Future> { val rejectedTransaction = try { val parsingResult = validateIsMapOrListParams(request).flatMap { validatedRequest -> @@ -105,7 +105,7 @@ class SaveRejectedTransactionRequestHandlerV1( is JsonRpcRequestMapParams -> parseMapParamsToRejectedTransaction(validatedRequest.params) is JsonRpcRequestListParams -> parseListParamsToRejectedTransaction(validatedRequest.params) else -> throw IllegalStateException( - "JsonRpcRequest should be as JsonRpcRequestMapParams or JsonRpcRequestListParams" + "JsonRpcRequest should be as JsonRpcRequestMapParams or JsonRpcRequestListParams", ) } Ok(parsedRejectedTransaction) @@ -120,9 +120,9 @@ class SaveRejectedTransactionRequestHandlerV1( Err( JsonRpcErrorResponse.invalidParams( request.id, - e.message - ) - ) + e.message, + ), + ), ) } @@ -143,12 +143,12 @@ class SaveRejectedTransactionRequestHandlerV1( } class GetTransactionExclusionStatusRequestHandlerV1( - private val transactionExclusionService: TransactionExclusionServiceV1 + private val transactionExclusionService: TransactionExclusionServiceV1, ) : JsonRpcRequestHandler { private fun parseListParamsToTxHash(requestListParams: List): ByteArray { if (requestListParams.size != 1) { throw IllegalArgumentException( - "The given request params list should have one argument" + "The given request params list should have one argument", ) } return ArgumentParser.getTxHashInRawBytes(requestListParams[0].toString()) @@ -157,7 +157,7 @@ class GetTransactionExclusionStatusRequestHandlerV1( override fun invoke( user: User?, request: JsonRpcRequest, - requestJson: JsonObject + requestJson: JsonObject, ): Future> { val txHash = try { val parsingResult = validateIsListParams(request).flatMap { validatedRequest -> @@ -178,9 +178,9 @@ class GetTransactionExclusionStatusRequestHandlerV1( Err( JsonRpcErrorResponse.invalidParams( request.id, - e.message - ) - ) + e.message, + ), + ), ) } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/TransactionExclusionErrorCodes.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/TransactionExclusionErrorCodes.kt index c9baffaa..759073d5 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/TransactionExclusionErrorCodes.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/app/api/TransactionExclusionErrorCodes.kt @@ -6,7 +6,8 @@ import net.consensys.linea.transactionexclusion.TransactionExclusionError enum class TransactionExclusionErrorCodes(val code: Int, val message: String) { // App/System/Server' error codes - SERVER_ERROR(-32000, "Server error"); + SERVER_ERROR(-32000, "Server error"), + ; fun toErrorObject(data: Any? = null): JsonRpcError { return JsonRpcError(this.code, this.message, data) diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/dto/RejectedTransactionJsonDto.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/dto/RejectedTransactionJsonDto.kt index ecdbf9a3..6e134be1 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/dto/RejectedTransactionJsonDto.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/dto/RejectedTransactionJsonDto.kt @@ -8,7 +8,7 @@ import net.consensys.linea.transactionexclusion.app.api.ArgumentParser data class ModuleOverflowJsonDto( val count: Long, val limit: Long, - val module: String + val module: String, ) { // Jackson ObjectMapper requires a default constructor constructor() : this(0L, 0L, "") @@ -17,7 +17,7 @@ data class ModuleOverflowJsonDto( fun parseListFrom(target: Any): List { return ObjectMapper().readValue( ObjectMapper().writeValueAsString(target), - Array::class.java + Array::class.java, ).toList() } } @@ -26,7 +26,7 @@ data class ModuleOverflowJsonDto( return ModuleOverflow( count = count, limit = limit, - module = module + module = module, ) } } @@ -37,7 +37,7 @@ data class RejectedTransactionJsonDto( val blockNumber: String?, val transactionRLP: String, val reasonMessage: String, - val overflows: Any + val overflows: Any, ) { // Jackson ObjectMapper requires a default constructor constructor() : this("", "", null, "", "", Any()) @@ -46,7 +46,7 @@ data class RejectedTransactionJsonDto( fun parseFrom(target: Any): RejectedTransactionJsonDto { return ObjectMapper().readValue( ObjectMapper().writeValueAsString(target), - RejectedTransactionJsonDto::class.java + RejectedTransactionJsonDto::class.java, ) } } @@ -85,7 +85,7 @@ data class RejectedTransactionJsonDto( transactionRLP = parsedTransactionRLP, reasonMessage = ArgumentParser.getReasonMessage(reasonMessage), overflows = ArgumentParser.getOverflows(overflows), - transactionInfo = ArgumentParser.getTransactionInfoFromRLP(parsedTransactionRLP) + transactionInfo = ArgumentParser.getTransactionInfoFromRLP(parsedTransactionRLP), ) } } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupService.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupService.kt index be86184f..674ad790 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupService.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupService.kt @@ -14,20 +14,20 @@ class RejectedTransactionCleanupService( private val config: Config, private val repository: RejectedTransactionsDao, private val clock: Clock = Clock.System, - private val log: Logger = LogManager.getLogger(RejectedTransactionCleanupService::class.java) + private val log: Logger = LogManager.getLogger(RejectedTransactionCleanupService::class.java), ) : PeriodicPollingService( vertx = vertx, pollingIntervalMs = config.pollingInterval.inWholeMilliseconds, - log = log + log = log, ) { data class Config( val pollingInterval: Duration, - val storagePeriod: Duration + val storagePeriod: Duration, ) override fun action(): SafeFuture<*> { return this.repository.deleteRejectedTransactions( - clock.now().minus(config.storagePeriod) + clock.now().minus(config.storagePeriod), ).thenPeek { deletedRows -> if (deletedRows > 0) { log.debug("deletedRows=$deletedRows") @@ -39,7 +39,7 @@ class RejectedTransactionCleanupService( log.error( "Error with rejected transaction cleanup service: errorMessage={}", error.message, - error + error, ) } } diff --git a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceV1Impl.kt b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceV1Impl.kt index bcbb6068..cc336e40 100644 --- a/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceV1Impl.kt +++ b/transaction-exclusion-api/app/src/main/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceV1Impl.kt @@ -20,33 +20,33 @@ class TransactionExclusionServiceV1Impl( private val config: Config, private val repository: RejectedTransactionsDao, metricsFacade: MetricsFacade, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : TransactionExclusionServiceV1 { data class Config( - val rejectedTimestampWithinDuration: Duration + val rejectedTimestampWithinDuration: Duration, ) private val txRejectionCounter = metricsFacade.createCounter( category = LineaMetricsCategory.TX_EXCLUSION_API, name = "transactions.rejected", - description = "Counter of rejected transactions reported to Transaction Exclusion API service" + description = "Counter of rejected transactions reported to Transaction Exclusion API service", ) override fun saveRejectedTransaction( - rejectedTransaction: RejectedTransaction + rejectedTransaction: RejectedTransaction, ): SafeFuture< - Result + Result, > { return this.repository.saveNewRejectedTransaction(rejectedTransaction) .handleComposed { _, error -> if (error != null) { if (error is DuplicatedRecordException) { SafeFuture.completedFuture( - Ok(SaveRejectedTransactionStatus.DUPLICATE_ALREADY_SAVED_BEFORE) + Ok(SaveRejectedTransactionStatus.DUPLICATE_ALREADY_SAVED_BEFORE), ) } else { SafeFuture.completedFuture( - Err(TransactionExclusionError(ErrorType.SERVER_ERROR, error.message ?: "")) + Err(TransactionExclusionError(ErrorType.SERVER_ERROR, error.message ?: "")), ) } } else { @@ -57,16 +57,16 @@ class TransactionExclusionServiceV1Impl( } override fun getTransactionExclusionStatus( - txHash: ByteArray + txHash: ByteArray, ): SafeFuture> { return this.repository.findRejectedTransactionByTxHash( txHash = txHash, - notRejectedBefore = clock.now().minus(config.rejectedTimestampWithinDuration) + notRejectedBefore = clock.now().minus(config.rejectedTimestampWithinDuration), ) .handleComposed { result, error -> if (error != null) { SafeFuture.completedFuture( - Err(TransactionExclusionError(ErrorType.SERVER_ERROR, error.message ?: "")) + Err(TransactionExclusionError(ErrorType.SERVER_ERROR, error.message ?: "")), ) } else { SafeFuture.completedFuture(Ok(result)) diff --git a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParserTest.kt b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParserTest.kt index df1635de..33237d4e 100644 --- a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParserTest.kt +++ b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/ArgumentParserTest.kt @@ -19,7 +19,7 @@ class ArgumentParserTest { val transactionRLPInHexStr = defaultRejectedTransaction.transactionRLP.encodeHex() Assertions.assertTrue( ArgumentParser.getTransactionRLPInRawBytes(transactionRLPInHexStr) - .contentEquals(transactionRLPInHexStr.decodeHex()) + .contentEquals(transactionRLPInHexStr.decodeHex()), ) } @@ -29,11 +29,11 @@ class ArgumentParserTest { assertThrows { ArgumentParser.getTransactionRLPInRawBytes( "0x02f8388204d2648203e88203e88203e8941195cf65f83b3a5768f3c4" + - "96d3a05ad6412c64b38203e88c666d93e9cc5f73748162cea9c0017b820" + "96d3a05ad6412c64b38203e88c666d93e9cc5f73748162cea9c0017b820", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("RLP-encoded transaction cannot be parsed") + error.message!!.contains("RLP-encoded transaction cannot be parsed"), ) } @@ -41,11 +41,11 @@ class ArgumentParserTest { assertThrows { ArgumentParser.getTransactionRLPInRawBytes( "yyf8388204d2648203e88203e88203e8941195cf65f83b3a5768f3c4" + - "96d3a05ad6412c64b38203e88c666d93e9cc5f73748162cea9c0017b8201xx" + "96d3a05ad6412c64b38203e88c666d93e9cc5f73748162cea9c0017b8201xx", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("RLP-encoded transaction cannot be parsed") + error.message!!.contains("RLP-encoded transaction cannot be parsed"), ) } } @@ -55,7 +55,7 @@ class ArgumentParserTest { val txHashInHexStr = "0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350ad7" Assertions.assertTrue( ArgumentParser.getTxHashInRawBytes(txHashInHexStr) - .contentEquals(txHashInHexStr.decodeHex()) + .contentEquals(txHashInHexStr.decodeHex()), ) } @@ -64,11 +64,11 @@ class ArgumentParserTest { // hex string of less than 64 hex characters assertThrows { ArgumentParser.getTxHashInRawBytes( - "0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350a" + "0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350a", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Hex string of transaction hash cannot be parsed") + error.message!!.contains("Hex string of transaction hash cannot be parsed"), ) } } @@ -78,7 +78,7 @@ class ArgumentParserTest { val transactionRLP = defaultRejectedTransaction.transactionRLP Assertions.assertEquals( ArgumentParser.getTransactionInfoFromRLP(transactionRLP), - defaultRejectedTransaction.transactionInfo + defaultRejectedTransaction.transactionInfo, ) } @@ -87,7 +87,7 @@ class ArgumentParserTest { val transactionRLP = rejectedContractDeploymentTransaction.transactionRLP Assertions.assertEquals( ArgumentParser.getTransactionInfoFromRLP(transactionRLP), - rejectedContractDeploymentTransaction.transactionInfo + rejectedContractDeploymentTransaction.transactionInfo, ) } @@ -99,11 +99,11 @@ class ArgumentParserTest { ( "0xaaf8388204d2648203e88203e88203e8941195cf65f83b3a5768f3c4" + "96d3a05ad6412c64b38203e88c666d93e9cc5f73748162cea9c0017b8201c8" - ).decodeHex() + ).decodeHex(), ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("RLP-encoded transaction cannot be parsed") + error.message!!.contains("RLP-encoded transaction cannot be parsed"), ) } } @@ -114,13 +114,13 @@ class ArgumentParserTest { ModuleOverflow( module = "ADD", count = 402, - limit = 70 + limit = 70, ), ModuleOverflow( module = "MUL", count = 587, - limit = 400 - ) + limit = 400, + ), ) // valid module overflow as json request params @@ -129,18 +129,18 @@ class ArgumentParserTest { mapOf( "module" to "ADD", "count" to "402", - "limit" to "70" + "limit" to "70", ), mapOf( "module" to "MUL", "count" to "587", - "limit" to "400" - ) + "limit" to "400", + ), ) Assertions.assertEquals( ArgumentParser.getOverflows(moduleOverflowJsonRequestParams), - expectedModuleOverflowList + expectedModuleOverflowList, ) } @@ -153,18 +153,18 @@ class ArgumentParserTest { mapOf( "module" to "ADD", "count" to "402", - "xxx" to "70" + "xxx" to "70", ), mapOf( "module" to "MUL", "count" to "587", - "limit" to "400" - ) - ) + "limit" to "400", + ), + ), ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Overflows cannot be parsed") + error.message!!.contains("Overflows cannot be parsed"), ) } @@ -175,18 +175,18 @@ class ArgumentParserTest { mapOf( "module" to null, "count" to "402", - "limit" to "70" + "limit" to "70", ), mapOf( "module" to "MUL", "count" to "587", - "limit" to "400" - ) - ) + "limit" to "400", + ), + ), ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Overflows cannot be parsed") + error.message!!.contains("Overflows cannot be parsed"), ) } @@ -195,7 +195,7 @@ class ArgumentParserTest { ArgumentParser.getOverflows(JsonObject()) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Overflows cannot be parsed") + error.message!!.contains("Overflows cannot be parsed"), ) } } @@ -205,13 +205,13 @@ class ArgumentParserTest { val reasonMessage = "Transaction line count for module ADD=402 is above the limit 70" Assertions.assertEquals( ArgumentParser.getReasonMessage(reasonMessage), - reasonMessage + reasonMessage, ) val reasonMessageWithMaxLen = Random.Default.nextBytes(128).encodeHex(prefix = false) Assertions.assertEquals( ArgumentParser.getReasonMessage(reasonMessageWithMaxLen), - reasonMessageWithMaxLen + reasonMessageWithMaxLen, ) } @@ -220,11 +220,11 @@ class ArgumentParserTest { // reason message string with more than 1024 characters assertThrows { ArgumentParser.getReasonMessage( - Random.Default.nextBytes(512).encodeHex(prefix = false) + "0" + Random.Default.nextBytes(512).encodeHex(prefix = false) + "0", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Reason message should not be more than 1024 characters") + error.message!!.contains("Reason message should not be more than 1024 characters"), ) } } @@ -235,11 +235,11 @@ class ArgumentParserTest { val blockNumberStr = "12345" Assertions.assertEquals( ArgumentParser.getBlockNumber(blockNumberStr)!!, - blockNumberStr.toULong() + blockNumberStr.toULong(), ) Assertions.assertNull( - ArgumentParser.getBlockNumber(null) + ArgumentParser.getBlockNumber(null), ) } @@ -248,22 +248,22 @@ class ArgumentParserTest { // block number string with hex string assertThrows { ArgumentParser.getBlockNumber( - "0x12345" + "0x12345", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Block number cannot be parsed to an unsigned number") + error.message!!.contains("Block number cannot be parsed to an unsigned number"), ) } // block number string with random characters assertThrows { ArgumentParser.getBlockNumber( - "xxyyzz" + "xxyyzz", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Block number cannot be parsed to an unsigned number") + error.message!!.contains("Block number cannot be parsed to an unsigned number"), ) } @@ -272,7 +272,7 @@ class ArgumentParserTest { ArgumentParser.getBlockNumber("") }.also { error -> Assertions.assertTrue( - error.message!!.contains("Block number cannot be parsed to an unsigned number") + error.message!!.contains("Block number cannot be parsed to an unsigned number"), ) } } @@ -283,7 +283,7 @@ class ArgumentParserTest { val timestampStr = "2024-09-05T09:22:52Z" Assertions.assertEquals( ArgumentParser.getTimestampFromISO8601(timestampStr), - Instant.parse(timestampStr) + Instant.parse(timestampStr), ) } @@ -292,22 +292,22 @@ class ArgumentParserTest { // timestamp string not in ISO-8601 assertThrows { ArgumentParser.getTimestampFromISO8601( - "2024-09-05_09:22:52" + "2024-09-05_09:22:52", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Timestamp is not in ISO-8601") + error.message!!.contains("Timestamp is not in ISO-8601"), ) } // timestamp string in epoch time millisecond assertThrows { ArgumentParser.getTimestampFromISO8601( - "1725543970103" + "1725543970103", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Timestamp is not in ISO-8601") + error.message!!.contains("Timestamp is not in ISO-8601"), ) } @@ -316,7 +316,7 @@ class ArgumentParserTest { ArgumentParser.getTimestampFromISO8601("") }.also { error -> Assertions.assertTrue( - error.message!!.contains("Timestamp is not in ISO-8601") + error.message!!.contains("Timestamp is not in ISO-8601"), ) } } @@ -326,7 +326,7 @@ class ArgumentParserTest { val txRejectionStageStr = "SEQUENCER" Assertions.assertEquals( ArgumentParser.getTxRejectionStage(txRejectionStageStr), - RejectedTransaction.Stage.SEQUENCER + RejectedTransaction.Stage.SEQUENCER, ) } @@ -335,22 +335,22 @@ class ArgumentParserTest { // rejection stage string in lower case assertThrows { ArgumentParser.getTxRejectionStage( - "sequencer" + "sequencer", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Unsupported transaction rejection stage") + error.message!!.contains("Unsupported transaction rejection stage"), ) } // rejection stage string in random characters assertThrows { ArgumentParser.getTxRejectionStage( - "helloworld" + "helloworld", ) }.also { error -> Assertions.assertTrue( - error.message!!.contains("Unsupported transaction rejection stage") + error.message!!.contains("Unsupported transaction rejection stage"), ) } } diff --git a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersTest.kt b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersTest.kt index e081e775..e78b8989 100644 --- a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersTest.kt +++ b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/app/api/RequestHandlersTest.kt @@ -33,27 +33,27 @@ class RequestHandlersTest { "timestamp" to "2024-09-05T09:22:52Z", "transactionRLP" to defaultRejectedTransaction.transactionRLP.encodeHex(), "reasonMessage" to defaultRejectedTransaction.reasonMessage, - "overflows" to defaultRejectedTransaction.overflows + "overflows" to defaultRejectedTransaction.overflows, ) private val mapRequest = JsonRpcRequestMapParams( "2.0", "1", "linea_saveRejectedTransactionV1", - mapParams + mapParams, ) private val listRequest = JsonRpcRequestListParams( "2.0", "1", "linea_saveRejectedTransactionV1", - listOf(mapParams) + listOf(mapParams), ) @BeforeEach fun beforeEach() { transactionExclusionServiceMock = mock( - defaultAnswer = Mockito.RETURNS_DEEP_STUBS + defaultAnswer = Mockito.RETURNS_DEEP_STUBS, ) } @@ -62,13 +62,13 @@ class RequestHandlersTest { val request = JsonRpcRequestMapParams("", "", "", emptyMap()) val saveRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val result = saveRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals( @@ -76,10 +76,10 @@ class RequestHandlersTest { JsonRpcErrorResponse.invalidParams( request.id, "Missing [txRejectionStage,timestamp,reasonMessage,transactionRLP,overflows] " + - "from the given request params" - ) + "from the given request params", + ), ), - result + result, ) } @@ -88,23 +88,23 @@ class RequestHandlersTest { val request = JsonRpcRequestListParams("", "", "", emptyList()) val saveRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val result = saveRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals( Err( JsonRpcErrorResponse.invalidParams( request.id, - "The given request params list should have one argument" - ) + "The given request params list should have one argument", + ), ), - result + result, ) } @@ -113,23 +113,23 @@ class RequestHandlersTest { val request = JsonRpcRequestListParams("", "", "", listOf("invalid_argument")) val saveRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val result = saveRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals( Err( JsonRpcErrorResponse.invalidParams( request.id, - "The argument in the request params list should be an object" - ) + "The argument in the request params list should be an object", + ), ), - result + result, ) } @@ -138,12 +138,12 @@ class RequestHandlersTest { whenever(transactionExclusionServiceMock.saveRejectedTransaction(any())) .thenReturn( SafeFuture.completedFuture( - Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED) - ) + Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED), + ), ) val saveRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonObject() @@ -156,7 +156,7 @@ class RequestHandlersTest { val result = saveRequestHandlerV1.invoke( user = null, request = mapRequest, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -167,12 +167,12 @@ class RequestHandlersTest { whenever(transactionExclusionServiceMock.saveRejectedTransaction(any())) .thenReturn( SafeFuture.completedFuture( - Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED) - ) + Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED), + ), ) val saveRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonObject() @@ -185,7 +185,7 @@ class RequestHandlersTest { val result = saveRequestHandlerV1.invoke( user = null, request = listRequest, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -196,12 +196,12 @@ class RequestHandlersTest { whenever(transactionExclusionServiceMock.saveRejectedTransaction(any())) .thenReturn( SafeFuture.completedFuture( - Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED) - ) + Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED), + ), ) val saveTxRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonObject() @@ -214,7 +214,7 @@ class RequestHandlersTest { val result = saveTxRequestHandlerV1.invoke( user = null, request = mapRequest, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -225,12 +225,12 @@ class RequestHandlersTest { whenever(transactionExclusionServiceMock.saveRejectedTransaction(any())) .thenReturn( SafeFuture.completedFuture( - Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.DUPLICATE_ALREADY_SAVED_BEFORE) - ) + Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.DUPLICATE_ALREADY_SAVED_BEFORE), + ), ) val saveTxRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonObject() @@ -243,7 +243,7 @@ class RequestHandlersTest { val result = saveTxRequestHandlerV1.invoke( user = null, request = mapRequest, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -257,14 +257,14 @@ class RequestHandlersTest { Err( TransactionExclusionError( ErrorType.SERVER_ERROR, - "error for unit test" - ) - ) - ) + "error for unit test", + ), + ), + ), ) val saveTxRequestHandlerV1 = SaveRejectedTransactionRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonRpcErrorResponse( @@ -272,15 +272,15 @@ class RequestHandlersTest { jsonRpcError( TransactionExclusionError( ErrorType.SERVER_ERROR, - "error for unit test" - ) - ) + "error for unit test", + ), + ), ) val result = saveTxRequestHandlerV1.invoke( user = null, request = mapRequest, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.getError()) @@ -291,23 +291,23 @@ class RequestHandlersTest { val request = JsonRpcRequestListParams("", "", "", emptyList()) val getRequestHandlerV1 = GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val result = getRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals( Err( JsonRpcErrorResponse.invalidParams( request.id, - "The given request params list should have one argument" - ) + "The given request params list should have one argument", + ), ), - result + result, ) } @@ -316,23 +316,23 @@ class RequestHandlersTest { val request = JsonRpcRequestListParams("", "", "", listOf("0x123")) val getRequestHandlerV1 = GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val result = getRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals( Err( JsonRpcErrorResponse.invalidParams( request.id, - "Hex string of transaction hash cannot be parsed: Must have an even length" - ) + "Hex string of transaction hash cannot be parsed: Must have an even length", + ), ), - result + result, ) } @@ -341,8 +341,8 @@ class RequestHandlersTest { whenever(transactionExclusionServiceMock.getTransactionExclusionStatus(any())) .thenReturn( SafeFuture.completedFuture( - Ok(defaultRejectedTransaction) - ) + Ok(defaultRejectedTransaction), + ), ) val request = JsonRpcRequestListParams( @@ -350,12 +350,12 @@ class RequestHandlersTest { "1", "linea_getTransactionExclusionStatusV1", listOf( - defaultRejectedTransaction.transactionInfo.hash.encodeHex() - ) + defaultRejectedTransaction.transactionInfo.hash.encodeHex(), + ), ) val getTxStatusRequestHandlerV1 = GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonObject() @@ -373,7 +373,7 @@ class RequestHandlersTest { val result = getTxStatusRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -389,12 +389,12 @@ class RequestHandlersTest { "1", "linea_getTransactionExclusionStatusV1", listOf( - defaultRejectedTransaction.transactionInfo.hash.encodeHex() - ) + defaultRejectedTransaction.transactionInfo.hash.encodeHex(), + ), ) val getTxStatusRequestHandlerV1 = GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonRpcSuccessResponse(request.id, null) @@ -402,7 +402,7 @@ class RequestHandlersTest { val result = getTxStatusRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.get()) @@ -416,10 +416,10 @@ class RequestHandlersTest { Err( TransactionExclusionError( ErrorType.SERVER_ERROR, - "error for unit test" - ) - ) - ) + "error for unit test", + ), + ), + ), ) val request = JsonRpcRequestListParams( @@ -427,12 +427,12 @@ class RequestHandlersTest { "1", "linea_getTransactionExclusionStatusV1", listOf( - defaultRejectedTransaction.transactionInfo.hash.encodeHex() - ) + defaultRejectedTransaction.transactionInfo.hash.encodeHex(), + ), ) val getTxStatusRequestHandlerV1 = GetTransactionExclusionStatusRequestHandlerV1( - transactionExclusionServiceMock + transactionExclusionServiceMock, ) val expectedResult = JsonRpcErrorResponse( @@ -440,15 +440,15 @@ class RequestHandlersTest { jsonRpcError( TransactionExclusionError( ErrorType.SERVER_ERROR, - "error for unit test" - ) - ) + "error for unit test", + ), + ), ) val result = getTxStatusRequestHandlerV1.invoke( user = null, request = request, - requestJson = JsonObject() + requestJson = JsonObject(), ).get() Assertions.assertEquals(expectedResult, result.getError()) diff --git a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupServiceTest.kt b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupServiceTest.kt index dff10b83..a5eec309 100644 --- a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupServiceTest.kt +++ b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/RejectedTransactionCleanupServiceTest.kt @@ -34,7 +34,7 @@ class RejectedTransactionCleanupServiceTest { fun beforeEach() { fakeClock.setTimeTo(Clock.System.now()) rejectedTransactionsRepositoryMock = mock( - defaultAnswer = Mockito.RETURNS_DEEP_STUBS + defaultAnswer = Mockito.RETURNS_DEEP_STUBS, ).also { whenever(it.deleteRejectedTransactions(any())) .thenReturn(SafeFuture.completedFuture(1)) @@ -43,18 +43,19 @@ class RejectedTransactionCleanupServiceTest { RejectedTransactionCleanupService( config = RejectedTransactionCleanupService.Config( pollingInterval = 100.milliseconds, - storagePeriod = 24.hours + storagePeriod = 24.hours, ), clock = fakeClock, vertx = Vertx.vertx(), - repository = rejectedTransactionsRepositoryMock + repository = rejectedTransactionsRepositoryMock, ) } @Test @Timeout(2, timeUnit = TimeUnit.SECONDS) - fun `when rejectedTransactionCleanupService starts, deleteRejectedTransaction should be called` - (testContext: VertxTestContext) { + fun `when rejectedTransactionCleanupService starts, deleteRejectedTransaction should be called`( + testContext: VertxTestContext, + ) { rejectedTransactionCleanupService.start() .thenApply { Awaitility.await() diff --git a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceTest.kt b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceTest.kt index f58f792f..e1b838fa 100644 --- a/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceTest.kt +++ b/transaction-exclusion-api/app/src/test/kotlin/net/consensys/linea/transactionexclusion/service/TransactionExclusionServiceTest.kt @@ -22,14 +22,14 @@ import kotlin.time.Duration.Companion.hours class TransactionExclusionServiceTest { private val metricsFacadeMock = mock(defaultAnswer = Mockito.RETURNS_DEEP_STUBS) private val config = TransactionExclusionServiceV1Impl.Config( - rejectedTimestampWithinDuration = 24.hours + rejectedTimestampWithinDuration = 24.hours, ) private lateinit var rejectedTransactionsRepositoryMock: RejectedTransactionsDao @BeforeEach fun beforeEach() { rejectedTransactionsRepositoryMock = mock( - defaultAnswer = Mockito.RETURNS_DEEP_STUBS + defaultAnswer = Mockito.RETURNS_DEEP_STUBS, ) } @@ -43,12 +43,12 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.SAVED), - transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get() + transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get(), ) } @@ -60,12 +60,12 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Ok(TransactionExclusionServiceV1.SaveRejectedTransactionStatus.DUPLICATE_ALREADY_SAVED_BEFORE), - transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get() + transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get(), ) } @@ -79,12 +79,12 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Err(TransactionExclusionError(ErrorType.SERVER_ERROR, "")), - transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get() + transactionExclusionService.saveRejectedTransaction(defaultRejectedTransaction).get(), ) } @@ -96,14 +96,14 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Ok(defaultRejectedTransaction), transactionExclusionService.getTransactionExclusionStatus( - defaultRejectedTransaction.transactionInfo.hash - ).get() + defaultRejectedTransaction.transactionInfo.hash, + ).get(), ) } @@ -115,14 +115,14 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Ok(null), transactionExclusionService.getTransactionExclusionStatus( - defaultRejectedTransaction.transactionInfo.hash - ).get() + defaultRejectedTransaction.transactionInfo.hash, + ).get(), ) } @@ -134,19 +134,19 @@ class TransactionExclusionServiceTest { val transactionExclusionService = TransactionExclusionServiceV1Impl( config = config, repository = rejectedTransactionsRepositoryMock, - metricsFacade = metricsFacadeMock + metricsFacade = metricsFacadeMock, ) Assertions.assertEquals( Err( TransactionExclusionError( ErrorType.SERVER_ERROR, - "" - ) + "", + ), ), transactionExclusionService.getTransactionExclusionStatus( - defaultRejectedTransaction.transactionInfo.hash - ).get() + defaultRejectedTransaction.transactionInfo.hash, + ).get(), ) } } diff --git a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/ErrorType.kt b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/ErrorType.kt index 1beea363..4e9f8a69 100644 --- a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/ErrorType.kt +++ b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/ErrorType.kt @@ -2,7 +2,7 @@ package net.consensys.linea.transactionexclusion /** For simplicity, placing all error codes into single enum */ enum class ErrorType { - SERVER_ERROR + SERVER_ERROR, } data class TransactionExclusionError(val errorType: ErrorType, val errorDetail: String) diff --git a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/RejectedTransaction.kt b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/RejectedTransaction.kt index 85db221e..8eec40dc 100644 --- a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/RejectedTransaction.kt +++ b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/RejectedTransaction.kt @@ -6,7 +6,7 @@ import linea.kotlin.encodeHex data class ModuleOverflow( val count: Long, val limit: Long, - val module: String + val module: String, ) { // Jackson ObjectMapper requires a default constructor constructor() : this(0L, 0L, "") @@ -20,7 +20,7 @@ data class TransactionInfo( val hash: ByteArray, val from: ByteArray, val to: ByteArray?, - val nonce: ULong + val nonce: ULong, ) { override fun equals(other: Any?): Boolean { if (this === other) return true @@ -55,12 +55,12 @@ data class RejectedTransaction( val transactionRLP: ByteArray, val reasonMessage: String, val overflows: List, - val transactionInfo: TransactionInfo + val transactionInfo: TransactionInfo, ) { enum class Stage { SEQUENCER, RPC, - P2P + P2P, } override fun equals(other: Any?): Boolean { diff --git a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionServiceV1.kt b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionServiceV1.kt index c6933ab4..580c5ad0 100644 --- a/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionServiceV1.kt +++ b/transaction-exclusion-api/core/src/main/kotlin/net/consensys/linea/transactionexclusion/TransactionExclusionServiceV1.kt @@ -6,14 +6,14 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface TransactionExclusionServiceV1 { enum class SaveRejectedTransactionStatus { SAVED, - DUPLICATE_ALREADY_SAVED_BEFORE + DUPLICATE_ALREADY_SAVED_BEFORE, } fun saveRejectedTransaction( - rejectedTransaction: RejectedTransaction + rejectedTransaction: RejectedTransaction, ): SafeFuture> fun getTransactionExclusionStatus( - txHash: ByteArray + txHash: ByteArray, ): SafeFuture> } diff --git a/transaction-exclusion-api/core/src/testFixtures/kotlin/net.consensys.linea.transactionexclusion.test/Common.kt b/transaction-exclusion-api/core/src/testFixtures/kotlin/net.consensys.linea.transactionexclusion.test/Common.kt index 8e0052cf..2bbba672 100644 --- a/transaction-exclusion-api/core/src/testFixtures/kotlin/net.consensys.linea.transactionexclusion.test/Common.kt +++ b/transaction-exclusion-api/core/src/testFixtures/kotlin/net.consensys.linea.transactionexclusion.test/Common.kt @@ -21,25 +21,25 @@ val defaultRejectedTransaction = RejectedTransaction( ModuleOverflow( module = "ADD", count = 402, - limit = 70 + limit = 70, ), ModuleOverflow( module = "MUL", count = 587, - limit = 401 + limit = 401, ), ModuleOverflow( module = "EXP", count = 9000, - limit = 8192 - ) + limit = 8192, + ), ), transactionInfo = TransactionInfo( hash = "0x526e56101cf39c1e717cef9cedf6fdddb42684711abda35bae51136dbb350ad7".decodeHex(), from = "0x4d144d7b9c96b26361d6ac74dd1d8267edca4fc2".decodeHex(), to = "0x1195cf65f83b3a5768f3c496d3a05ad6412c64b3".decodeHex(), - nonce = 100UL - ) + nonce = 100UL, + ), ) val rejectedContractDeploymentTransaction = RejectedTransaction( @@ -59,13 +59,13 @@ val rejectedContractDeploymentTransaction = RejectedTransaction( ModuleOverflow( module = "HUB", count = 2119318, - limit = 2097152 - ) + limit = 2097152, + ), ), transactionInfo = TransactionInfo( hash = "0x583eb047887cc72f93ead08f389a2cd84440f3322bc4b191803d5adb0a167525".decodeHex(), from = "0x0d06838d1dfba9ef0a4166cca9be16fb1d76dbfc".decodeHex(), to = null, - nonce = 1UL - ) + nonce = 1UL, + ), ) diff --git a/transaction-exclusion-api/persistence/rejectedtransaction/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDaoTest.kt b/transaction-exclusion-api/persistence/rejectedtransaction/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDaoTest.kt index 5a46bb36..c0b231a6 100644 --- a/transaction-exclusion-api/persistence/rejectedtransaction/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDaoTest.kt +++ b/transaction-exclusion-api/persistence/rejectedtransaction/src/integrationTest/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDaoTest.kt @@ -48,7 +48,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { transactionRLP: ByteArray = defaultRejectedTransaction.transactionRLP, reasonMessage: String = defaultRejectedTransaction.reasonMessage, overflows: List = defaultRejectedTransaction.overflows, - transactionInfo: TransactionInfo = defaultRejectedTransaction.transactionInfo + transactionInfo: TransactionInfo = defaultRejectedTransaction.transactionInfo, ): RejectedTransaction { return RejectedTransaction( txRejectionStage = txRejectionStage, @@ -57,7 +57,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { transactionRLP = transactionRLP, reasonMessage = reasonMessage, overflows = overflows, - transactionInfo = transactionInfo + transactionInfo = transactionInfo, ) } @@ -78,12 +78,12 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { RejectedTransactionsPostgresDao( readConnection = sqlClient, writeConnection = sqlClient, - clock = fakeClock + clock = fakeClock, ) } private fun performInsertTest( - rejectedTransaction: RejectedTransaction + rejectedTransaction: RejectedTransaction, ) { rejectedTransactionsPostgresDao.saveNewRejectedTransaction(rejectedTransaction).get() @@ -94,7 +94,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { } assertThat(newlyInsertedFullTxnsRows.size).isEqualTo(1) assertThat(newlyInsertedFullTxnsRows.first().getBuffer("tx_rlp").bytes).isEqualTo( - rejectedTransaction.transactionRLP + rejectedTransaction.transactionRLP, ) // assert the corresponding record was inserted into the rejected_transactions table @@ -106,28 +106,28 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(newlyInsertedRejectedTxnsRows.size).isEqualTo(1) val insertedRow = newlyInsertedRejectedTxnsRows.first() assertThat(insertedRow.getLong("created_epoch_milli")).isEqualTo( - fakeClock.now().toEpochMilliseconds() + fakeClock.now().toEpochMilliseconds(), ) assertThat(insertedRow.getString("reject_stage")).isEqualTo( - RejectedTransactionsPostgresDao.rejectedStageToDbValue(rejectedTransaction.txRejectionStage) + RejectedTransactionsPostgresDao.rejectedStageToDbValue(rejectedTransaction.txRejectionStage), ) assertThat(insertedRow.getLong("block_number")?.toULong()).isEqualTo( - rejectedTransaction.blockNumber + rejectedTransaction.blockNumber, ) assertThat(insertedRow.getJsonArray("overflows").encode()).isEqualTo( - ObjectMapper().writeValueAsString(rejectedTransaction.overflows) + ObjectMapper().writeValueAsString(rejectedTransaction.overflows), ) assertThat(insertedRow.getLong("reject_timestamp")).isEqualTo( - rejectedTransaction.timestamp.toEpochMilliseconds() + rejectedTransaction.timestamp.toEpochMilliseconds(), ) assertThat(insertedRow.getBuffer("tx_from").bytes).isEqualTo( - rejectedTransaction.transactionInfo.from + rejectedTransaction.transactionInfo.from, ) assertThat(insertedRow.getBuffer("tx_to")?.bytes).isEqualTo( - rejectedTransaction.transactionInfo.to + rejectedTransaction.transactionInfo.to, ) assertThat(insertedRow.getLong("tx_nonce")).isEqualTo( - rejectedTransaction.transactionInfo.nonce.toLong() + rejectedTransaction.transactionInfo.nonce.toLong(), ) } @@ -166,10 +166,10 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { ModuleOverflow( module = "MUL", count = 587, - limit = 401 - ) - ) - ) + limit = 401, + ), + ), + ), ) // assert that the total number of rows in the two tables are correct @@ -190,9 +190,9 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { ModuleOverflow( module = "ADD", count = 587, - limit = 401 - ) - ) + limit = 401, + ), + ), ) // assert that the insertion of duplicatedRejectedTransaction would trigger DuplicatedRecordException error @@ -203,7 +203,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { assertThat(executionException.cause!!.message) .isEqualTo( "RejectedTransaction ${duplicatedRejectedTransaction.transactionInfo.hash.encodeHex()} " + - "is already persisted!" + "is already persisted!", ) } @@ -216,7 +216,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { fun `findRejectedTransactionByTxHash returns rejected transaction with most recent timestamp from db`() { // insert a new rejected transaction val oldestRejectedTransaction = createRejectedTransaction( - timestamp = fakeClock.now().minus(10.seconds) + timestamp = fakeClock.now().minus(10.seconds), ) performInsertTest(oldestRejectedTransaction) @@ -225,21 +225,21 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { performInsertTest( createRejectedTransaction( reasonMessage = "Transaction line count for module MUL=587 is above the limit 401", - timestamp = fakeClock.now().minus(9.seconds) - ) + timestamp = fakeClock.now().minus(9.seconds), + ), ) // insert another rejected transaction with same txHash but different reason // and with the most recent timestamp val newestRejectedTransaction = createRejectedTransaction( reasonMessage = "Transaction line count for module EXP=9000 is above the limit 8192", - timestamp = fakeClock.now().minus(8.seconds) + timestamp = fakeClock.now().minus(8.seconds), ) performInsertTest(newestRejectedTransaction) // find the rejected transaction with the txHash val foundRejectedTransaction = rejectedTransactionsPostgresDao.findRejectedTransactionByTxHash( - oldestRejectedTransaction.transactionInfo.hash + oldestRejectedTransaction.transactionInfo.hash, ).get() // assert that the found rejected transaction is the same as the one with most recent timestamp @@ -254,14 +254,14 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { fun `findRejectedTransactionByTxHash returns null as rejected timestamp exceeds queryable window`() { // insert a new rejected transaction with timestamp exceeds the 1-hour queryable window val rejectedTransaction = createRejectedTransaction( - timestamp = fakeClock.now().minus(1.hours).minus(1.seconds) + timestamp = fakeClock.now().minus(1.hours).minus(1.seconds), ) performInsertTest(rejectedTransaction) // find the rejected transaction with the txHash val foundRejectedTransaction = rejectedTransactionsPostgresDao.findRejectedTransactionByTxHash( rejectedTransaction.transactionInfo.hash, - notRejectedBefore + notRejectedBefore, ).get() // assert that null is returned from the find method @@ -282,11 +282,11 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { hash = "0x078ecd6f00bff4beca9116ca85c65ddd265971e415d7df7a96b3c10424b031e2".decodeHex(), from = "0x4d144d7b9c96b26361d6ac74dd1d8267edca4fc2".decodeHex(), to = "0x1195cf65f83b3a5768f3c496d3a05ad6412c64b3".decodeHex(), - nonce = 101UL + nonce = 101UL, ), reasonMessage = "Transaction line count for module EXP=10000 is above the limit 8192", - timestamp = fakeClock.now() - ) + timestamp = fakeClock.now(), + ), ) // advance the fake clock to make its created timestamp exceeds the 10-hours storage window fakeClock.advanceBy(1.hours) @@ -294,8 +294,8 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { // insert another rejected transaction B1 performInsertTest( createRejectedTransaction( - timestamp = fakeClock.now() - ) + timestamp = fakeClock.now(), + ), ) // advance the fake clock to make its created timestamp exceeds the 10-hours storage window fakeClock.advanceBy(1.hours) @@ -304,8 +304,8 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { performInsertTest( createRejectedTransaction( reasonMessage = "Transaction line count for module EXP=9000 is above the limit 8192", - timestamp = fakeClock.now() - ) + timestamp = fakeClock.now(), + ), ) // advance the fake clock to make its created timestamp stay within the 10-hours storage window fakeClock.advanceBy(10.hours) @@ -317,7 +317,7 @@ class RejectedTransactionsPostgresDaoTest : CleanDbTestSuiteParallel() { // delete the rejected transactions with storage window as 10 hours from now val deletedRows = rejectedTransactionsPostgresDao.deleteRejectedTransactions( - fakeClock.now().minus(10.hours) + fakeClock.now().minus(10.hours), ).get() // assert that number of total deleted rows in rejected_transactions table is 2 diff --git a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsDao.kt b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsDao.kt index 140ab685..0882b21e 100644 --- a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsDao.kt +++ b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsDao.kt @@ -6,15 +6,15 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture interface RejectedTransactionsDao { fun saveNewRejectedTransaction( - rejectedTransaction: RejectedTransaction + rejectedTransaction: RejectedTransaction, ): SafeFuture fun findRejectedTransactionByTxHash( txHash: ByteArray, - notRejectedBefore: Instant = Instant.DISTANT_PAST + notRejectedBefore: Instant = Instant.DISTANT_PAST, ): SafeFuture fun deleteRejectedTransactions( - createdBefore: Instant + createdBefore: Instant, ): SafeFuture } diff --git a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDao.kt b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDao.kt index 59ab1b2a..602232f7 100644 --- a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDao.kt +++ b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RejectedTransactionsPostgresDao.kt @@ -22,7 +22,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RejectedTransactionsPostgresDao( private val readConnection: SqlClient, private val writeConnection: SqlClient, - private val clock: Clock = Clock.System + private val clock: Clock = Clock.System, ) : RejectedTransactionsDao { private val log = LogManager.getLogger(this.javaClass.name) private val queryLog = SQLQueryLogger(log) @@ -44,7 +44,7 @@ class RejectedTransactionsPostgresDao( "P2P" -> RejectedTransaction.Stage.P2P else -> throw IllegalStateException( "The db string value: \"$dbStrValue\" cannot be mapped to any RejectedTransaction.Stage enums: " + - RejectedTransaction.Stage.entries.joinToString(",", "[", "]") { it.name } + RejectedTransaction.Stage.entries.joinToString(",", "[", "]") { it.name }, ) } } @@ -52,7 +52,7 @@ class RejectedTransactionsPostgresDao( fun parseModuleOverflowListFromJsonString(jsonString: String): List { return ObjectMapper().readValue( jsonString, - Array::class.java + Array::class.java, ).toList() } @@ -64,14 +64,14 @@ class RejectedTransactionsPostgresDao( transactionRLP = record.getBuffer("tx_rlp").bytes, reasonMessage = record.getString("reject_reason"), overflows = parseModuleOverflowListFromJsonString( - record.getJsonArray("overflows").encode() + record.getJsonArray("overflows").encode(), ), transactionInfo = TransactionInfo( hash = record.getBuffer("tx_hash").bytes, from = record.getBuffer("tx_from").bytes, to = record.getBuffer("tx_to")?.bytes, - nonce = record.getLong("tx_nonce").toULong() - ) + nonce = record.getLong("tx_nonce").toULong(), + ), ) } @@ -145,7 +145,7 @@ class RejectedTransactionsPostgresDao( rejectedTransaction.timestamp.toEpochMilliseconds(), rejectedTransaction.blockNumber?.toLong(), ObjectMapper().writeValueAsString(rejectedTransaction.overflows), - rejectedTransaction.transactionRLP + rejectedTransaction.transactionRLP, ) queryLog.log(Level.TRACE, insertSql, params) @@ -156,8 +156,8 @@ class RejectedTransactionsPostgresDao( Future.failedFuture( DuplicatedRecordException( "RejectedTransaction ${rejectedTransaction.transactionInfo.hash.encodeHex()} is already persisted!", - th - ) + th, + ), ) } else { Future.failedFuture(th) @@ -168,14 +168,14 @@ class RejectedTransactionsPostgresDao( override fun findRejectedTransactionByTxHash( txHash: ByteArray, - notRejectedBefore: Instant + notRejectedBefore: Instant, ): SafeFuture { return selectSqlQuery .execute( Tuple.of( txHash, - notRejectedBefore.toEpochMilliseconds() - ) + notRejectedBefore.toEpochMilliseconds(), + ), ) .toSafeFuture() .thenApply { rowSet -> rowSet.map(::parseRecord) } @@ -183,7 +183,7 @@ class RejectedTransactionsPostgresDao( } override fun deleteRejectedTransactions( - createdBefore: Instant + createdBefore: Instant, ): SafeFuture { return deleteRejectedTransactionsSqlQuery .execute(Tuple.of(createdBefore.toEpochMilliseconds())) diff --git a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDao.kt b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDao.kt index 5a50edd6..546fa488 100644 --- a/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDao.kt +++ b/transaction-exclusion-api/persistence/rejectedtransaction/src/main/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDao.kt @@ -7,7 +7,7 @@ import tech.pegasys.teku.infrastructure.async.SafeFuture class RetryingRejectedTransactionsPostgresDao( private val delegate: RejectedTransactionsPostgresDao, - private val persistenceRetryer: PersistenceRetryer + private val persistenceRetryer: PersistenceRetryer, ) : RejectedTransactionsDao { override fun saveNewRejectedTransaction(rejectedTransaction: RejectedTransaction): SafeFuture { return persistenceRetryer.retryQuery({ delegate.saveNewRejectedTransaction(rejectedTransaction) }) @@ -15,7 +15,7 @@ class RetryingRejectedTransactionsPostgresDao( override fun findRejectedTransactionByTxHash( txHash: ByteArray, - notRejectedBefore: Instant + notRejectedBefore: Instant, ): SafeFuture { return persistenceRetryer.retryQuery({ delegate.findRejectedTransactionByTxHash(txHash, notRejectedBefore) }) } diff --git a/transaction-exclusion-api/persistence/rejectedtransaction/src/test/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDaoTest.kt b/transaction-exclusion-api/persistence/rejectedtransaction/src/test/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDaoTest.kt index b21dbf81..7570d8ad 100644 --- a/transaction-exclusion-api/persistence/rejectedtransaction/src/test/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDaoTest.kt +++ b/transaction-exclusion-api/persistence/rejectedtransaction/src/test/kotlin/net/consensys/zkevm/persistence/dao/rejectedtransaction/RetryingRejectedTransactionsPostgresDaoTest.kt @@ -34,9 +34,9 @@ class RetryingRejectedTransactionsPostgresDaoTest { PersistenceRetryer( vertx = vertx, PersistenceRetryer.Config( - backoffDelay = 1.milliseconds - ) - ) + backoffDelay = 1.milliseconds, + ), + ), ) whenever(delegateRejectedTransactionsDao.saveNewRejectedTransaction(eq(rejectedTransaction))) @@ -45,8 +45,8 @@ class RetryingRejectedTransactionsPostgresDaoTest { whenever( delegateRejectedTransactionsDao.findRejectedTransactionByTxHash( eq(rejectedTransaction.transactionInfo.hash), - eq(notRejectedBefore) - ) + eq(notRejectedBefore), + ), ) .thenReturn(SafeFuture.completedFuture(null)) @@ -61,16 +61,16 @@ class RetryingRejectedTransactionsPostgresDaoTest { retryingRejectedTransactionsPostgresDao.findRejectedTransactionByTxHash( rejectedTransaction.transactionInfo.hash, - notRejectedBefore + notRejectedBefore, ) verify(delegateRejectedTransactionsDao, times(1)).findRejectedTransactionByTxHash( eq(rejectedTransaction.transactionInfo.hash), - eq(notRejectedBefore) + eq(notRejectedBefore), ) retryingRejectedTransactionsPostgresDao.deleteRejectedTransactions(createdBefore) verify(delegateRejectedTransactionsDao, times(1)).deleteRejectedTransactions( - eq(createdBefore) + eq(createdBefore), ) } }