From 4400fd27c8c8cf74f6dfd5f95daa1679a60696d1 Mon Sep 17 00:00:00 2001 From: Oleg Jakushkin Date: Mon, 7 Nov 2022 16:33:04 +0000 Subject: [PATCH] Review fixes 1) throw concrete exceptions 2) Naming 3) Unused removal 4) Function simplified 5) standarizing is all over the solution --- .../Executor/UserOperationSimulator.cs | 2 +- .../Contract/ContractDataStoreTests.cs | 4 +- .../ContractDataStoreWithLocalDataTests.cs | 4 +- .../Contract/TxPriorityContractTests.cs | 6 +- .../ReadOnlyBlockTreeTests.cs | 2 +- .../Validators/HeaderValidatorTests.cs | 2 +- .../BlockTree.AcceptVisitor.cs | 4 +- .../Nethermind.Blockchain/BlockTree.cs | 8 +-- .../BlockhashProvider.cs | 6 +- .../Contracts/Json/AbiDefinitionConverter.cs | 2 +- .../Data/FileLocalDataSource.cs | 2 +- .../Find/IBlockFinder.cs | 16 ++--- .../ReadOnlyBlockTree.cs | 4 +- .../Receipts/PersistentReceiptStorage.cs | 4 +- .../Receipts/ReceiptsIterator.cs | 4 +- .../Receipts/ReceiptsRecovery.cs | 2 +- .../Synchronization/ISyncConfig.cs | 2 +- .../Visitors/StartupBlockTreeFixer.cs | 6 +- .../Modules/CliFunctionAttribute.cs | 2 +- .../Nethermind.Cli/Modules/CliModuleLoader.cs | 6 +- .../Modules/CliPropertyAttribute.cs | 2 +- src/Nethermind/Nethermind.Cli/NodeManager.cs | 2 +- .../CliqueBlockProducerTests.cs | 2 +- .../StandardConfigTests.cs | 2 +- .../Nethermind.Config/ConfigSourceHelper.cs | 2 +- .../AuRaContractGasLimitOverride.cs | 2 +- .../AuRaSealValidator.cs | 6 +- .../Contracts/DataStore/ContractDataStore.cs | 2 +- .../DataStore/DictionaryContractDataStore.cs | 2 +- .../Contracts/TxPriorityContract.LocalData.cs | 2 +- .../InitializeBlockchainAuRa.cs | 46 ++++++------- .../LoadGenesisBlockAuRa.cs | 6 +- .../StartBlockProducerAuRa.cs | 26 ++++---- .../TxAuRaFilterBuilders.cs | 4 +- .../Rewards/AuRaRewardCalculator.cs | 8 +-- .../Validators/ContractBasedValidator.cs | 4 +- .../Validators/ListBasedValidator.cs | 2 +- .../Validators/MultiValidator.cs | 2 +- .../Validators/PendingValidatorsDecoder.cs | 4 +- .../ReportingContractBasedValidator.cs | 2 +- .../Validators/ValidatorInfoDecoder.cs | 6 +- .../Validators/ValidatorStore.cs | 2 +- .../BlockHeaderExtensions.cs | 2 +- .../CliqueBlockProducer.cs | 8 +-- .../CliqueRpcModule.cs | 8 +-- .../SnapshotManager.cs | 6 +- .../EthashSealer.cs | 12 ++-- .../Comparers/TransactionComparerProvider.cs | 2 +- .../Processing/BlockchainProcessor.cs | 18 +++--- .../Processing/CompositeDataRecoveryStep.cs | 2 +- .../Processing/ReadOnlyTxProcessingEnv.cs | 2 +- .../Producers/BlockProducerBase.cs | 6 +- .../IBlockProductionTriggerExtensions.cs | 10 +-- .../Tracing/GethStyleTracer.cs | 20 +++--- .../Nethermind.Consensus/Tracing/Tracer.cs | 4 +- .../Transactions/TxFilterPipelineBuilder.cs | 2 +- .../Nethermind.Consensus/TxFilterAdapter.cs | 2 +- .../Validators/HeaderValidator.cs | 4 +- .../Validators/UnclesValidator.cs | 4 +- .../Nethermind.Core.Test/AddressTests.cs | 4 +- .../Builders/BlockBuilder.cs | 2 +- .../Nethermind.Core.Test/BytesTests.cs | 10 +-- .../Encoding/BlockInfoDecoderTests.cs | 2 +- .../Nethermind.Core.Test/KeccakTests.cs | 4 +- .../MicrosoftJwtAuthentication.cs | 4 +- src/Nethermind/Nethermind.Core/Block.cs | 8 +-- src/Nethermind/Nethermind.Core/BlockHeader.cs | 4 +- .../Caching/MemCountingCache.cs | 2 +- .../Collections/LinkedHashSet.cs | 20 +++--- .../Eip2930/AccessListBuilder.cs | 2 +- .../Nethermind.Core/Extensions/Bytes.cs | 2 +- src/Nethermind/Nethermind.Core/Reactive.cs | 2 +- src/Nethermind/Nethermind.Core/Transaction.cs | 2 +- .../Nethermind.Crypto/EthereumEcdsa.cs | 2 +- .../SecureStringExtensions.cs | 4 +- .../Nethermind.Db.Rocks/DbOnTheRocks.cs | 6 +- .../Nethermind.Db.Rocks/RocksDbExtensions.cs | 2 +- .../Nethermind.Db/Blooms/BloomStorage.cs | 4 +- .../Nethermind.Db/ReadOnlyDbProvider.cs | 4 +- .../Nethermind.Db/SimpleFilePublicKeyDb.cs | 4 +- .../Integrations/EthStatsIntegration.cs | 2 +- .../VirtualMachineTestsBase.cs | 2 +- .../Nethermind.Evm/CodeAnalysis/CodeInfo.cs | 2 +- .../Nethermind.Evm/EvmPooledMemory.cs | 4 +- src/Nethermind/Nethermind.Evm/IEvmMemory.cs | 2 +- .../Precompiles/EcRecoverPrecompile.cs | 2 +- .../Nethermind.Evm/Tracing/BlockTracerBase.cs | 2 +- .../Tracing/GethStyle/GethLikeTxTracer.cs | 4 +- .../Tracing/ParityStyle/ParityLikeTxTracer.cs | 4 +- .../Tracing/Proofs/ProofTxTracer.cs | 6 +- .../TransactionProcessor.cs | 4 +- .../Nethermind.Evm/VirtualMachine.cs | 6 +- .../Nethermind.Facade/BlockchainBridge.cs | 2 +- .../Nethermind.Facade/Eth/EthSyncingInfo.cs | 4 +- .../Filters/AddressFilter.cs | 8 +-- .../Filters/FilterManager.cs | 8 +-- .../Nethermind.Facade/Filters/FilterStore.cs | 6 +- .../Nethermind.Facade/Filters/LogFinder.cs | 8 +-- src/Nethermind/Nethermind.Grpc/Nethermind.cs | 8 +-- .../Nethermind.Grpc/NethermindGrpc.cs | 4 +- src/Nethermind/Nethermind.Hive/HivePlugin.cs | 12 ++-- .../Steps/EthereumStepsManager.cs | 4 +- .../Nethermind.Init/Steps/FilterBootnodes.cs | 4 +- .../Nethermind.Init/Steps/InitRlp.cs | 2 +- .../Steps/InitializeBlockProducer.cs | 2 +- .../Steps/InitializeBlockchain.cs | 16 ++--- .../Steps/InitializeNetwork.cs | 64 +++++++++---------- .../Nethermind.Init/Steps/LoadGenesisBlock.cs | 24 +++---- .../Steps/Migrations/BloomMigration.cs | 22 +++---- .../Steps/Migrations/ReceiptFixMigration.cs | 2 +- .../Steps/RegisterRpcModules.cs | 62 +++++++++--------- .../Nethermind.Init/Steps/ReviewBlockTree.cs | 4 +- .../Steps/StartBlockProcessor.cs | 2 +- .../Steps/StartBlockProducer.cs | 4 +- .../Steps/UpdateDiscoveryConfig.cs | 2 +- .../Data/SerializationTestBase.cs | 2 +- .../Data/BlockParameterConverter.cs | 2 +- .../Data/TransactionForRpc.cs | 6 +- .../Nethermind.JsonRpc/JsonRpcProcessor.cs | 10 +-- .../Nethermind.JsonRpc/JsonRpcRequest.cs | 2 +- .../Nethermind.JsonRpc/JsonRpcService.cs | 8 +-- .../Nethermind.JsonRpc/JsonRpcUrl.cs | 6 +- .../JsonRpcUrlCollection.cs | 2 +- .../Modules/Admin/AdminRpcModule.cs | 2 +- .../Modules/Admin/PeerInfo.cs | 4 +- .../Modules/BlockFinderExtensions.cs | 14 ++-- .../Modules/DebugModule/DebugBridge.cs | 2 +- .../Modules/DebugModule/DebugRpcModule.cs | 24 +++---- .../DebugModule/GethLikeTxTraceConverter.cs | 2 +- .../Modules/Eth/EthRpcModule.cs | 16 ++--- .../Nethermind.JsonRpc/Modules/Eth/Filter.cs | 2 +- .../Modules/ModuleFactoryBase.cs | 2 +- .../Modules/Parity/ParityRpcModule.cs | 2 +- .../Modules/Proof/ProofRpcModule.cs | 4 +- .../Modules/ReceiptFinderExtensions.cs | 2 +- .../Modules/RpcModuleProvider.cs | 2 +- .../ParityAccountStateChangeConverter.cs | 18 +++--- .../Trace/ParityTraceAddressConverter.cs | 2 +- .../Trace/ParityTraceResultConverter.cs | 2 +- .../Trace/ParityTxTraceFromReplayConverter.cs | 2 +- .../ConsolePasswordProvider.cs | 2 +- .../Nethermind.KeyStore/FileKeyStore.cs | 10 +-- .../FilePasswordProvider.cs | 2 +- .../KeyStorePasswordProvider.cs | 2 +- .../StackTraceUtils.cs | 6 +- .../BlockTreeTests.cs | 4 +- .../EngineModuleTests.HelperFunctions.cs | 2 +- .../ExternalRpcIntegrationTests.cs | 4 +- .../Synchronization/BeaconHeadersSyncTests.cs | 8 +-- .../Data/V1/ExecutionPayloadV1.cs | 2 +- .../Handlers/V1/ForkchoiceUpdatedV1Handler.cs | 10 +-- .../Handlers/V1/GetPayloadV1Handler.cs | 2 +- .../Handlers/V1/NewPayloadV1Handler.cs | 2 +- .../InvalidChainTracker.cs | 4 +- .../MergePlugin.BlockProducer.cs | 30 ++++----- .../Nethermind.Merge.Plugin/MergePlugin.cs | 18 +++--- .../Nethermind.Merge.Plugin/PoSSwitcher.cs | 6 +- .../Synchronization/BeaconSync.cs | 2 +- .../Synchronization/ChainLevelHelper.cs | 16 ++--- .../Synchronization/MergeBlockDownloader.cs | 6 +- ...BlocksSyncPeerAllocationStrategyFactory.cs | 2 +- .../Synchronization/PeerRefresher.cs | 2 +- src/Nethermind/Nethermind.Mev/MevRpcModule.cs | 2 +- .../Metrics/MetricsController.cs | 31 +++++---- .../MonitoringService.cs | 2 +- .../DiscoveryApp.cs | 4 +- .../DiscoveryManager.cs | 4 +- .../Lifecycle/NodeLifecycleManager.cs | 2 +- .../Lifecycle/NodeLifecycleManagerFactory.cs | 2 +- .../NettyDiscoveryHandler.cs | 4 +- .../NodesLocator.cs | 2 +- .../RoutingTable/NodeTable.cs | 2 +- .../Serializers/NeighborsMsgSerializer.cs | 2 +- .../Nethermind.Network.Dns/EnrTreeParser.cs | 2 +- .../NodeStatsManager.cs | 2 +- .../Eth/V63/ReceiptsMessageSerializerTests.cs | 6 +- .../PeerManagerTests.cs | 2 +- .../SnapProtocolHandlerTests.cs | 2 +- .../MessageSerializationService.cs | 4 +- .../Nethermind.Network/NetworkStorage.cs | 2 +- .../Nethermind.Network/NodesLoader.cs | 2 +- .../Nethermind.Network/P2P/MessageQueue.cs | 4 +- .../SyncPeerProtocolHandlerBase.cs | 6 +- .../Nethermind.Network/P2P/Session.cs | 16 ++--- .../Eth/V62/Eth62ProtocolHandler.cs | 2 +- .../Eth/V62/MessageSizeEstimator.cs | 6 +- .../Eth/V62/Messages/BlockBodiesMessage.cs | 2 +- .../Messages/BlockBodiesMessageSerializer.cs | 2 +- .../GetBlockHeadersMessageSerializer.cs | 4 +- .../V63/Messages/ReceiptsMessageSerializer.cs | 4 +- .../Subprotocols/Les/LesProtocolHandler.cs | 6 +- .../Messages/AccountRangeMessageSerializer.cs | 8 +-- .../Messages/GetTrieNodesMessageSerializer.cs | 4 +- .../StorageRangesMessageSerializer.cs | 8 +-- .../BlockWitnessHashesMessageSerializer.cs | 2 +- .../Nethermind.Network/PeerManager.cs | 4 +- .../Nethermind.Network/Rlpx/RlpxHost.cs | 2 +- .../Nethermind.Network/SessionMonitor.cs | 2 +- .../Framework/TestBuilder.cs | 2 +- .../EthereumRunnerTests.cs | 4 +- .../Nethermind.Runner/JsonRpc/Startup.cs | 4 +- .../Logging/CustomMicrosoftLogger.cs | 2 +- src/Nethermind/Nethermind.Runner/Program.cs | 4 +- .../PublicKeyConverter.cs | 2 +- .../UInt256Converter.cs | 2 +- .../AccountDecoder.cs | 6 +- .../BlockInfoDecoder.cs | 2 +- .../ChainLevelDecoder.cs | 4 +- .../Eip2930/AccessListDecoder.cs | 4 +- .../HeaderDecoder.cs | 2 +- .../LogEntryDecoder.cs | 10 +-- .../ReceiptMessageDecoder.cs | 4 +- .../ReceiptStorageDecoder.cs | 4 +- .../RlpDecoderExtensions.cs | 4 +- .../Nethermind.Serialization.Rlp/RlpStream.cs | 10 +-- .../Nethermind.Serialization.Rlp/TxDecoder.cs | 2 +- .../ChainSpecStyle/ChainSpecLoader.cs | 12 ++-- .../BySpeedStrategyTests.cs | 2 +- .../BlockDownloaderTests.cs | 4 +- .../FastBlocks/FastBlocksFeedTests.cs | 6 +- .../FastSync/ReceiptsSyncFeedTests.cs | 2 +- .../FastSync/StateSyncFeedTestsBase.cs | 2 +- .../Mocks/FirstFree.cs | 2 +- .../ParallelSync/SyncDispatcherTests.cs | 2 +- .../TrieScenarios.cs | 2 +- .../Blocks/BlockDownloadContext.cs | 4 +- .../Blocks/BlockDownloader.cs | 18 +++--- .../Blocks/BlocksSyncPeerSelectionStrategy.cs | 6 +- .../BlocksSyncPeerSelectionStrategyFactory.cs | 2 +- .../FastBlocks/BodiesSyncFeed.cs | 4 +- .../FastBlocks/FastBlocksSelectionStrategy.cs | 2 +- .../FastBlocks/FastHeadersSyncFeed.cs | 8 +-- .../FastBlocks/MemorySizeEstimator.cs | 10 +-- .../FastBlocks/ReceiptsSyncFeed.cs | 6 +- .../FastSync/DependentItemComparer.cs | 2 +- .../FastSync/PendingSyncItems.cs | 4 +- .../FastSync/TreeSync.cs | 8 +-- .../LesSync/CanonicalHashTrie.cs | 4 +- .../ParallelSync/MultiSyncModeSelector.cs | 2 +- .../ParallelSync/SyncDispatcher.cs | 4 +- .../ParallelSync/SyncProgressResolver.cs | 2 +- .../AllocationStrategies/BySpeedStrategy.cs | 6 +- .../AllocationStrategies/TotalDiffStrategy.cs | 2 +- .../Peers/SyncPeerAllocation.cs | 2 +- .../Peers/SyncPeerPool.cs | 8 +-- .../Peers/SyncPeersReport.cs | 2 +- .../SnapSync/ProgressTracker.cs | 2 +- .../SnapSync/SnapProviderHelper.cs | 4 +- .../SnapSync/SnapSyncFeed.cs | 8 +-- .../StateSync/StateSyncDispatcher.cs | 2 +- .../Nethermind.Synchronization/SyncServer.cs | 10 +-- .../Nethermind.Trie/NodeCommitInfo.cs | 4 +- src/Nethermind/Nethermind.Trie/TreeDumper.cs | 2 +- .../Nethermind.Trie/TrieNode.Visitor.cs | 2 +- .../Collections/SortedPool.cs | 6 +- src/Nethermind/Nethermind.TxPool/TxPool.cs | 2 +- src/Nethermind/Nethermind.TxPool/TxSealer.cs | 2 +- .../Nethermind.Wallet/DevKeyStoreWallet.cs | 2 +- .../ProtectedKeyStoreWallet.cs | 2 +- 259 files changed, 723 insertions(+), 724 deletions(-) diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs b/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs index 20d4108c558..1752daff6c2 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs @@ -252,7 +252,7 @@ private void CallAndRestore( bool treatBlockHeaderAsParentBlock, ITxTracer tracer) { - if (transaction.SenderAddress == null) + if (transaction.SenderAddress is null) { transaction.SenderAddress = Address.SystemUser; } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreTests.cs index 3710549d3a9..4a1bb8c84a1 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreTests.cs @@ -262,8 +262,8 @@ protected virtual TestCase BuildTestCase(IComparer keyComparer = null, DataContract = dataContract, BlockTree = blockTree, ReceiptFinder = receiptsFinder, - ContractDataStore = keyComparer == null - ? (IContractDataStore)new ContractDataStore(new HashSetContractDataStoreCollection(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance) + ContractDataStore = keyComparer is null + ? new ContractDataStore(new HashSetContractDataStoreCollection(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance) : new DictionaryContractDataStore(new SortedListContractDataStoreCollection(keyComparer, valueComparer), dataContract, blockTree, receiptsFinder, LimboLogs.Instance) }; } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreWithLocalDataTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreWithLocalDataTests.cs index a9950f75c6f..1bcb9f86904 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreWithLocalDataTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/ContractDataStoreWithLocalDataTests.cs @@ -129,8 +129,8 @@ private TestCase BuildTestCase(ILocalDataSource> localDataS DataContract = dataContract, BlockTree = blockTree, ReceiptFinder = receiptsFinder, - ContractDataStore = keyComparer == null - ? (IContractDataStore)new ContractDataStoreWithLocalData(new HashSetContractDataStoreCollection(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource) + ContractDataStore = keyComparer is null + ? new ContractDataStoreWithLocalData(new HashSetContractDataStoreCollection(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource) : new DictionaryContractDataStore(new SortedListContractDataStoreCollection(keyComparer, valueComparer), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource) }; } diff --git a/src/Nethermind/Nethermind.AuRa.Test/Contract/TxPriorityContractTests.cs b/src/Nethermind/Nethermind.AuRa.Test/Contract/TxPriorityContractTests.cs index 14c6b5c8844..81343eeb5a3 100644 --- a/src/Nethermind/Nethermind.AuRa.Test/Contract/TxPriorityContractTests.cs +++ b/src/Nethermind/Nethermind.AuRa.Test/Contract/TxPriorityContractTests.cs @@ -158,7 +158,7 @@ public async Task whitelist_should_return_correctly_with_local_storage([Values(t if (!await semaphoreSlim.WaitAsync(100)) { - if (chain.LocalDataSource.Data == null) + if (chain.LocalDataSource.Data is null) { Assert.Fail("Local file rule storage has not been loaded."); } @@ -207,7 +207,7 @@ public async Task priority_should_return_correctly_with_local_storage([Values(tr if (!await semaphoreSlim.WaitAsync(100)) { - if (chain.LocalDataSource.Data == null) + if (chain.LocalDataSource.Data is null) { Assert.Fail("Local file rule storage has not been loaded."); } @@ -253,7 +253,7 @@ public async Task mingas_should_return_correctly_with_local_storage([Values(true if (!await semaphoreSlim.WaitAsync(100)) { - if (chain.LocalDataSource.Data == null) + if (chain.LocalDataSource.Data is null) { Assert.Fail("Local file rule storage has not been loaded."); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/ReadOnlyBlockTreeTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/ReadOnlyBlockTreeTests.cs index 07c3701929c..4bc1cfcf453 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/ReadOnlyBlockTreeTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/ReadOnlyBlockTreeTests.cs @@ -49,7 +49,7 @@ public void DeleteChainSlice_throws_when_endNumber_other_than_bestKnownNumber() [TestCase(10, 20, 15, 16, false, TestName = "Allow deletion.")] public void DeleteChainSlice_throws_when_corrupted_blocks_not_found(long? head, long bestKnown, long start, long? corruptedBlock, bool throws) { - _innerBlockTree.Head.Returns(head == null ? null : Build.A.Block.WithHeader(Build.A.BlockHeader.WithNumber(head.Value).TestObject).TestObject); + _innerBlockTree.Head.Returns(head is null ? null : Build.A.Block.WithHeader(Build.A.BlockHeader.WithNumber(head.Value).TestObject).TestObject); _innerBlockTree.BestKnownNumber.Returns(bestKnown); _innerBlockTree.FindHeader(Arg.Any(), Arg.Any()) .Returns(c => c.Arg() == corruptedBlock ? null : Build.A.BlockHeader.WithNumber(c.Arg()).TestObject); diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Validators/HeaderValidatorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Validators/HeaderValidatorTests.cs index 43041923b11..08e9bf37afb 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Validators/HeaderValidatorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Validators/HeaderValidatorTests.cs @@ -285,7 +285,7 @@ public void When_gas_used_is_negative() public void When_total_difficulty_0_or_null_we_should_skip_total_difficulty_validation(long? totalDifficulty) { _block.Header.Difficulty = 1; - _block.Header.TotalDifficulty = totalDifficulty == null ? null : (UInt256)totalDifficulty; + _block.Header.TotalDifficulty = totalDifficulty is null ? null : (UInt256)totalDifficulty; _block.Header.SealEngineType = SealEngineType.None; _block.Header.Hash = _block.CalculateHash(); diff --git a/src/Nethermind/Nethermind.Blockchain/BlockTree.AcceptVisitor.cs b/src/Nethermind/Nethermind.Blockchain/BlockTree.AcceptVisitor.cs index 0f76e8f84ec..c1a39e710c6 100644 --- a/src/Nethermind/Nethermind.Blockchain/BlockTree.AcceptVisitor.cs +++ b/src/Nethermind/Nethermind.Blockchain/BlockTree.AcceptVisitor.cs @@ -63,10 +63,10 @@ public async Task Accept(IBlockTreeVisitor visitor, CancellationToken cancellati // if we delete blocks during the process then the number of blocks at this level will be falling and we need to adjust the index Keccak hash = level!.BlockInfos[blockIndex - (numberOfBlocksAtThisLevel - level.BlockInfos.Length)].BlockHash; Block block = FindBlock(hash, BlockTreeLookupOptions.None); - if (block == null) + if (block is null) { BlockHeader header = FindHeader(hash, BlockTreeLookupOptions.None); - if (header == null) + if (header is null) { if (await VisitMissing(visitor, hash, cancellationToken)) break; } diff --git a/src/Nethermind/Nethermind.Blockchain/BlockTree.cs b/src/Nethermind/Nethermind.Blockchain/BlockTree.cs index 0f8e5830482..d24d854eee9 100644 --- a/src/Nethermind/Nethermind.Blockchain/BlockTree.cs +++ b/src/Nethermind/Nethermind.Blockchain/BlockTree.cs @@ -1349,7 +1349,7 @@ public void UpdateMainChain(IReadOnlyList blocks, bool wereProcessed, boo public void UpdateBeaconMainChain(BlockInfo[]? blockInfos, long clearBeaconMainChainStartPoint) { - if (blockInfos == null || blockInfos.Length == 0) + if (blockInfos is null || blockInfos.Length == 0) return; using BatchWrite batch = _chainLevelInfoRepository.StartBatch(); @@ -1502,7 +1502,7 @@ private bool HeadImprovementRequirementsSatisfied(BlockHeader header) bool preMergeImprovementRequirementSatisfied = header.TotalDifficulty > (Head?.TotalDifficulty ?? 0) && (header.TotalDifficulty < _specProvider.TerminalTotalDifficulty - || _specProvider.TerminalTotalDifficulty == null); + || _specProvider.TerminalTotalDifficulty is null); // after the merge, we will accept only the blocks with Difficulty = 0. However, during the transition process // we can have terminal PoW blocks with Difficulty > 0. That is why we accept everything greater or equal @@ -1515,7 +1515,7 @@ private bool HeadImprovementRequirementsSatisfied(BlockHeader header) private bool BestSuggestedImprovementRequirementsSatisfied(BlockHeader header) { - if (BestSuggestedHeader == null) return true; + if (BestSuggestedHeader is null) return true; bool reachedTtd = header.IsPostTTD(_specProvider); bool isPostMerge = header.IsPoS(); @@ -1811,7 +1811,7 @@ BlockHeader GetParentHeader(BlockHeader current) => while (stack.TryPop(out (BlockHeader child, ChainLevelInfo level, BlockInfo blockInfo) item)) { item.child.TotalDifficulty = current.TotalDifficulty + item.child.Difficulty; - if (item.level == null) + if (item.level is null) { item.blockInfo = new(item.child.Hash, item.child.TotalDifficulty.Value); item.level = new(false, item.blockInfo); diff --git a/src/Nethermind/Nethermind.Blockchain/BlockhashProvider.cs b/src/Nethermind/Nethermind.Blockchain/BlockhashProvider.cs index 119b74d8c95..d3622a2c4e5 100644 --- a/src/Nethermind/Nethermind.Blockchain/BlockhashProvider.cs +++ b/src/Nethermind/Nethermind.Blockchain/BlockhashProvider.cs @@ -47,7 +47,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number) bool isFastSyncSearch = false; BlockHeader header = _blockTree.FindParentHeader(currentBlock, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (header == null) + if (header is null) { throw new InvalidDataException("Parent header cannot be found when executing BLOCKHASH operation"); } @@ -61,7 +61,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number) } header = _blockTree.FindParentHeader(header, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (header == null) + if (header is null) { throw new InvalidDataException("Parent header cannot be found when executing BLOCKHASH operation"); } @@ -72,7 +72,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number) { BlockHeader currentHeader = header; header = _blockTree.FindHeader(number, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (header == null) + if (header is null) { isFastSyncSearch = true; header = currentHeader; diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionConverter.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionConverter.cs index 93ef3c97a15..e6c8b18fea2 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionConverter.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionConverter.cs @@ -69,7 +69,7 @@ public override AbiDefinition ReadJson( { string name = definitionToken[_nameTokenName]?.Value(); JToken typeToken = definitionToken[_typeTokenName]; - if (typeToken == null) + if (typeToken is null) { continue; } diff --git a/src/Nethermind/Nethermind.Blockchain/Data/FileLocalDataSource.cs b/src/Nethermind/Nethermind.Blockchain/Data/FileLocalDataSource.cs index 65af91e666d..e3d1ec42212 100644 --- a/src/Nethermind/Nethermind.Blockchain/Data/FileLocalDataSource.cs +++ b/src/Nethermind/Nethermind.Blockchain/Data/FileLocalDataSource.cs @@ -71,7 +71,7 @@ private void SetupWatcher(string filePath) catch (PathTooLongException) { } catch (NotSupportedException) { } - if (fileInfo == null) + if (fileInfo is null) { // file name is not valid if (_logger.IsError) _logger.Error($"Invalid file path to watch: {filePath}."); diff --git a/src/Nethermind/Nethermind.Blockchain/Find/IBlockFinder.cs b/src/Nethermind/Nethermind.Blockchain/Find/IBlockFinder.cs index ae74d553605..479f95eb68b 100644 --- a/src/Nethermind/Nethermind.Blockchain/Find/IBlockFinder.cs +++ b/src/Nethermind/Nethermind.Blockchain/Find/IBlockFinder.cs @@ -70,11 +70,11 @@ public interface IBlockFinder public Block? FindLatestBlock() => FindHeadBlock(); - public Block? FindPendingBlock() => PendingHash == null ? null : FindBlock(PendingHash, BlockTreeLookupOptions.None); + public Block? FindPendingBlock() => PendingHash is null ? null : FindBlock(PendingHash, BlockTreeLookupOptions.None); - public Block? FindFinalizedBlock() => FinalizedHash == null ? null : FindBlock(FinalizedHash, BlockTreeLookupOptions.None); + public Block? FindFinalizedBlock() => FinalizedHash is null ? null : FindBlock(FinalizedHash, BlockTreeLookupOptions.None); - public Block? FindSafeBlock() => SafeHash == null ? null : FindBlock(SafeHash, BlockTreeLookupOptions.None); + public Block? FindSafeBlock() => SafeHash is null ? null : FindBlock(SafeHash, BlockTreeLookupOptions.None); public BlockHeader? FindHeader(Keccak blockHash) => FindHeader(blockHash, BlockTreeLookupOptions.None); @@ -86,17 +86,17 @@ public interface IBlockFinder public BlockHeader? FindLatestHeader() => Head?.Header; - public BlockHeader? FindPendingHeader() => PendingHash == null ? null : FindHeader(PendingHash, BlockTreeLookupOptions.None); + public BlockHeader? FindPendingHeader() => PendingHash is null ? null : FindHeader(PendingHash, BlockTreeLookupOptions.None); - public BlockHeader? FindFinalizedHeader() => FinalizedHash == null ? null : FindHeader(FinalizedHash, BlockTreeLookupOptions.None); + public BlockHeader? FindFinalizedHeader() => FinalizedHash is null ? null : FindHeader(FinalizedHash, BlockTreeLookupOptions.None); - public BlockHeader? FindSafeHeader() => SafeHash == null ? null : FindHeader(SafeHash, BlockTreeLookupOptions.None); + public BlockHeader? FindSafeHeader() => SafeHash is null ? null : FindHeader(SafeHash, BlockTreeLookupOptions.None); BlockHeader FindBestSuggestedHeader(); public Block? FindBlock(BlockParameter? blockParameter, bool headLimit = false) { - if (blockParameter == null) + if (blockParameter is null) { return FindLatestBlock(); } @@ -124,7 +124,7 @@ public interface IBlockFinder public BlockHeader? FindHeader(BlockParameter? blockParameter, bool headLimit = false) { - if (blockParameter == null) + if (blockParameter is null) { return FindLatestHeader(); } diff --git a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs index dab6928f569..c790be9b7db 100644 --- a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs +++ b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs @@ -164,7 +164,7 @@ public event EventHandler NewHeadBlock public int DeleteChainSlice(in long startNumber, long? endNumber = null) { var bestKnownNumber = BestKnownNumber; - if (endNumber == null || endNumber == bestKnownNumber) + if (endNumber is null || endNumber == bestKnownNumber) { if (Head?.Number > 0) { @@ -181,7 +181,7 @@ IEnumerable GetPotentiallyCorruptedBlocks(long start) } } - if (GetPotentiallyCorruptedBlocks(startNumber).Any(b => b == null)) + if (GetPotentiallyCorruptedBlocks(startNumber).Any(b => b is null)) { return _wrapped.DeleteChainSlice(startNumber); } diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs index 503d139eaab..c81573ec72f 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs @@ -54,14 +54,14 @@ public PersistentReceiptStorage(IColumnsDb receiptsDb, ISpecPro _transactionDb = _database.GetColumnDb(ReceiptsColumns.Transactions); byte[] lowestBytes = _database.Get(Keccak.Zero); - _lowestInsertedReceiptBlock = lowestBytes == null ? (long?)null : new RlpStream(lowestBytes).DecodeLong(); + _lowestInsertedReceiptBlock = lowestBytes is null ? (long?)null : new RlpStream(lowestBytes).DecodeLong(); _migratedBlockNumber = Get(MigrationBlockNumberKey, long.MaxValue); } public Keccak FindBlockHash(Keccak txHash) { var blockHashData = _transactionDb.Get(txHash); - return blockHashData == null ? FindReceiptObsolete(txHash)?.BlockHash : new Keccak(blockHashData); + return blockHashData is null ? FindReceiptObsolete(txHash)?.BlockHash : new Keccak(blockHashData); } // Find receipt stored with old - obsolete format. diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs index 271a29330d0..e8a4d717b04 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs @@ -51,7 +51,7 @@ public ReceiptsIterator(TxReceipt[] receipts) public bool TryGetNext(out TxReceiptStructRef current) { - if (_receipts == null) + if (_receipts is null) { if (_decoderContext.Position < _length) { @@ -87,7 +87,7 @@ public void Reset() public void Dispose() { - if (_receipts == null && !_decoderContext.Data.IsEmpty) + if (_receipts is null && !_decoderContext.Data.IsEmpty) { _blocksDb?.DangerousReleaseMemory(_decoderContext.Data); } diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsRecovery.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsRecovery.cs index 8359c08d225..65d7a2af525 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsRecovery.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsRecovery.cs @@ -63,7 +63,7 @@ public ReceiptsRecoveryResult TryRecover(Block block, TxReceipt[] receipts, bool return ReceiptsRecoveryResult.Fail; } - public bool NeedRecover(TxReceipt[] receipts, bool forceRecoverSender = true) => receipts?.Length > 0 && (receipts[0].BlockHash == null || (forceRecoverSender && receipts[0].Sender == null)); + public bool NeedRecover(TxReceipt[] receipts, bool forceRecoverSender = true) => receipts?.Length > 0 && (receipts[0].BlockHash is null || (forceRecoverSender && receipts[0].Sender is null)); private void RecoverReceiptData(IReleaseSpec releaseSpec, TxReceipt receipt, Block block, Transaction transaction, int transactionIndex, long gasUsedBefore, bool force) { diff --git a/src/Nethermind/Nethermind.Blockchain/Synchronization/ISyncConfig.cs b/src/Nethermind/Nethermind.Blockchain/Synchronization/ISyncConfig.cs index f073e872496..6c0a49723f3 100644 --- a/src/Nethermind/Nethermind.Blockchain/Synchronization/ISyncConfig.cs +++ b/src/Nethermind/Nethermind.Blockchain/Synchronization/ISyncConfig.cs @@ -71,7 +71,7 @@ public interface ISyncConfig : IConfig UInt256 PivotTotalDifficultyParsed => UInt256.Parse(PivotTotalDifficulty ?? "0"); [ConfigItem(DisabledForCli = true, HiddenFromDocs = true)] - Keccak PivotHashParsed => PivotHash == null ? null : new Keccak(Bytes.FromHexString(PivotHash)); + Keccak PivotHashParsed => PivotHash is null ? null : new Keccak(Bytes.FromHexString(PivotHash)); [ConfigItem(Description = "[EXPERIMENTAL] Defines the earliest body downloaded in fast sync when DownloadBodiesInFastSync is enabled. Actual values used will be Math.Max(1, Math.Min(PivotNumber, AncientBodiesBarrier))", DefaultValue = "0")] public long AncientBodiesBarrier { get; set; } diff --git a/src/Nethermind/Nethermind.Blockchain/Visitors/StartupBlockTreeFixer.cs b/src/Nethermind/Nethermind.Blockchain/Visitors/StartupBlockTreeFixer.cs index 99354577fab..2a908cbd11f 100644 --- a/src/Nethermind/Nethermind.Blockchain/Visitors/StartupBlockTreeFixer.cs +++ b/src/Nethermind/Nethermind.Blockchain/Visitors/StartupBlockTreeFixer.cs @@ -122,7 +122,7 @@ Task IBlockTreeVisitor.VisitLevelStart(ChainLevelInfo chainLe return Task.FromResult(LevelVisitOutcome.DeleteLevel); } - if (chainLevelInfo == null) + if (chainLevelInfo is null) { _gapStart = _currentLevelNumber; } @@ -255,8 +255,8 @@ private bool CanSuggestBlocks(Block block) if (block?.ParentHash != null) { BlockHeader? parentHeader = _blockTree.FindParentHeader(block.Header, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (parentHeader == null || parentHeader.StateRoot == null || - _stateDb.Get(parentHeader.StateRoot) == null) + if (parentHeader is null || parentHeader.StateRoot is null || + _stateDb.Get(parentHeader.StateRoot) is null) return false; } else diff --git a/src/Nethermind/Nethermind.Cli/Modules/CliFunctionAttribute.cs b/src/Nethermind/Nethermind.Cli/Modules/CliFunctionAttribute.cs index fc3cb91e69e..74525602742 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/CliFunctionAttribute.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/CliFunctionAttribute.cs @@ -38,7 +38,7 @@ public CliFunctionAttribute(string objectName, string functionName) public override string ToString() { - return $"{ObjectName}.{FunctionName}{(Description == null ? "" : $" {Description}")}"; + return $"{ObjectName}.{FunctionName}{(Description is null ? "" : $" {Description}")}"; } } } diff --git a/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs b/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs index 97efc8ebed0..bc21a19d2bf 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs @@ -58,7 +58,7 @@ public CliModuleLoader(ICliEngine engine, IJsonRpcClient client, ICliConsole cli /// private static Delegate CreateDelegate(MethodInfo methodInfo, CliModuleBase module) { - if (methodInfo == null) + if (methodInfo is null) { throw new ArgumentNullException(nameof(methodInfo)); } @@ -78,7 +78,7 @@ private static Delegate CreateDelegate(MethodInfo methodInfo, CliModuleBase modu private void LoadModule(CliModuleBase module) { CliModuleAttribute? cliModuleAttribute = module.GetType().GetCustomAttribute(); - if (cliModuleAttribute == null) + if (cliModuleAttribute is null) { _cliConsole.WriteErrorLine( $"Could not load module {module.GetType().Name} bacause of a missing {nameof(CliModuleAttribute)}."); @@ -100,7 +100,7 @@ private void LoadModule(CliModuleBase module) string? objectName = cliProperty?.ObjectName ?? cliFunction?.ObjectName; string? itemName = cliProperty?.PropertyName ?? cliFunction?.FunctionName; - if (objectName == null) + if (objectName is null) { throw new InvalidDataException($"Method {methodInfo.Name} of {module.GetType().Name} should be decorated with one of {nameof(CliPropertyAttribute)} or {nameof(CliFunctionAttribute)}"); } diff --git a/src/Nethermind/Nethermind.Cli/Modules/CliPropertyAttribute.cs b/src/Nethermind/Nethermind.Cli/Modules/CliPropertyAttribute.cs index 7b8d53a68c0..5979667669a 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/CliPropertyAttribute.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/CliPropertyAttribute.cs @@ -36,7 +36,7 @@ public CliPropertyAttribute(string objectName, string propertyName) public override string ToString() { - return $"{ObjectName}.{PropertyName}{(Description == null ? "" : $" {Description}")}"; + return $"{ObjectName}.{PropertyName}{(Description is null ? "" : $" {Description}")}"; } } } diff --git a/src/Nethermind/Nethermind.Cli/NodeManager.cs b/src/Nethermind/Nethermind.Cli/NodeManager.cs index 74a18406503..3202383fe6c 100644 --- a/src/Nethermind/Nethermind.Cli/NodeManager.cs +++ b/src/Nethermind/Nethermind.Cli/NodeManager.cs @@ -126,7 +126,7 @@ public async Task PostJint(string method, params object[] parameters) T? result = default; try { - if (_currentClient == null) + if (_currentClient is null) { _cliConsole.WriteErrorLine("[INTERNAL ERROR] JSON RPC client not set."); } diff --git a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs index 55599a4747e..1d64176de88 100644 --- a/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs +++ b/src/Nethermind/Nethermind.Clique.Test/CliqueBlockProducerTests.cs @@ -428,7 +428,7 @@ private void WaitForNumber(PrivateKey nodeKey, long number) public Block GetBlock(PrivateKey privateKey, long number) { Block block = _blockTrees[privateKey].FindBlock(number, BlockTreeLookupOptions.None); - if (block == null) + if (block is null) { throw new InvalidOperationException($"Cannot find block {number}"); } diff --git a/src/Nethermind/Nethermind.Config.Test/StandardConfigTests.cs b/src/Nethermind/Nethermind.Config.Test/StandardConfigTests.cs index 9b9215a42ad..2d4b98d322b 100644 --- a/src/Nethermind/Nethermind.Config.Test/StandardConfigTests.cs +++ b/src/Nethermind/Nethermind.Config.Test/StandardConfigTests.cs @@ -96,7 +96,7 @@ private static void CheckDescribedOrHidden(PropertyInfo property, object? instan private static void CheckDefault(PropertyInfo property, object? instance) { ConfigItemAttribute? attribute = property.GetCustomAttribute(); - if (attribute == null || attribute.DisabledForCli) + if (attribute is null || attribute.DisabledForCli) { //there are properties without attribute - we don't pay attention to them return; diff --git a/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs b/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs index 50bb08cca86..428f074b931 100644 --- a/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs +++ b/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs @@ -111,7 +111,7 @@ private static object GetValue(Type valueType, string itemValue) var nullableType = Nullable.GetUnderlyingType(valueType); - return nullableType == null + return nullableType is null ? Convert.ChangeType(itemValue, valueType) : !string.IsNullOrEmpty(itemValue) && !itemValue.Equals("null", StringComparison.InvariantCultureIgnoreCase) ? Convert.ChangeType(itemValue, nullableType) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaContractGasLimitOverride.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaContractGasLimitOverride.cs index 66c840d8336..6613590b173 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaContractGasLimitOverride.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaContractGasLimitOverride.cs @@ -118,7 +118,7 @@ public class Cache public bool IsGasLimitValid(BlockHeader parentHeader, in long gasLimit, out long? expectedGasLimit) { expectedGasLimit = GetGasLimitFromContract(parentHeader); - return expectedGasLimit == null || expectedGasLimit == gasLimit; + return expectedGasLimit is null || expectedGasLimit == gasLimit; } } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaSealValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaSealValidator.cs index 290815c644a..9b47226541b 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaSealValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaSealValidator.cs @@ -55,14 +55,14 @@ public bool ValidateParams(BlockHeader parent, BlockHeader header, bool isUncle { const long rejectedStepDrift = 4; - if (header.AuRaSignature == null) + if (header.AuRaSignature is null) { if (_logger.IsError) _logger.Error($"Block {header.Number}, hash {header.Hash} is missing signature."); return false; } // Ensure header is from the step after parent. - if (header.AuRaStep == null) + if (header.AuRaStep is null) { if (_logger.IsError) _logger.Error($"Block {header.Number}, hash {header.Hash} is missing step value."); return false; @@ -234,7 +234,7 @@ public bool ContainsSiblingOrInsert(BlockHeader header, int validatorCount) contains = stepElement.AuthorBlocks?.Contains(item) ?? stepElement.AuthorBlock == item; if (!contains) { - if (stepElement.AuthorBlocks == null) + if (stepElement.AuthorBlocks is null) { stepElement.AuthorBlocks = new HashSet { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ContractDataStore.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ContractDataStore.cs index 437647a80fb..d33fc686c06 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ContractDataStore.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ContractDataStore.cs @@ -42,7 +42,7 @@ public class ContractDataStore : IDisposable, IContractDataStore protected internal ContractDataStore(IContractDataStoreCollection collection, IDataContract dataContract, IBlockTree blockTree, IReceiptFinder receiptFinder, ILogManager logManager) { - Collection = collection == null || collection is ThreadSafeContractDataStoreCollectionDecorator ? collection : new ThreadSafeContractDataStoreCollectionDecorator(collection); + Collection = collection is null || collection is ThreadSafeContractDataStoreCollectionDecorator ? collection : new ThreadSafeContractDataStoreCollectionDecorator(collection); _dataContract = dataContract ?? throw new ArgumentNullException(nameof(dataContract)); _receiptFinder = receiptFinder ?? throw new ArgumentNullException(nameof(receiptFinder)); _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree)); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/DictionaryContractDataStore.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/DictionaryContractDataStore.cs index 49bbe84c237..40eddec7c3c 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/DictionaryContractDataStore.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/DictionaryContractDataStore.cs @@ -46,7 +46,7 @@ public DictionaryContractDataStore( IReceiptFinder receiptFinder, ILogManager logManager, ILocalDataSource> localDataSource) - : this(localDataSource == null + : this(localDataSource is null ? CreateContractDataStore(collection, dataContract, blockTree, receiptFinder, logManager) : CreateContractDataStoreWithLocalData(collection, dataContract, blockTree, receiptFinder, logManager, localDataSource)) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.LocalData.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.LocalData.cs index ecf9d48955c..73cb80733df 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.LocalData.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.LocalData.cs @@ -53,7 +53,7 @@ internal LocalDataSource(LocalDataSource localDataSource, Func Data => _localDataSource.Data == null + public IEnumerable Data => _localDataSource.Data is null ? Enumerable.Empty() : _getData(_localDataSource.Data) ?? Enumerable.Empty(); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs index ea7906fa6b7..f8ccc3092b7 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/InitializeBlockchainAuRa.cs @@ -58,19 +58,19 @@ public InitializeBlockchainAuRa(AuRaNethermindApi api) : base(api) protected override BlockProcessor CreateBlockProcessor() { - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); - if (_api.ChainHeadStateProvider == null) throw new StepDependencyException(nameof(_api.ChainHeadStateProvider)); - if (_api.BlockValidator == null) throw new StepDependencyException(nameof(_api.BlockValidator)); - if (_api.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); - if (_api.TransactionProcessor == null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.StateProvider == null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider == null) throw new StepDependencyException(nameof(_api.StorageProvider)); - if (_api.TxPool == null) throw new StepDependencyException(nameof(_api.TxPool)); - if (_api.ReceiptStorage == null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.GasPriceOracle == null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.ChainHeadStateProvider is null) throw new StepDependencyException(nameof(_api.ChainHeadStateProvider)); + if (_api.BlockValidator is null) throw new StepDependencyException(nameof(_api.BlockValidator)); + if (_api.RewardCalculatorSource is null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); + if (_api.TransactionProcessor is null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); + if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.TxPool is null) throw new StepDependencyException(nameof(_api.TxPool)); + if (_api.ReceiptStorage is null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.GasPriceOracle is null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); var processingReadOnlyTransactionProcessorSource = CreateReadOnlyTransactionProcessorSource(); var txPermissionFilterOnlyTxProcessorSource = CreateReadOnlyTransactionProcessorSource(); @@ -122,10 +122,10 @@ protected override IHealthHintService CreateHealthHintService() => private IAuRaValidator CreateAuRaValidator(IBlockProcessor processor, IReadOnlyTxProcessorSource readOnlyTxProcessorSource) { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.EngineSigner == null) throw new StepDependencyException(nameof(_api.EngineSigner)); - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.EngineSigner is null) throw new StepDependencyException(nameof(_api.EngineSigner)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); var chainSpecAuRa = _api.ChainSpec.AuRa; @@ -166,7 +166,7 @@ private IAuRaValidator CreateAuRaValidator(IBlockProcessor processor, IReadOnlyT protected AuRaContractGasLimitOverride? GetGasLimitCalculator() { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); var blockGasLimitContractTransitions = _api.ChainSpec.AuRa.BlockGasLimitContractTransitions; if (blockGasLimitContractTransitions?.Any() == true) @@ -195,10 +195,10 @@ private IAuRaValidator CreateAuRaValidator(IBlockProcessor processor, IReadOnlyT protected override void InitSealEngine() { - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); - if (_api.EthereumEcdsa == null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.EthereumEcdsa is null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); _api.ValidatorStore = new ValidatorStore(_api.DbProvider.BlockInfosDb); @@ -216,7 +216,7 @@ protected override void InitSealEngine() protected override IHeaderValidator CreateHeaderValidator() { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); var blockGasLimitContractTransitions = _api.ChainSpec.AuRa.BlockGasLimitContractTransitions; return blockGasLimitContractTransitions?.Any() == true ? new AuRaHeaderValidator( diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs index 2a80ae0650f..331c1f9e42c 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/LoadGenesisBlockAuRa.cs @@ -39,13 +39,13 @@ protected override void Load() private void CreateSystemAccounts() { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); bool hasConstructorAllocation = _api.ChainSpec.Allocations.Values.Any(a => a.Constructor != null); if (hasConstructorAllocation) { - if (_api.StateProvider == null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider == null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); + if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); _api.StateProvider.CreateAccount(Address.Zero, UInt256.Zero); _api.StorageProvider.Commit(); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs index 95d66a87fca..84b57dfabc8 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs @@ -87,8 +87,8 @@ public IBlockProductionTrigger CreateTrigger() public Task BuildProducer(IBlockProductionTrigger blockProductionTrigger, ITxSource? additionalTxSource = null) { - if (_api.EngineSigner == null) throw new StepDependencyException(nameof(_api.EngineSigner)); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.EngineSigner is null) throw new StepDependencyException(nameof(_api.EngineSigner)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); ILogger logger = _api.LogManager.GetClassLogger(); if (logger.IsWarn) logger.Warn("Starting AuRa block producer & sealer"); @@ -118,13 +118,13 @@ public Task BuildProducer(IBlockProductionTrigger blockProductio private BlockProcessor CreateBlockProcessor(ReadOnlyTxProcessingEnv changeableTxProcessingEnv, ReadOnlyTxProcessingEnv constantContractTxProcessingEnv) { - if (_api.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); - if (_api.ValidatorStore == null) throw new StepDependencyException(nameof(_api.ValidatorStore)); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.EngineSigner == null) throw new StepDependencyException(nameof(_api.EngineSigner)); - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); - if (_api.GasPriceOracle == null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); + if (_api.RewardCalculatorSource is null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); + if (_api.ValidatorStore is null) throw new StepDependencyException(nameof(_api.ValidatorStore)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.EngineSigner is null) throw new StepDependencyException(nameof(_api.EngineSigner)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.GasPriceOracle is null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); var chainSpecAuRa = _api.ChainSpec.AuRa; @@ -350,9 +350,9 @@ IList GetRandomContracts( return false; } - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.EngineSigner == null) throw new StepDependencyException(nameof(_api.EngineSigner)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.EngineSigner is null) throw new StepDependencyException(nameof(_api.EngineSigner)); IList txSources = new List { CreateStandardTxSourceForProducer(processingEnv, readOnlyTxProcessorSource) }; bool needSigner = false; @@ -384,7 +384,7 @@ IList GetRandomContracts( private IGasLimitCalculator CreateGasLimitCalculator(IReadOnlyTxProcessorSource readOnlyTxProcessorSource) { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); var blockGasLimitContractTransitions = _api.ChainSpec.AuRa.BlockGasLimitContractTransitions; IGasLimitCalculator gasLimitCalculator = diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/TxAuRaFilterBuilders.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/TxAuRaFilterBuilders.cs index 195809439a3..af594c5468c 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/TxAuRaFilterBuilders.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/TxAuRaFilterBuilders.cs @@ -90,8 +90,8 @@ private static ITxFilter CreateBaseAuRaTxFilter( public static ITxFilter? CreateTxPermissionFilter(AuRaNethermindApi api, IReadOnlyTxProcessorSource readOnlyTxProcessorSource) { - if (api.ChainSpec == null) throw new StepDependencyException(nameof(api.ChainSpec)); - if (api.SpecProvider == null) throw new StepDependencyException(nameof(api.SpecProvider)); + if (api.ChainSpec is null) throw new StepDependencyException(nameof(api.ChainSpec)); + if (api.SpecProvider is null) throw new StepDependencyException(nameof(api.SpecProvider)); if (api.ChainSpec.Parameters.TransactionPermissionContract != null) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs index 46a5f890c91..bd25885e6bc 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs @@ -36,9 +36,9 @@ public class AuRaRewardCalculator : IRewardCalculator public AuRaRewardCalculator(AuRaParameters auRaParameters, IAbiEncoder abiEncoder, ITransactionProcessor transactionProcessor) { - if (auRaParameters == null) throw new ArgumentNullException(nameof(auRaParameters)); - if (abiEncoder == null) throw new ArgumentNullException(nameof(abiEncoder)); - if (transactionProcessor == null) throw new ArgumentNullException(nameof(transactionProcessor)); + if (auRaParameters is null) throw new ArgumentNullException(nameof(auRaParameters)); + if (abiEncoder is null) throw new ArgumentNullException(nameof(abiEncoder)); + if (transactionProcessor is null) throw new ArgumentNullException(nameof(transactionProcessor)); IList BuildTransitions() { @@ -64,7 +64,7 @@ IList BuildTransitions() return contracts; } - if (auRaParameters == null) throw new ArgumentNullException(nameof(AuRaParameters)); + if (auRaParameters is null) throw new ArgumentNullException(nameof(AuRaParameters)); _contracts = BuildTransitions(); _blockRewardCalculator = new StaticRewardCalculator(auRaParameters.BlockReward); } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs index d4b2f9f057e..124ca28c79d 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ContractBasedValidator.cs @@ -103,7 +103,7 @@ public override void OnBlockProcessingStart(Block block, ProcessingOptions optio var isProcessingBlock = !isProducingBlock; var isInitBlock = InitBlockNumber == block.Number; var notConsecutiveBlock = block.Number - 1 > _lastProcessedBlockNumber || _lastProcessedBlockNumber == 0; - var shouldLoadValidators = Validators == null || notConsecutiveBlock || isProducingBlock; + var shouldLoadValidators = Validators is null || notConsecutiveBlock || isProducingBlock; var mainChainProcessing = !ForSealing && isProcessingBlock; if (shouldLoadValidators) @@ -229,7 +229,7 @@ private void FinalizePendingValidatorsIfNeeded(BlockHeader block, bool isProcess private void InitiateChange(Block block, Address[] potentialValidators, bool isProcessingBlock, bool initiateChangeIsImmediatelyFinalized = false) { // We are ignoring the signal if there are already pending validators. This replicates Parity behaviour which can be seen as a bug. - if (CurrentPendingValidators == null && potentialValidators.Length > 0) + if (CurrentPendingValidators is null && potentialValidators.Length > 0) { SetPendingValidators(new PendingValidators(block.Number, block.Hash, potentialValidators) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs index 46e842102a3..1f1b90017cb 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs @@ -26,7 +26,7 @@ public sealed class ListBasedValidator : AuRaValidatorBase public ListBasedValidator(AuRaParameters.Validator validator, IValidSealerStrategy validSealerStrategy, IValidatorStore validatorStore, ILogManager logManager, long startBlockNumber, bool forSealing = false) : base(validSealerStrategy, validatorStore, logManager, startBlockNumber, forSealing) { - if (validator == null) throw new ArgumentNullException(nameof(validator)); + if (validator is null) throw new ArgumentNullException(nameof(validator)); Validators = validator.Addresses?.Length > 0 ? validator.Addresses diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs index 75f98431464..d3e13e2c659 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs @@ -51,7 +51,7 @@ public MultiValidator( ILogManager logManager, bool forSealing = false) { - if (validator == null) throw new ArgumentNullException(nameof(validator)); + if (validator is null) throw new ArgumentNullException(nameof(validator)); if (validator.ValidatorType != AuRaParameters.ValidatorType.Multi) throw new ArgumentException("Wrong validator type.", nameof(validator)); _validatorFactory = validatorFactory ?? throw new ArgumentNullException(nameof(validatorFactory)); _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree)); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs index 9fd1ec82561..b971b05d6dc 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs @@ -58,7 +58,7 @@ public PendingValidators Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = public Rlp Encode(PendingValidators item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } @@ -83,7 +83,7 @@ public void Encode(RlpStream rlpStream, PendingValidators item, RlpBehaviors rlp } public int GetLength(PendingValidators item, RlpBehaviors rlpBehaviors) => - item == null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total); + item is null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total); private (int Total, int Addresses) GetContentLength(PendingValidators item, RlpBehaviors rlpBehaviors) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs index dd64b2b6f71..cd5bf152f21 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ReportingContractBasedValidator.cs @@ -176,7 +176,7 @@ private ITxSender SetSender(long blockNumber) public void TryReportSkipped(BlockHeader header, BlockHeader parent) { - if (Validators == null) + if (Validators is null) { return; } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorInfoDecoder.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorInfoDecoder.cs index 52d86999373..f730cff6316 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorInfoDecoder.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorInfoDecoder.cs @@ -50,7 +50,7 @@ internal class ValidatorInfoDecoder : IRlpStreamDecoder, IRlpObje public Rlp Encode(ValidatorInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } @@ -62,7 +62,7 @@ public Rlp Encode(ValidatorInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors. public void Encode(RlpStream stream, ValidatorInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { stream.EncodeNullObject(); return; @@ -79,7 +79,7 @@ public void Encode(RlpStream stream, ValidatorInfo? item, RlpBehaviors rlpBehavi } } - public int GetLength(ValidatorInfo? item, RlpBehaviors rlpBehaviors) => item == null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total); + public int GetLength(ValidatorInfo? item, RlpBehaviors rlpBehaviors) => item is null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total); private static (int Total, int Validators) GetContentLength(ValidatorInfo item, RlpBehaviors rlpBehaviors) { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorStore.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorStore.cs index 3fb875783d6..f6e68f41703 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorStore.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ValidatorStore.cs @@ -60,7 +60,7 @@ public void SetValidators(long finalizingBlockNumber, Address[] validators) public Address[] GetValidators(long? blockNumber = null) { - return blockNumber == null || blockNumber > _latestFinalizedValidatorsBlockNumber ? GetLatestValidatorInfo().Validators : FindValidatorInfo(blockNumber.Value); + return blockNumber is null || blockNumber > _latestFinalizedValidatorsBlockNumber ? GetLatestValidatorInfo().Validators : FindValidatorInfo(blockNumber.Value); } public PendingValidators PendingValidators diff --git a/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs b/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs index dd7151022f1..39122d85ea3 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs @@ -28,7 +28,7 @@ public static bool IsInTurn(this BlockHeader header) internal static Address[] ExtractSigners(BlockHeader blockHeader) { - if (blockHeader.ExtraData == null) + if (blockHeader.ExtraData is null) { throw new Exception(string.Empty); } diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs index d4b929b438e..58afe1ec398 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliqueBlockProducer.cs @@ -132,14 +132,14 @@ private void TimerOnElapsed(object sender, ElapsedEventArgs e) { try { - if (_blockTree.Head == null) + if (_blockTree.Head is null) { _timer.Enabled = true; return; } Block? scheduledBlock = _scheduledBlock; - if (scheduledBlock == null) + if (scheduledBlock is null) { if (_blockTree.Head.Timestamp + _config.BlockPeriod < _timestamper.UnixTime.Seconds) { @@ -321,7 +321,7 @@ public async Task StopAsync() bool IBlockProducer.IsProducingBlocks(ulong? maxProducingInterval) { - if (_producerTask == null || _producerTask.IsCompleted) + if (_producerTask is null || _producerTask.IsCompleted) return false; if (maxProducingInterval != null) return _lastProducedBlock.AddSeconds(maxProducingInterval.Value) > DateTime.UtcNow; @@ -336,7 +336,7 @@ bool IBlockProducer.IsProducingBlocks(ulong? maxProducingInterval) private Block? PrepareBlock(Block parentBlock) { BlockHeader parentHeader = parentBlock.Header; - if (parentHeader.Hash == null) + if (parentHeader.Hash is null) { if (_logger.IsError) _logger.Error( $"Preparing new block on top of {parentHeader.ToString(BlockHeader.Format.Short)} - parent header hash is null"); diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliqueRpcModule.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliqueRpcModule.cs index 66a9f437fac..324bbf0b354 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliqueRpcModule.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliqueRpcModule.cs @@ -41,7 +41,7 @@ public CliqueRpcModule(ICliqueBlockProducer? cliqueBlockProducer, ISnapshotManag public bool ProduceBlock(Keccak parentHash) { - if (_cliqueBlockProducer == null) + if (_cliqueBlockProducer is null) { return false; } @@ -52,7 +52,7 @@ public bool ProduceBlock(Keccak parentHash) public void CastVote(Address signer, bool vote) { - if (_cliqueBlockProducer == null) + if (_cliqueBlockProducer is null) { throw new InvalidOperationException(CannotVoteOnNonValidatorMessage); } @@ -62,7 +62,7 @@ public void CastVote(Address signer, bool vote) public void UncastVote(Address signer) { - if (_cliqueBlockProducer == null) + if (_cliqueBlockProducer is null) { throw new InvalidOperationException(CannotVoteOnNonValidatorMessage); } @@ -164,7 +164,7 @@ public ResultWrapper clique_getSignersAtHashAnnotated(Keccak hash) } BlockHeader? header = _blockTree.FindHeader(hash); - if (header == null) + if (header is null) { return ResultWrapper
.Fail($"Could not find block with hash {hash}"); } diff --git a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs index f7f50a401a3..5eede0da2a0 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs @@ -127,7 +127,7 @@ public Snapshot GetOrCreateSnapshot(long number, Keccak hash) throw new InvalidOperationException($"Unknown ancestor ({hash}) of {previousHeader?.ToString(BlockHeader.Format.Short)}"); } - if (header.Hash == null) throw new InvalidOperationException("Block tree block without hash set"); + if (header.Hash is null) throw new InvalidOperationException("Block tree block without hash set"); Keccak parentHash = header.ParentHash; if (IsEpochTransition(number)) @@ -141,7 +141,7 @@ public Snapshot GetOrCreateSnapshot(long number, Keccak hash) for (int i = 0; i < signersCount; i++) { Address signer = new(header.ExtraData.Slice(Clique.ExtraVanityLength + i * Address.ByteLength, Address.ByteLength)); - signers.Add(signer, signer == epochSigner ? number : parentSnapshot == null ? 0L : parentSnapshot.Signers.ContainsKey(signer) ? parentSnapshot.Signers[signer] : 0L); + signers.Add(signer, signer == epochSigner ? number : parentSnapshot is null ? 0L : parentSnapshot.Signers.ContainsKey(signer) ? parentSnapshot.Signers[signer] : 0L); } snapshot = new Snapshot(number, header.Hash, signers); @@ -246,7 +246,7 @@ private static Keccak GetSnapshotKey(Keccak blockHash) { Keccak key = GetSnapshotKey(hash); byte[]? bytes = _blocksDb.Get(key); - if (bytes == null) return null; + if (bytes is null) return null; return _decoder.Decode(bytes.AsRlpStream()); } diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/EthashSealer.cs b/src/Nethermind/Nethermind.Consensus.Ethash/EthashSealer.cs index 07db9719f04..4b2f5f6a639 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/EthashSealer.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/EthashSealer.cs @@ -67,12 +67,12 @@ public bool CanSeal(long blockNumber, Keccak parentHash) internal async Task MineAsync(CancellationToken cancellationToken, Block processed, ulong? startNonce) { - if (processed.Header.TxRoot == null || - processed.Header.StateRoot == null || - processed.Header.ReceiptsRoot == null || - processed.Header.UnclesHash == null || - processed.Header.Bloom == null || - processed.Header.ExtraData == null) + if (processed.Header.TxRoot is null || + processed.Header.StateRoot is null || + processed.Header.ReceiptsRoot is null || + processed.Header.UnclesHash is null || + processed.Header.Bloom is null || + processed.Header.ExtraData is null) { throw new InvalidOperationException($"Requested to mine an invalid block {processed.Header}"); } diff --git a/src/Nethermind/Nethermind.Consensus/Comparers/TransactionComparerProvider.cs b/src/Nethermind/Nethermind.Consensus/Comparers/TransactionComparerProvider.cs index 20d1ec0e1b9..3fb841baab5 100644 --- a/src/Nethermind/Nethermind.Consensus/Comparers/TransactionComparerProvider.cs +++ b/src/Nethermind/Nethermind.Consensus/Comparers/TransactionComparerProvider.cs @@ -39,7 +39,7 @@ public TransactionComparerProvider(ISpecProvider specProvider, IBlockFinder bloc public IComparer GetDefaultComparer() { - if (_defaultComparer == null) + if (_defaultComparer is null) { IComparer gasPriceComparer = new GasPriceTxComparer(_blockFinder, _specProvider); _defaultComparer = gasPriceComparer diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs index 1df1f3ac192..48ebb4341ae 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockchainProcessor.cs @@ -276,7 +276,7 @@ private void RunProcessingLoop() { try { - if (blockRef.IsInDb || blockRef.Block == null) + if (blockRef.IsInDb || blockRef.Block is null) { BlockRemoved?.Invoke(this, new BlockHashEventArgs(blockRef.BlockHash, ProcessingResult.MissingBlock)); throw new InvalidOperationException("Processing loop expects only resolved blocks"); @@ -357,7 +357,7 @@ private void FireProcessingQueueEmpty() _stopwatch.Restart(); Block[]? processedBlocks = ProcessBranch(processingBranch, options, tracer); - if (processedBlocks == null) + if (processedBlocks is null) { return null; } @@ -405,7 +405,7 @@ private void FireProcessingQueueEmpty() public bool IsProcessingBlocks(ulong? maxProcessingInterval) { - if (_processorTask == null || _recoveryTask == null || _processorTask.IsCompleted || + if (_processorTask is null || _recoveryTask is null || _processorTask.IsCompleted || _recoveryTask.IsCompleted) return false; @@ -559,7 +559,7 @@ private ProcessingBranch PrepareProcessingBranch(Block suggestedBlock, Processin branchingPoint = _blockTree.FindParentHeader(toBeProcessed.Header, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (branchingPoint == null) + if (branchingPoint is null) { // genesis block break; @@ -582,7 +582,7 @@ private ProcessingBranch PrepareProcessingBranch(Block suggestedBlock, Processin toBeProcessed = _blockTree.FindParent(toBeProcessed.Header, BlockTreeLookupOptions.None); if (_logger.IsTrace) _logger.Trace($"Found parent {toBeProcessed?.ToString(Block.Format.Short)}"); bool isFastSyncTransition = headIsGenesis && toBeProcessedIsNotBlockOne; - if (toBeProcessed == null) + if (toBeProcessed is null) { if (_logger.IsDebug) _logger.Debug( @@ -602,7 +602,7 @@ private ProcessingBranch PrepareProcessingBranch(Block suggestedBlock, Processin } // if we have parent state it means that we don't need to go deeper - if (toBeProcessed?.StateRoot == null || _stateReader.HasStateForBlock(toBeProcessed.Header)) + if (toBeProcessed?.StateRoot is null || _stateReader.HasStateForBlock(toBeProcessed.Header)) { if (_logger.IsInfo) _logger.Info($"Found state for parent: {toBeProcessed}, StateRoot: {toBeProcessed?.StateRoot}"); break; @@ -636,7 +636,7 @@ private ProcessingBranch PrepareProcessingBranch(Block suggestedBlock, Processin else { if (_logger.IsTrace) - _logger.Trace(branchingPoint == null + _logger.Trace(branchingPoint is null ? "Setting as genesis block" : $"Adding on top of {branchingPoint.ToString(BlockHeader.Format.Short)}"); } @@ -660,7 +660,7 @@ private bool RunSimpleChecksAheadOfProcessing(Block suggestedBlock, ProcessingOp return false; } - if (suggestedBlock.Header.TotalDifficulty == null) + if (suggestedBlock.Header.TotalDifficulty is null) { if (_logger.IsDebug) _logger.Debug( @@ -677,7 +677,7 @@ private bool RunSimpleChecksAheadOfProcessing(Block suggestedBlock, ProcessingOp for (int i = 0; i < suggestedBlock.Uncles.Length; i++) { - if (suggestedBlock.Uncles[i].Hash == null) + if (suggestedBlock.Uncles[i].Hash is null) { if (_logger.IsDebug) _logger.Debug($"Skipping processing block {suggestedBlock.ToString(Block.Format.FullHashAndNumber)} with null uncle hash ar {i}"); throw new InvalidOperationException($"Uncle's {i} hash is null when processing block"); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs b/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs index 28f0902c950..701e5f21139 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs @@ -26,7 +26,7 @@ public class CompositeBlockPreprocessorStep : IBlockPreprocessorStep public CompositeBlockPreprocessorStep(params IBlockPreprocessorStep[] recoverySteps) { - if (recoverySteps == null) throw new ArgumentNullException(nameof(recoverySteps)); + if (recoverySteps is null) throw new ArgumentNullException(nameof(recoverySteps)); _recoverySteps = new LinkedList(); for (int i = 0; i < recoverySteps.Length; i++) diff --git a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs index abb4b9a2df8..e0bbe2e71f2 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs @@ -58,7 +58,7 @@ public ReadOnlyTxProcessingEnv( ISpecProvider? specProvider, ILogManager? logManager) { - if (specProvider == null) throw new ArgumentNullException(nameof(specProvider)); + if (specProvider is null) throw new ArgumentNullException(nameof(specProvider)); DbProvider = readOnlyDbProvider ?? throw new ArgumentNullException(nameof(readOnlyDbProvider)); _codeDb = readOnlyDbProvider.CodeDb.AsReadOnly(true); diff --git a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs index da5c9f89757..91837d33f17 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/BlockProducerBase.cs @@ -125,7 +125,7 @@ public virtual Task StopAsync() public bool IsProducingBlocks(ulong? maxProducingInterval) { if (Logger.IsTrace) Logger.Trace($"Checking IsProducingBlocks: maxProducingInterval {maxProducingInterval}, _lastProducedBlock {_lastProducedBlockDateTime}, IsRunning() {IsRunning()}"); - return IsRunning() && (maxProducingInterval == null || _lastProducedBlockDateTime.AddSeconds(maxProducingInterval.Value) > DateTime.UtcNow); + return IsRunning() && (maxProducingInterval is null || _lastProducedBlockDateTime.AddSeconds(maxProducingInterval.Value) > DateTime.UtcNow); } private async Task TryProduceAndAnnounceNewBlock(CancellationToken token, BlockHeader? parentHeader, IBlockTracer? blockTracer = null, PayloadAttributes? payloadAttributes = null) @@ -165,7 +165,7 @@ public bool IsProducingBlocks(ulong? maxProducingInterval) protected virtual Task TryProduceNewBlock(CancellationToken token, BlockHeader? parentHeader, IBlockTracer? blockTracer = null, PayloadAttributes? payloadAttributes = null) { - if (parentHeader == null) + if (parentHeader is null) { if (Logger.IsWarn) Logger.Warn("Preparing new block - parent header is null"); } @@ -267,7 +267,7 @@ protected virtual Task SealBlock(Block block, BlockHeader parent, Cancell private bool PreparedBlockCanBeMined(Block? block) { - if (block == null) + if (block is null) { if (Logger.IsError) Logger.Error("Failed to prepare block for mining."); return false; diff --git a/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs b/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs index 2eb9e1b74aa..8edd382c674 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs @@ -24,21 +24,21 @@ public static class BlockProductionTriggerExtensions { public static IBlockProductionTrigger IfPoolIsNotEmpty(this IBlockProductionTrigger? trigger, ITxPool? txPool) { - if (trigger == null) throw new ArgumentNullException(nameof(trigger)); - if (txPool == null) throw new ArgumentNullException(nameof(txPool)); + if (trigger is null) throw new ArgumentNullException(nameof(trigger)); + if (txPool is null) throw new ArgumentNullException(nameof(txPool)); return trigger.ButOnlyWhen(() => txPool.GetPendingTransactionsCount() > 0); } public static IBlockProductionTrigger ButOnlyWhen(this IBlockProductionTrigger? trigger, Func condition) { - if (trigger == null) throw new ArgumentNullException(nameof(trigger)); + if (trigger is null) throw new ArgumentNullException(nameof(trigger)); return new TriggerWithCondition(trigger, condition); } public static IBlockProductionTrigger Or(this IBlockProductionTrigger? trigger, IBlockProductionTrigger? alternative) { - if (trigger == null) throw new ArgumentNullException(nameof(trigger)); - if (alternative == null) throw new ArgumentNullException(nameof(alternative)); + if (trigger is null) throw new ArgumentNullException(nameof(trigger)); + if (alternative is null) throw new ArgumentNullException(nameof(alternative)); if (trigger is CompositeBlockProductionTrigger composite1) { diff --git a/src/Nethermind/Nethermind.Consensus/Tracing/GethStyleTracer.cs b/src/Nethermind/Nethermind.Consensus/Tracing/GethStyleTracer.cs index ed2bec530db..3d1e6a7cf9d 100644 --- a/src/Nethermind/Nethermind.Consensus/Tracing/GethStyleTracer.cs +++ b/src/Nethermind/Nethermind.Consensus/Tracing/GethStyleTracer.cs @@ -53,7 +53,7 @@ public GethStyleTracer( public GethLikeTxTrace Trace(Keccak blockHash, int txIndex, GethTraceOptions options, CancellationToken cancellationToken) { Block block = _blockTree.FindBlock(blockHash, BlockTreeLookupOptions.None); - if (block == null) throw new InvalidOperationException("Only historical blocks"); + if (block is null) throw new InvalidOperationException("Only historical blocks"); if (txIndex > block.Transactions.Length - 1) throw new InvalidOperationException($"Block {blockHash} has only {block.Transactions.Length} transactions and the requested tx index was {txIndex}"); @@ -87,13 +87,13 @@ public GethLikeTxTrace Trace(Keccak blockHash, int txIndex, GethTraceOptions opt public GethLikeTxTrace? Trace(Keccak txHash, GethTraceOptions traceOptions, CancellationToken cancellationToken) { Keccak? blockHash = _receiptStorage.FindBlockHash(txHash); - if (blockHash == null) + if (blockHash is null) { return null; } Block block = _blockTree.FindBlock(blockHash, BlockTreeLookupOptions.RequireCanonical); - if (block == null) + if (block is null) { return null; } @@ -104,7 +104,7 @@ public GethLikeTxTrace Trace(Keccak blockHash, int txIndex, GethTraceOptions opt public GethLikeTxTrace? Trace(long blockNumber, int txIndex, GethTraceOptions options, CancellationToken cancellationToken) { Block block = _blockTree.FindBlock(blockNumber, BlockTreeLookupOptions.RequireCanonical); - if (block == null) throw new InvalidOperationException("Only historical blocks"); + if (block is null) throw new InvalidOperationException("Only historical blocks"); if (txIndex > block.Transactions.Length - 1) throw new InvalidOperationException($"Block {blockNumber} has only {block.Transactions.Length} transactions and the requested tx index was {txIndex}"); @@ -114,8 +114,8 @@ public GethLikeTxTrace Trace(Keccak blockHash, int txIndex, GethTraceOptions opt public GethLikeTxTrace? Trace(long blockNumber, Transaction tx, GethTraceOptions options, CancellationToken cancellationToken) { Block block = _blockTree.FindBlock(blockNumber, BlockTreeLookupOptions.RequireCanonical); - if (block == null) throw new InvalidOperationException("Only historical blocks"); - if (tx.Hash == null) throw new InvalidOperationException("Cannot trace transactions without tx hash set."); + if (block is null) throw new InvalidOperationException("Only historical blocks"); + if (tx.Hash is null) throw new InvalidOperationException("Cannot trace transactions without tx hash set."); block = block.WithReplacedBodyCloned(BlockBody.WithOneTransactionOnly(tx)); GethLikeBlockTracer blockTracer = new(tx.Hash, options); @@ -136,7 +136,7 @@ public GethLikeTxTrace[] TraceBlock(Rlp blockRlp, GethTraceOptions options, Canc private GethLikeTxTrace? Trace(Block block, Keccak? txHash, CancellationToken cancellationToken, GethTraceOptions options) { - if (txHash == null) throw new InvalidOperationException("Cannot trace transactions without tx hash set."); + if (txHash is null) throw new InvalidOperationException("Cannot trace transactions without tx hash set."); GethLikeBlockTracer listener = new(txHash, options); _processor.Process(block, ProcessingOptions.Trace, listener.WithCancellation(cancellationToken)); @@ -145,7 +145,7 @@ public GethLikeTxTrace[] TraceBlock(Rlp blockRlp, GethTraceOptions options, Canc private GethLikeTxTrace[] TraceBlock(Block? block, GethTraceOptions options, CancellationToken cancellationToken, Keccak? txHash = null) { - if (block == null) throw new InvalidOperationException("Only canonical, historical blocks supported"); + if (block is null) throw new InvalidOperationException("Only canonical, historical blocks supported"); if (!block.IsGenesis) { @@ -158,7 +158,7 @@ private GethLikeTxTrace[] TraceBlock(Block? block, GethTraceOptions options, Can if (!_blockTree.IsMainChain(parent.Hash)) throw new InvalidOperationException("Cannot trace orphaned blocks"); } - GethLikeBlockTracer listener = txHash == null ? new GethLikeBlockTracer(options) : new GethLikeBlockTracer(txHash, options); + GethLikeBlockTracer listener = txHash is null ? new GethLikeBlockTracer(options) : new GethLikeBlockTracer(txHash, options); _processor.Process(block, ProcessingOptions.Trace, listener.WithCancellation(cancellationToken)); return listener.BuildResult().ToArray(); } @@ -166,7 +166,7 @@ private GethLikeTxTrace[] TraceBlock(Block? block, GethTraceOptions options, Can private static Block GetBlockToTrace(Rlp blockRlp) { Block block = Rlp.Decode(blockRlp); - if (block.TotalDifficulty == null) + if (block.TotalDifficulty is null) { block.Header.TotalDifficulty = 1; } diff --git a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs index 0a6a05f60c4..0b89de4c7fe 100644 --- a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs +++ b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs @@ -62,8 +62,8 @@ We also want to make it read only so the state is not modified persistently in a public void Accept(ITreeVisitor visitor, Keccak stateRoot) { - if (visitor == null) throw new ArgumentNullException(nameof(visitor)); - if (stateRoot == null) throw new ArgumentNullException(nameof(stateRoot)); + if (visitor is null) throw new ArgumentNullException(nameof(visitor)); + if (stateRoot is null) throw new ArgumentNullException(nameof(stateRoot)); _stateProvider.Accept(visitor, stateRoot); } diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs b/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs index 713a81cf885..8b50b471a2f 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs @@ -31,7 +31,7 @@ public static ITxFilterPipeline CreateStandardFilteringPipeline( ISpecProvider? specProvider, IMiningConfig? miningConfig = null) { - if (specProvider == null) throw new ArgumentNullException(nameof(specProvider)); + if (specProvider is null) throw new ArgumentNullException(nameof(specProvider)); return new TxFilterPipelineBuilder(logManager) .WithMinGasPriceFilter(miningConfig?.MinGasPrice ?? UInt256.Zero, specProvider) diff --git a/src/Nethermind/Nethermind.Consensus/TxFilterAdapter.cs b/src/Nethermind/Nethermind.Consensus/TxFilterAdapter.cs index dc041730e45..e8002f65c80 100644 --- a/src/Nethermind/Nethermind.Consensus/TxFilterAdapter.cs +++ b/src/Nethermind/Nethermind.Consensus/TxFilterAdapter.cs @@ -43,7 +43,7 @@ public AcceptTxResult Accept(Transaction tx, TxHandlingOptions txHandlingOptions if (tx is not GeneratedTransaction) { BlockHeader parentHeader = _blockTree.Head?.Header; - if (parentHeader == null) return AcceptTxResult.Accepted; + if (parentHeader is null) return AcceptTxResult.Accepted; AcceptTxResult isAllowed = _txFilter.IsAllowed(tx, parentHeader); if (!isAllowed) diff --git a/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs index 1eb182d44e4..b3b434849a2 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/HeaderValidator.cs @@ -77,7 +77,7 @@ public virtual bool Validate(BlockHeader header, BlockHeader? parent, bool isUnc IReleaseSpec spec = _specProvider.GetSpec(header.Number); bool extraDataValid = ValidateExtraData(header, parent, spec, isUncle); - if (parent == null) + if (parent is null) { if (header.Number == 0) { @@ -179,7 +179,7 @@ protected virtual bool ValidateExtraData(BlockHeader header, BlockHeader? parent { bool extraDataValid = header.ExtraData.Length <= spec.MaximumExtraDataSize && (isUncle - || _daoBlockNumber == null + || _daoBlockNumber is null || header.Number < _daoBlockNumber || header.Number >= _daoBlockNumber + 10 || Bytes.AreEqual(header.ExtraData, DaoExtraData)); diff --git a/src/Nethermind/Nethermind.Consensus/Validators/UnclesValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/UnclesValidator.cs index e38599ee9c0..a7f9833c020 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/UnclesValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/UnclesValidator.cs @@ -70,7 +70,7 @@ public bool Validate(BlockHeader header, BlockHeader[] uncles) Block ancestor = _blockTree.FindBlock(header.ParentHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded); for (int ancestorLevel = 0; ancestorLevel < 5; ancestorLevel++) { - if (ancestor == null) + if (ancestor is null) { break; } @@ -106,7 +106,7 @@ private bool IsKin(BlockHeader header, BlockHeader uncle, int relationshipLevel) } BlockHeader parent = _blockTree.FindParentHeader(header, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (parent == null) + if (parent is null) { return false; } diff --git a/src/Nethermind/Nethermind.Core.Test/AddressTests.cs b/src/Nethermind/Nethermind.Core.Test/AddressTests.cs index 3d6890f232e..59977c4b73e 100644 --- a/src/Nethermind/Nethermind.Core.Test/AddressTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/AddressTests.cs @@ -100,9 +100,9 @@ public void Equals_operator_works() Assert.True(addressA == addressA); #pragma warning restore CS1718 Assert.False(addressA == addressB); - Assert.False(addressA == null); + Assert.False(addressA is null); Assert.False(null == addressA); - Assert.True((Address?)null == null); + Assert.True((Address?)null is null); } [Test] diff --git a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs index 8b875e0ab77..7467f5d8965 100644 --- a/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs +++ b/src/Nethermind/Nethermind.Core.Test/Builders/BlockBuilder.cs @@ -165,7 +165,7 @@ public BlockBuilder WithParent(BlockHeader blockHeader) { TestObjectInternal.Header.Number = blockHeader?.Number + 1 ?? 0; TestObjectInternal.Header.Timestamp = blockHeader?.Timestamp + 1 ?? 0; - TestObjectInternal.Header.ParentHash = blockHeader == null ? Keccak.Zero : blockHeader.Hash; + TestObjectInternal.Header.ParentHash = blockHeader is null ? Keccak.Zero : blockHeader.Hash; return this; } diff --git a/src/Nethermind/Nethermind.Core.Test/BytesTests.cs b/src/Nethermind/Nethermind.Core.Test/BytesTests.cs index 20b9cef8170..4bca7884aab 100644 --- a/src/Nethermind/Nethermind.Core.Test/BytesTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/BytesTests.cs @@ -39,8 +39,8 @@ public class BytesTests public void Compares_bytes_properly(string? hexString1, string? hexString2, int expectedResult) { IComparer comparer = Bytes.Comparer; - byte[]? x = hexString1 == null ? null : Bytes.FromHexString(hexString1); - byte[]? y = hexString2 == null ? null : Bytes.FromHexString(hexString2); + byte[]? x = hexString1 is null ? null : Bytes.FromHexString(hexString1); + byte[]? y = hexString2 is null ? null : Bytes.FromHexString(hexString2); Assert.AreEqual(expectedResult, comparer.Compare(x, y)); } @@ -84,10 +84,10 @@ public void ToHexString(string input, string expectedResult, bool with0x, bool n [TestCase("0x0102", "0x01", false)] public void Compares_bytes_equality_properly(string? hexString1, string? hexString2, bool expectedResult) { - // interestingly, sequence equals that we have been using for some time returns 0x == null, null == 0x + // interestingly, sequence equals that we have been using for some time returns 0x is null, null == 0x IEqualityComparer comparer = Bytes.EqualityComparer; - byte[]? x = hexString1 == null ? null : Bytes.FromHexString(hexString1); - byte[]? y = hexString2 == null ? null : Bytes.FromHexString(hexString2); + byte[]? x = hexString1 is null ? null : Bytes.FromHexString(hexString1); + byte[]? y = hexString2 is null ? null : Bytes.FromHexString(hexString2); Assert.AreEqual(expectedResult, comparer.Equals(x, y)); } diff --git a/src/Nethermind/Nethermind.Core.Test/Encoding/BlockInfoDecoderTests.cs b/src/Nethermind/Nethermind.Core.Test/Encoding/BlockInfoDecoderTests.cs index 8b7e2f97481..40b380b0973 100644 --- a/src/Nethermind/Nethermind.Core.Test/Encoding/BlockInfoDecoderTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/Encoding/BlockInfoDecoderTests.cs @@ -87,7 +87,7 @@ private static void RoundtripBackwardsCompatible(bool valueDecode, bool chainWit public static Rlp BlockInfoEncodeDeprecated(BlockInfo? item, bool chainWithFinalization) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } diff --git a/src/Nethermind/Nethermind.Core.Test/KeccakTests.cs b/src/Nethermind/Nethermind.Core.Test/KeccakTests.cs index db5f5fcc8c7..6910284c260 100644 --- a/src/Nethermind/Nethermind.Core.Test/KeccakTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/KeccakTests.cs @@ -95,8 +95,8 @@ public void Zero() [TestCase("0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "0x0000000000000000000000000000000000000000000000000000000000000000", 1)] public void Compare(string a, string b, int result) { - Keccak keccakA = a == null ? null : new Keccak(a); - Keccak keccakB = b == null ? null : new Keccak(b); + Keccak keccakA = a is null ? null : new Keccak(a); + Keccak keccakB = b is null ? null : new Keccak(b); Math.Sign(keccakA.CompareTo(keccakB)).Should().Be(result); } diff --git a/src/Nethermind/Nethermind.Core/Authentication/MicrosoftJwtAuthentication.cs b/src/Nethermind/Nethermind.Core/Authentication/MicrosoftJwtAuthentication.cs index e8a483cec2d..401af96a081 100644 --- a/src/Nethermind/Nethermind.Core/Authentication/MicrosoftJwtAuthentication.cs +++ b/src/Nethermind/Nethermind.Core/Authentication/MicrosoftJwtAuthentication.cs @@ -117,7 +117,7 @@ public static MicrosoftJwtAuthentication CreateFromFileOrGenerate(string filePat public bool Authenticate(string? token) { - if (token == null) + if (token is null) { if (_logger.IsWarn) _logger.Warn("Message authentication error: Can't find authentication token"); return false; @@ -184,7 +184,7 @@ private bool LifetimeValidator( SecurityToken securityToken, TokenValidationParameters validationParameters) { - if (expires == null) return true; + if (expires is null) return true; long exp = ((DateTimeOffset)expires).ToUnixTimeSeconds(); return _timestamper.UnixTime.SecondsLong < exp; } diff --git a/src/Nethermind/Nethermind.Core/Block.cs b/src/Nethermind/Nethermind.Core/Block.cs index 5e0034610a6..44e82d7c2d4 100644 --- a/src/Nethermind/Nethermind.Core/Block.cs +++ b/src/Nethermind/Nethermind.Core/Block.cs @@ -114,14 +114,14 @@ public string ToString(Format format) return format switch { Format.Full => ToFullString(), - Format.FullHashAndNumber => Hash == null ? $"{Number} null" : $"{Number} ({Hash})", - Format.HashNumberAndTx => Hash == null + Format.FullHashAndNumber => Hash is null ? $"{Number} null" : $"{Number} ({Hash})", + Format.HashNumberAndTx => Hash is null ? $"{Number} null, tx count: {Body.Transactions.Length}" : $"{Number} {TimestampDate:HH:mm:ss} ({Hash?.ToShortString()}), tx count: {Body.Transactions.Length}", - Format.HashNumberDiffAndTx => Hash == null + Format.HashNumberDiffAndTx => Hash is null ? $"{Number} null, diff: {Difficulty}, tx count: {Body.Transactions.Length}" : $"{Number} ({Hash?.ToShortString()}), diff: {Difficulty}, tx count: {Body.Transactions.Length}", - _ => Hash == null ? $"{Number} null" : $"{Number} ({Hash?.ToShortString()})" + _ => Hash is null ? $"{Number} null" : $"{Number} ({Hash?.ToShortString()})" }; } diff --git a/src/Nethermind/Nethermind.Core/BlockHeader.cs b/src/Nethermind/Nethermind.Core/BlockHeader.cs index 478f06c37f4..4bbbed5e7ee 100644 --- a/src/Nethermind/Nethermind.Core/BlockHeader.cs +++ b/src/Nethermind/Nethermind.Core/BlockHeader.cs @@ -120,9 +120,9 @@ public string ToString(Format format) case Format.Full: return ToString(string.Empty); case Format.FullHashAndNumber: - return Hash == null ? $"{Number} null" : $"{Number} ({Hash})"; + return Hash is null ? $"{Number} null" : $"{Number} ({Hash})"; default: - return Hash == null ? $"{Number} null" : $"{Number} ({Hash.ToShortString()})"; + return Hash is null ? $"{Number} null" : $"{Number} ({Hash.ToShortString()})"; } } diff --git a/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs b/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs index ecc3320ddf7..6debfea027e 100644 --- a/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs +++ b/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs @@ -95,7 +95,7 @@ public bool TryGet(Keccak key, out byte[]? value) [MethodImpl(MethodImplOptions.Synchronized)] public void Set(Keccak key, byte[]? val) { - if (val == null) + if (val is null) { Delete(key); return; diff --git a/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs b/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs index 9c5c676c8d6..321597b0dff 100644 --- a/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs +++ b/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs @@ -71,7 +71,7 @@ public bool Add(T item) public void ExceptWith(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); foreach (T t in other) { @@ -81,7 +81,7 @@ public void ExceptWith(IEnumerable? other) public void IntersectWith(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); T[] ts = new T[Count]; CopyTo(ts, 0); @@ -97,7 +97,7 @@ public void IntersectWith(IEnumerable? other) public bool IsProperSubsetOf(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); int contains = 0; int noContains = 0; @@ -118,7 +118,7 @@ public bool IsProperSubsetOf(IEnumerable? other) public bool IsProperSupersetOf(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); ISet set = other.ToHashSet(); int otherCount = set.Count; @@ -146,7 +146,7 @@ public bool IsProperSupersetOf(IEnumerable? other) public bool IsSubsetOf(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); ISet set = other.ToHashSet(); return this.All(t => set.Contains(t)); @@ -154,21 +154,21 @@ public bool IsSubsetOf(IEnumerable? other) public bool IsSupersetOf(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); return other.All(Contains); } public bool Overlaps(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); return other.Any(Contains); } public bool SetEquals(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); ISet set = other.ToHashSet(); return Count == set.Count && IsSupersetOf(set); @@ -176,7 +176,7 @@ public bool SetEquals(IEnumerable? other) public void SymmetricExceptWith(IEnumerable other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); T[] ts = new T[Count]; CopyTo(ts, 0); @@ -200,7 +200,7 @@ public void SymmetricExceptWith(IEnumerable other) public void UnionWith(IEnumerable? other) { - if (other == null) throw new ArgumentNullException(nameof(other)); + if (other is null) throw new ArgumentNullException(nameof(other)); foreach (T t in other) { diff --git a/src/Nethermind/Nethermind.Core/Eip2930/AccessListBuilder.cs b/src/Nethermind/Nethermind.Core/Eip2930/AccessListBuilder.cs index 4efd5cbe17a..b05eb9c4e8a 100644 --- a/src/Nethermind/Nethermind.Core/Eip2930/AccessListBuilder.cs +++ b/src/Nethermind/Nethermind.Core/Eip2930/AccessListBuilder.cs @@ -59,7 +59,7 @@ public void AddAddress(Address address) public void AddStorage(in UInt256 index) { - if (_currentAddress == null) + if (_currentAddress is null) { throw new InvalidOperationException("No address known when adding index to the access list"); } diff --git a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs index 9dd641e973c..7a9ad378a40 100644 --- a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs +++ b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs @@ -769,7 +769,7 @@ public static byte[] FromHexStringOld(string? hexString) [DebuggerStepThrough] public static byte[] FromHexString(string hexString) { - if (hexString == null) + if (hexString is null) { throw new ArgumentNullException($"{nameof(hexString)}"); } diff --git a/src/Nethermind/Nethermind.Core/Reactive.cs b/src/Nethermind/Nethermind.Core/Reactive.cs index a2cedbe8191..788a34abcbf 100644 --- a/src/Nethermind/Nethermind.Core/Reactive.cs +++ b/src/Nethermind/Nethermind.Core/Reactive.cs @@ -26,7 +26,7 @@ public AnonymousDisposable(Action dispose) /// /// Gets a value that indicates whether the object is disposed. /// - public bool IsDisposed => _dispose == null; + public bool IsDisposed => _dispose is null; /// /// Calls the disposal action if and only if the current instance hasn't been disposed yet. diff --git a/src/Nethermind/Nethermind.Core/Transaction.cs b/src/Nethermind/Nethermind.Core/Transaction.cs index 04ee327a41b..af8e592f103 100644 --- a/src/Nethermind/Nethermind.Core/Transaction.cs +++ b/src/Nethermind/Nethermind.Core/Transaction.cs @@ -50,7 +50,7 @@ public class Transaction public Address? SenderAddress { get; set; } public Signature? Signature { get; set; } public bool IsSigned => Signature != null; - public bool IsContractCreation => To == null; + public bool IsContractCreation => To is null; public bool IsMessageCall => To != null; public Keccak? Hash { get; set; } public PublicKey? DeliveredBy { get; set; } // tks: this is added so we do not send the pending tx back to original sources, not used yet diff --git a/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs b/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs index 12604441c8e..cafd38fc03d 100644 --- a/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs +++ b/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs @@ -93,7 +93,7 @@ public bool Verify(Address sender, Transaction tx) /// public Address? RecoverAddress(Transaction tx, bool useSignatureChainId = false) { - if (tx.Signature == null) + if (tx.Signature is null) { throw new InvalidDataException("Cannot recover sender address from a transaction without a signature."); } diff --git a/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs b/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs index bdd2e36a1ca..1e481a6d188 100644 --- a/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs +++ b/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs @@ -24,7 +24,7 @@ public static class SecureStringExtensions { public static byte[] ToByteArray(this SecureString secureString, System.Text.Encoding encoding = null) { - if (secureString == null) + if (secureString is null) { throw new ArgumentNullException(nameof(secureString)); } @@ -48,7 +48,7 @@ public static byte[] ToByteArray(this SecureString secureString, System.Text.Enc public static string Unsecure(this SecureString secureString) { - if (secureString == null) + if (secureString is null) { throw new ArgumentNullException(nameof(secureString)); } diff --git a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs index 0bd05dd43cc..75ac4e15f64 100644 --- a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs +++ b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs @@ -83,7 +83,7 @@ private RocksDb Init(string basePath, string dbPath, IDbConfig dbConfig, ILogMan static RocksDb Open(string path, (DbOptions Options, ColumnFamilies? Families) db) { (DbOptions options, ColumnFamilies? families) = db; - return families == null ? RocksDb.Open(options, path) : RocksDb.Open(options, path, families); + return families is null ? RocksDb.Open(options, path) : RocksDb.Open(options, path, families); } _fullPath = GetFullDbPath(dbPath, basePath); @@ -291,7 +291,7 @@ public byte[]? this[byte[] key] UpdateWriteMetrics(); - if (value == null) + if (value is null) { _db.Remove(key, null, WriteOptions); } @@ -456,7 +456,7 @@ public byte[]? this[byte[] key] throw new ObjectDisposedException($"Attempted to write a disposed batch {_dbOnTheRocks.Name}"); } - if (value == null) + if (value is null) { _rocksBatch.Delete(key); } diff --git a/src/Nethermind/Nethermind.Db.Rocks/RocksDbExtensions.cs b/src/Nethermind/Nethermind.Db.Rocks/RocksDbExtensions.cs index c4cf3f73c1c..13f52391ee4 100644 --- a/src/Nethermind/Nethermind.Db.Rocks/RocksDbExtensions.cs +++ b/src/Nethermind/Nethermind.Db.Rocks/RocksDbExtensions.cs @@ -43,7 +43,7 @@ internal static unsafe Span GetSpan(this RocksDb db, byte[] key, ColumnFam keyLength = key.Length; var keyLengthPtr = (UIntPtr)keyLength; - var result = cf == null + var result = cf is null ? RocksDbNative.Instance.rocksdb_get(db.Handle, readOptions, key, keyLengthPtr, out var valueLength, out var error) : RocksDbNative.Instance.rocksdb_get_cf(db.Handle, readOptions, cf.Handle, key, keyLengthPtr, out valueLength, out error); diff --git a/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs b/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs index 4e73ba38074..f02621e3301 100644 --- a/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs +++ b/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs @@ -113,7 +113,7 @@ void ValidateCurrentDbStructure(IList sizes) { var levelsFromDb = _bloomInfoDb.Get(LevelsKey); - if (levelsFromDb == null) + if (levelsFromDb is null) { _bloomInfoDb.Set(LevelsKey, Rlp.Encode(sizes.ToArray()).Bytes); } @@ -271,7 +271,7 @@ public void Store(long blockNumber, Bloom bloom) lock (_fileStore) { Bloom? existingBloom = _cache.Get(bucket); - if (existingBloom == null) + if (existingBloom is null) { byte[] bytes = new byte[Bloom.ByteLength]; int bytesRead = _fileStore.Read(bucket, bytes); diff --git a/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs b/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs index 85b7dc210f5..f2eba65bf9e 100644 --- a/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs +++ b/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs @@ -31,7 +31,7 @@ public ReadOnlyDbProvider(IDbProvider? wrappedProvider, bool createInMemoryWrite { _wrappedProvider = wrappedProvider ?? throw new ArgumentNullException(nameof(wrappedProvider)); _createInMemoryWriteStore = createInMemoryWriteStore; - if (wrappedProvider == null) + if (wrappedProvider is null) { throw new ArgumentNullException(nameof(wrappedProvider)); } @@ -74,7 +74,7 @@ public T GetDb(string dbName) where T : class, IDb _registeredDbs.TryGetValue(dbName, out IReadOnlyDb? found); T result = found as T; - if (result == null && found != null) + if (result is null && found != null) { throw new IOException( $"An attempt was made to resolve DB {dbName} as {typeof(T)} while its type is {found.GetType()}."); diff --git a/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs b/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs index ce028a21de0..4a562a411a9 100644 --- a/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs +++ b/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs @@ -45,7 +45,7 @@ public class SimpleFilePublicKeyDb : IFullDb public SimpleFilePublicKeyDb(string name, string dbDirectoryPath, ILogManager logManager) { _logger = logManager.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); - if (dbDirectoryPath == null) throw new ArgumentNullException(nameof(dbDirectoryPath)); + if (dbDirectoryPath is null) throw new ArgumentNullException(nameof(dbDirectoryPath)); Name = name ?? throw new ArgumentNullException(nameof(name)); DbPath = Path.Combine(dbDirectoryPath, DbFileName); Description = $"{Name}|{DbPath}"; @@ -63,7 +63,7 @@ public byte[] this[byte[] key] get => _cache[key]; set { - if (value == null) + if (value is null) { _cache.TryRemove(key, out _); } diff --git a/src/Nethermind/Nethermind.EthStats/Integrations/EthStatsIntegration.cs b/src/Nethermind/Nethermind.EthStats/Integrations/EthStatsIntegration.cs index d6650abd98e..3e05bcabad2 100644 --- a/src/Nethermind/Nethermind.EthStats/Integrations/EthStatsIntegration.cs +++ b/src/Nethermind/Nethermind.EthStats/Integrations/EthStatsIntegration.cs @@ -170,7 +170,7 @@ private void BlockTreeOnNewHeadBlock(object? sender, BlockEventArgs e) return; } - if (block == null) + if (block is null) { _logger.Error($"{nameof(EthStatsIntegration)} received null as the new head block."); return; diff --git a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs index e3e406bae0f..40126355290 100644 --- a/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs +++ b/src/Nethermind/Nethermind.Evm.Test/VirtualMachineTestsBase.cs @@ -217,7 +217,7 @@ protected virtual Block BuildBlock(long blockNumber, SenderRecipientAndMiner sen { senderRecipientAndMiner ??= SenderRecipientAndMiner.Default; return Build.A.Block.WithNumber(blockNumber) - .WithTransactions(tx == null ? new Transaction[0] : new[] { tx }) + .WithTransactions(tx is null ? new Transaction[0] : new[] { tx }) .WithGasLimit(blockGasLimit) .WithBeneficiary(senderRecipientAndMiner.Miner) .WithTimestamp(timestamp) diff --git a/src/Nethermind/Nethermind.Evm/CodeAnalysis/CodeInfo.cs b/src/Nethermind/Nethermind.Evm/CodeAnalysis/CodeInfo.cs index fa8aec92dae..b7d7c6f8322 100644 --- a/src/Nethermind/Nethermind.Evm/CodeAnalysis/CodeInfo.cs +++ b/src/Nethermind/Nethermind.Evm/CodeAnalysis/CodeInfo.cs @@ -48,7 +48,7 @@ public CodeInfo(IPrecompile precompile) public bool ValidateJump(int destination, bool isSubroutine) { - if (_analyzer == null) + if (_analyzer is null) { CreateAnalyzer(); } diff --git a/src/Nethermind/Nethermind.Evm/EvmPooledMemory.cs b/src/Nethermind/Nethermind.Evm/EvmPooledMemory.cs index 80f0a28a69d..898cc8d97fd 100644 --- a/src/Nethermind/Nethermind.Evm/EvmPooledMemory.cs +++ b/src/Nethermind/Nethermind.Evm/EvmPooledMemory.cs @@ -172,7 +172,7 @@ public ReadOnlyMemory Inspect(in UInt256 location, in UInt256 length) return new byte[(long)length]; } - if (_memory == null || location + length > _memory.Length) + if (_memory is null || location + length > _memory.Length) { return ReadOnlyMemory.Empty; } @@ -273,7 +273,7 @@ private void UpdateSize(in UInt256 position, in UInt256 length, bool rentIfNeede if (rentIfNeeded) { - if (_memory == null) + if (_memory is null) { _memory = Pool.Rent((int)Size); Array.Clear(_memory, 0, (int)Size); diff --git a/src/Nethermind/Nethermind.Evm/IEvmMemory.cs b/src/Nethermind/Nethermind.Evm/IEvmMemory.cs index dbeb486e0fa..658b2612abe 100644 --- a/src/Nethermind/Nethermind.Evm/IEvmMemory.cs +++ b/src/Nethermind/Nethermind.Evm/IEvmMemory.cs @@ -58,7 +58,7 @@ public StackableEvmMemory(StackableEvmMemory stackableEvmMemory, ulong offset) public void Dispose() { - if (_parent == null) + if (_parent is null) { _pooled.Dispose(); } diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs b/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs index cad1040b753..0eaf2613d7f 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs @@ -76,7 +76,7 @@ public long BaseGasCost(IReleaseSpec releaseSpec) Signature signature = new(r, s, v); Address recovered = _ecdsa.RecoverAddress(signature, hash); - if (recovered == null) + if (recovered is null) { return (Array.Empty(), true); } diff --git a/src/Nethermind/Nethermind.Evm/Tracing/BlockTracerBase.cs b/src/Nethermind/Nethermind.Evm/Tracing/BlockTracerBase.cs index 63d054c73fb..4f49d5e66e2 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/BlockTracerBase.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/BlockTracerBase.cs @@ -25,7 +25,7 @@ public abstract class BlockTracerBase : IBlockTracer where TTra { private readonly Keccak? _txHash; - private bool IsTracingEntireBlock => _txHash == null; + private bool IsTracingEntireBlock => _txHash is null; protected BlockTracerBase() { diff --git a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs index 9439e6693d2..a6ffe326b23 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/GethLikeTxTracer.cs @@ -78,7 +78,7 @@ public void StartOperation(int depth, long gas, Instruction opcode, int pc, bool } else if (_traceEntry.Depth < (previousTraceEntry?.Depth ?? 0)) { - if (previousTraceEntry == null) + if (previousTraceEntry is null) { throw new InvalidOperationException("Unexpected missing previous trace when leaving a call."); } @@ -87,7 +87,7 @@ public void StartOperation(int depth, long gas, Instruction opcode, int pc, bool } else { - if (previousTraceEntry == null) + if (previousTraceEntry is null) { throw new InvalidOperationException("Unexpected missing previous trace on continuation."); } diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs index ad69f0b6a27..f29a792bbfa 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs @@ -50,7 +50,7 @@ public ParityLikeTxTracer(Block block, Transaction? tx, ParityTraceTypes parityT _trace = new ParityLikeTxTrace { TransactionHash = tx?.Hash, - TransactionPosition = tx == null ? (int?)null : Array.IndexOf(block.Transactions!, tx), + TransactionPosition = tx is null ? (int?)null : Array.IndexOf(block.Transactions!, tx), BlockNumber = block.Number, BlockHash = block.Hash! }; @@ -261,7 +261,7 @@ public void MarkAsFailed(Address recipient, long gasSpent, byte[] output, string _trace.Output = output; // quick tx fail (before execution) - if (_trace.Action == null) + if (_trace.Action is null) { _trace.Action = new ParityTraceAction(); _trace.Action.From = _tx.SenderAddress; diff --git a/src/Nethermind/Nethermind.Evm/Tracing/Proofs/ProofTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/Proofs/ProofTxTracer.cs index 16224518576..b343bb758df 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/Proofs/ProofTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/Proofs/ProofTxTracer.cs @@ -89,7 +89,7 @@ public void ReportAccess(IReadOnlySet
accessedAddresses, IReadOnlySet()) + if (_treatSystemAccountDifferently && Address.SystemUser == address && before is null && after == Array.Empty()) { return; } @@ -109,7 +109,7 @@ public void ReportCodeChange(Address address, byte[]? before, byte[]? after) public void ReportNonceChange(Address address, UInt256? before, UInt256? after) { - if (_treatSystemAccountDifferently && Address.SystemUser == address && before == null && after == UInt256.Zero) + if (_treatSystemAccountDifferently && Address.SystemUser == address && before is null && after == UInt256.Zero) { return; } diff --git a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs index e59c26b52e2..40f9767f344 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionProcessing/TransactionProcessor.cs @@ -325,7 +325,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra PrepareAccountForContractDeployment(contractAddress!, spec); } - if (recipient == null) + if (recipient is null) { // this transaction is not a contract creation so it should have the recipient known and not null throw new InvalidDataException("Recipient has not been resolved properly before tx execution"); @@ -341,7 +341,7 @@ private void Execute(Transaction transaction, BlockHeader block, ITxTracer txTra env.CodeSource = recipient; env.ExecutingAccount = recipient; env.InputData = data ?? Array.Empty(); - env.CodeInfo = machineCode == null + env.CodeInfo = machineCode is null ? _virtualMachine.GetCachedCodeInfo(_worldState, recipient, spec) : new CodeInfo(machineCode); diff --git a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs index c4bfdf8914a..0ef60fc7688 100644 --- a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs +++ b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs @@ -400,11 +400,11 @@ public CodeInfo GetCachedCodeInfo(IWorldState worldState, Address codeSource, IR Keccak codeHash = state.GetCodeHash(codeSource); CodeInfo cachedCodeInfo = _codeCache.Get(codeHash); - if (cachedCodeInfo == null) + if (cachedCodeInfo is null) { byte[] code = state.GetCode(codeHash); - if (code == null) + if (code is null) { throw new NullReferenceException($"Code {codeHash} missing in the state for address {codeSource}"); } @@ -3054,7 +3054,7 @@ public CallResult(byte[] output, bool? precompileSuccess, bool shouldRevert = fa public EvmExceptionType ExceptionType { get; } public bool ShouldRevert { get; } public bool? PrecompileSuccess { get; } // TODO: check this behaviour as it seems it is required and previously that was not the case - public bool IsReturn => StateToExecute == null; + public bool IsReturn => StateToExecute is null; public bool IsException => ExceptionType != EvmExceptionType.None; } } diff --git a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs index 42a4286a9c6..e821fb59c2f 100644 --- a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs +++ b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs @@ -244,7 +244,7 @@ private void CallAndRestore( bool treatBlockHeaderAsParentBlock, ITxTracer tracer) { - if (transaction.SenderAddress == null) + if (transaction.SenderAddress is null) { transaction.SenderAddress = Address.SystemUser; } diff --git a/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs b/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs index e639a220992..94428b10f63 100644 --- a/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs +++ b/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs @@ -57,14 +57,14 @@ public SyncingResult GetFullInfo() if (_syncConfig.FastSync) { if (_syncConfig.DownloadReceiptsInFastSync && - (_receiptStorage.LowestInsertedReceiptBlockNumber == null || _receiptStorage.LowestInsertedReceiptBlockNumber > _syncConfig.AncientReceiptsBarrierCalc)) + (_receiptStorage.LowestInsertedReceiptBlockNumber is null || _receiptStorage.LowestInsertedReceiptBlockNumber > _syncConfig.AncientReceiptsBarrierCalc)) { if (_logger.IsTrace) _logger.Trace($"Receipts not finished - EthSyncingInfo - HighestBlock: {bestSuggestedNumber}, CurrentBlock: {headNumberOrZero}, AncientReceiptsBarrier: {_syncConfig.AncientReceiptsBarrierCalc}. LowestInsertedBodyNumber: {_blockTree.LowestInsertedBodyNumber} LowestInsertedReceiptBlockNumber: {_receiptStorage.LowestInsertedReceiptBlockNumber}"); return ReturnSyncing(headNumberOrZero, bestSuggestedNumber); } if (_syncConfig.DownloadBodiesInFastSync && - (_blockTree.LowestInsertedBodyNumber == null || _blockTree.LowestInsertedBodyNumber > _syncConfig.AncientBodiesBarrierCalc)) + (_blockTree.LowestInsertedBodyNumber is null || _blockTree.LowestInsertedBodyNumber > _syncConfig.AncientBodiesBarrierCalc)) { if (_logger.IsTrace) _logger.Trace($"Bodies not finished - EthSyncingInfo - HighestBlock: {bestSuggestedNumber}, CurrentBlock: {headNumberOrZero}, AncientBodiesBarrier: {_syncConfig.AncientBodiesBarrierCalc}. LowestInsertedBodyNumber: {_blockTree.LowestInsertedBodyNumber} LowestInsertedReceiptBlockNumber: {_receiptStorage.LowestInsertedReceiptBlockNumber}"); return ReturnSyncing(headNumberOrZero, bestSuggestedNumber); diff --git a/src/Nethermind/Nethermind.Facade/Filters/AddressFilter.cs b/src/Nethermind/Nethermind.Facade/Filters/AddressFilter.cs index 2c0351039e8..30e49e99d06 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/AddressFilter.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/AddressFilter.cs @@ -49,7 +49,7 @@ public bool Accepts(Address address) return Addresses.Contains(address); } - return Address == null || Address == address; + return Address is null || Address == address; } public bool Accepts(ref AddressStructRef address) @@ -64,7 +64,7 @@ public bool Accepts(ref AddressStructRef address) return false; } - return Address == null || Address == address; + return Address is null || Address == address; } public bool Matches(Core.Bloom bloom) @@ -85,7 +85,7 @@ public bool Matches(Core.Bloom bloom) return result; } - else if (Address == null) + else if (Address is null) { return true; } @@ -113,7 +113,7 @@ public bool Matches(ref BloomStructRef bloom) return result; } - else if (Address == null) + else if (Address is null) { return true; } diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs index 324e22ca9cf..7239dff90eb 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs @@ -171,7 +171,7 @@ public Keccak[] PollPendingTransactionHashes(int filterId) private void AddReceipts(params TxReceipt[] txReceipts) { - if (txReceipts == null) + if (txReceipts is null) { throw new ArgumentNullException(nameof(txReceipts)); } @@ -193,7 +193,7 @@ private void AddReceipts(params TxReceipt[] txReceipts) private void AddBlock(Block block) { - if (block == null) + if (block is null) { throw new ArgumentNullException(nameof(block)); } @@ -208,7 +208,7 @@ private void AddBlock(Block block) private void StoreBlock(BlockFilter filter, Block block) { - if (block.Hash == null) + if (block.Hash is null) { throw new InvalidOperationException("Cannot filter on blocks without calculated hashes"); } @@ -220,7 +220,7 @@ private void StoreBlock(BlockFilter filter, Block block) private void StoreLogs(LogFilter filter, TxReceipt txReceipt, ref long logIndex) { - if (txReceipt.Logs == null || txReceipt.Logs.Length == 0) + if (txReceipt.Logs is null || txReceipt.Logs.Length == 0) { return; } diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs index 1cb298adbd3..ff5eb853301 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs @@ -111,7 +111,7 @@ private int GetFilterId(bool generateId) private TopicsFilter GetTopicsFilter(IEnumerable? topics = null) { - if (topics == null) + if (topics is null) { return SequenceTopicsFilter.AnyTopic; } @@ -129,7 +129,7 @@ private TopicsFilter GetTopicsFilter(IEnumerable? topics = null) private TopicExpression GetTopicExpression(FilterTopic? filterTopic) { - if (filterTopic == null) + if (filterTopic is null) { return AnyTopic.Instance; } @@ -191,7 +191,7 @@ private static FilterTopic GetTopic(object obj) } var topics = obj as IEnumerable; - if (topics == null) + if (topics is null) { return null; } diff --git a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs index 6f5bbc55e6d..cc40b2f3753 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs @@ -109,7 +109,7 @@ Keccak FindBlockHash(long blockNumber, CancellationToken token) { token.ThrowIfCancellationRequested(); var blockHash = _blockFinder.FindBlockHash(blockNumber); - if (blockHash == null) + if (blockHash is null) { if (_logger.IsError) _logger.Error($"Could not find block {blockNumber} in database. eth_getLogs will return incomplete results."); } @@ -236,7 +236,7 @@ private static IEnumerable FilterLogsInBlockLowMemoryAllocation(LogFi { cancellationToken.ThrowIfCancellationRequested(); - LogEntriesIterator logsIterator = receipt.Logs == null ? new LogEntriesIterator(receipt.LogsRlp) : new LogEntriesIterator(receipt.Logs); + LogEntriesIterator logsIterator = receipt.Logs is null ? new LogEntriesIterator(receipt.LogsRlp) : new LogEntriesIterator(receipt.Logs); if (filter.Matches(ref receipt.Bloom)) { while (logsIterator.TryGetNext(out var log)) @@ -248,7 +248,7 @@ private static IEnumerable FilterLogsInBlockLowMemoryAllocation(LogFi logList ??= new List(); Keccak[] topics = log.Topics; - if (topics == null) + if (topics is null) { var topicsValueDecoderContext = new Rlp.ValueDecoderContext(log.TopicsRlp); topics = KeccakDecoder.Instance.DecodeArray(ref topicsValueDecoderContext); @@ -294,7 +294,7 @@ private IEnumerable FilterLogsInBlockHighMemoryAllocation(LogFilter f else { var block = _blockFinder.FindBlock(blockHash, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - return block == null ? null : _receiptFinder.Get(block); + return block is null ? null : _receiptFinder.Get(block); } } diff --git a/src/Nethermind/Nethermind.Grpc/Nethermind.cs b/src/Nethermind/Nethermind.Grpc/Nethermind.cs index f2fc2917afc..cdf4ef3ff36 100644 --- a/src/Nethermind/Nethermind.Grpc/Nethermind.cs +++ b/src/Nethermind/Nethermind.Grpc/Nethermind.cs @@ -165,7 +165,7 @@ public int CalculateSize() { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(QueryRequest other) { - if (other == null) { + if (other is null) { return; } if (other.Client.Length != 0) { @@ -320,7 +320,7 @@ public int CalculateSize() { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(QueryResponse other) { - if (other == null) { + if (other is null) { return; } if (other.Client.Length != 0) { @@ -471,7 +471,7 @@ public int CalculateSize() { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SubscriptionRequest other) { - if (other == null) { + if (other is null) { return; } if (other.Client.Length != 0) { @@ -626,7 +626,7 @@ public int CalculateSize() { [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(SubscriptionResponse other) { - if (other == null) { + if (other is null) { return; } if (other.Client.Length != 0) { diff --git a/src/Nethermind/Nethermind.Grpc/NethermindGrpc.cs b/src/Nethermind/Nethermind.Grpc/NethermindGrpc.cs index a473f201ea1..30e54f0977e 100644 --- a/src/Nethermind/Nethermind.Grpc/NethermindGrpc.cs +++ b/src/Nethermind/Nethermind.Grpc/NethermindGrpc.cs @@ -122,8 +122,8 @@ protected override NethermindServiceClient NewInstance(ClientBaseConfiguration c /// An object implementing the server-side handling logic. public static void BindService(grpc::ServiceBinderBase serviceBinder, NethermindServiceBase serviceImpl) { - serviceBinder.AddMethod(__Method_Query, serviceImpl == null ? null : new grpc::UnaryServerMethod(serviceImpl.Query)); - serviceBinder.AddMethod(__Method_Subscribe, serviceImpl == null ? null : new grpc::ServerStreamingServerMethod(serviceImpl.Subscribe)); + serviceBinder.AddMethod(__Method_Query, serviceImpl is null ? null : new grpc::UnaryServerMethod(serviceImpl.Query)); + serviceBinder.AddMethod(__Method_Subscribe, serviceImpl is null ? null : new grpc::ServerStreamingServerMethod(serviceImpl.Subscribe)); } } diff --git a/src/Nethermind/Nethermind.Hive/HivePlugin.cs b/src/Nethermind/Nethermind.Hive/HivePlugin.cs index 1ed0e81337d..2ee584a1ceb 100644 --- a/src/Nethermind/Nethermind.Hive/HivePlugin.cs +++ b/src/Nethermind/Nethermind.Hive/HivePlugin.cs @@ -42,12 +42,12 @@ public async Task InitNetworkProtocol() { if (Enabled) { - if (_api.BlockTree == null) throw new ArgumentNullException(nameof(_api.BlockTree)); - if (_api.BlockProcessingQueue == null) throw new ArgumentNullException(nameof(_api.BlockProcessingQueue)); - if (_api.ConfigProvider == null) throw new ArgumentNullException(nameof(_api.ConfigProvider)); - if (_api.LogManager == null) throw new ArgumentNullException(nameof(_api.LogManager)); - if (_api.FileSystem == null) throw new ArgumentNullException(nameof(_api.FileSystem)); - if (_api.BlockValidator == null) throw new ArgumentNullException(nameof(_api.BlockValidator)); + if (_api.BlockTree is null) throw new ArgumentNullException(nameof(_api.BlockTree)); + if (_api.BlockProcessingQueue is null) throw new ArgumentNullException(nameof(_api.BlockProcessingQueue)); + if (_api.ConfigProvider is null) throw new ArgumentNullException(nameof(_api.ConfigProvider)); + if (_api.LogManager is null) throw new ArgumentNullException(nameof(_api.LogManager)); + if (_api.FileSystem is null) throw new ArgumentNullException(nameof(_api.FileSystem)); + if (_api.BlockValidator is null) throw new ArgumentNullException(nameof(_api.BlockValidator)); HiveRunner hiveRunner = new( _api.BlockTree, diff --git a/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs b/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs index e1f6e64f817..f644da96ed3 100644 --- a/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs +++ b/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs @@ -41,7 +41,7 @@ public EthereumStepsManager( INethermindApi context, ILogManager logManager) { - if (loader == null) + if (loader is null) { throw new ArgumentNullException(nameof(loader)); } @@ -127,7 +127,7 @@ private void RunOneRoundOfInitialization(CancellationToken cancellationToken) } IStep? step = CreateStepInstance(stepInfo); - if (step == null) + if (step is null) { if (_logger.IsError) _logger.Error($"Unable to create instance of Ethereum runner step {stepInfo}"); continue; diff --git a/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs b/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs index 1b9eb4f6efa..674223a5a8c 100644 --- a/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs +++ b/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs @@ -34,12 +34,12 @@ public FilterBootnodes(INethermindApi api) public Task Execute(CancellationToken _) { - if (_api.ChainSpec == null) + if (_api.ChainSpec is null) { return Task.CompletedTask; } - if (_api.NodeKey == null) + if (_api.NodeKey is null) { return Task.CompletedTask; } diff --git a/src/Nethermind/Nethermind.Init/Steps/InitRlp.cs b/src/Nethermind/Nethermind.Init/Steps/InitRlp.cs index 85fea21fec4..ea1196591f1 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitRlp.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitRlp.cs @@ -38,7 +38,7 @@ public InitRlp(INethermindApi api) [Todo(Improve.Refactor, "Automatically scan all the references solutions?")] public virtual Task Execute(CancellationToken _) { - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); Assembly? assembly = Assembly.GetAssembly(typeof(NetworkNodeDecoder)); if (assembly is not null) diff --git a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockProducer.cs b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockProducer.cs index 8b885022dd5..21a6cdbc074 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockProducer.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockProducer.cs @@ -58,7 +58,7 @@ protected virtual async Task BuildProducer() _api.Config(), _api.LogManager); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); IConsensusPlugin? consensusPlugin = _api.GetConsensusPlugin(); if (consensusPlugin is not null) diff --git a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs index 5f21e314dbf..9e7c150edef 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitializeBlockchain.cs @@ -78,10 +78,10 @@ private Task InitBlockchain() (IApiWithStores getApi, IApiWithBlockchain setApi) = _api.ForBlockchain; - if (getApi.ChainSpec == null) throw new StepDependencyException(nameof(getApi.ChainSpec)); - if (getApi.DbProvider == null) throw new StepDependencyException(nameof(getApi.DbProvider)); - if (getApi.SpecProvider == null) throw new StepDependencyException(nameof(getApi.SpecProvider)); - if (getApi.BlockTree == null) throw new StepDependencyException(nameof(getApi.BlockTree)); + if (getApi.ChainSpec is null) throw new StepDependencyException(nameof(getApi.ChainSpec)); + if (getApi.DbProvider is null) throw new StepDependencyException(nameof(getApi.DbProvider)); + if (getApi.SpecProvider is null) throw new StepDependencyException(nameof(getApi.SpecProvider)); + if (getApi.BlockTree is null) throw new StepDependencyException(nameof(getApi.BlockTree)); _logger = getApi.LogManager.GetClassLogger(); IInitConfig initConfig = getApi.Config(); @@ -230,7 +230,7 @@ private Task InitBlockchain() getApi.LogManager); InitSealEngine(); - if (_api.SealValidator == null) throw new StepDependencyException(nameof(_api.SealValidator)); + if (_api.SealValidator is null) throw new StepDependencyException(nameof(_api.SealValidator)); setApi.HeaderValidator = CreateHeaderValidator(); @@ -356,9 +356,9 @@ protected virtual TxPool.TxPool CreateTxPool() => // TODO: remove from here - move to consensus? protected virtual BlockProcessor CreateBlockProcessor() { - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); - if (_api.TransactionProcessor == null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.RewardCalculatorSource is null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); + if (_api.TransactionProcessor is null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); return new BlockProcessor( _api.SpecProvider, diff --git a/src/Nethermind/Nethermind.Init/Steps/InitializeNetwork.cs b/src/Nethermind/Nethermind.Init/Steps/InitializeNetwork.cs index f216e2fc519..4abae67230e 100644 --- a/src/Nethermind/Nethermind.Init/Steps/InitializeNetwork.cs +++ b/src/Nethermind/Nethermind.Init/Steps/InitializeNetwork.cs @@ -99,7 +99,7 @@ public async Task Execute(CancellationToken cancellationToken) private async Task Initialize(CancellationToken cancellationToken) { - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); if (_networkConfig.DiagTracerEnabled) { @@ -268,7 +268,7 @@ await StartDiscovery().ContinueWith(initDiscoveryTask => _logger.Error("Unable to start the peer manager.", e); } - if (_api.Enode == null) + if (_api.Enode is null) { throw new InvalidOperationException("Cannot initialize network without knowing own enode"); } @@ -284,7 +284,7 @@ protected virtual MultiSyncModeSelector CreateMultiSyncModeSelector(SyncProgress private Task StartDiscovery() { - if (_api.DiscoveryApp == null) throw new StepDependencyException(nameof(_api.DiscoveryApp)); + if (_api.DiscoveryApp is null) throw new StepDependencyException(nameof(_api.DiscoveryApp)); if (!_api.Config().DiscoveryEnabled) { @@ -300,9 +300,9 @@ private Task StartDiscovery() private void StartPeer() { - if (_api.PeerManager == null) throw new StepDependencyException(nameof(_api.PeerManager)); - if (_api.SessionMonitor == null) throw new StepDependencyException(nameof(_api.SessionMonitor)); - if (_api.PeerPool == null) throw new StepDependencyException(nameof(_api.PeerPool)); + if (_api.PeerManager is null) throw new StepDependencyException(nameof(_api.PeerManager)); + if (_api.SessionMonitor is null) throw new StepDependencyException(nameof(_api.SessionMonitor)); + if (_api.PeerPool is null) throw new StepDependencyException(nameof(_api.PeerPool)); if (!_api.Config().PeerManagerEnabled) { @@ -318,11 +318,11 @@ private void StartPeer() private void InitDiscovery() { - if (_api.NodeStatsManager == null) throw new StepDependencyException(nameof(_api.NodeStatsManager)); - if (_api.Timestamper == null) throw new StepDependencyException(nameof(_api.Timestamper)); - if (_api.NodeKey == null) throw new StepDependencyException(nameof(_api.NodeKey)); - if (_api.CryptoRandom == null) throw new StepDependencyException(nameof(_api.CryptoRandom)); - if (_api.EthereumEcdsa == null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); + if (_api.NodeStatsManager is null) throw new StepDependencyException(nameof(_api.NodeStatsManager)); + if (_api.Timestamper is null) throw new StepDependencyException(nameof(_api.Timestamper)); + if (_api.NodeKey is null) throw new StepDependencyException(nameof(_api.NodeKey)); + if (_api.CryptoRandom is null) throw new StepDependencyException(nameof(_api.CryptoRandom)); + if (_api.EthereumEcdsa is null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); if (!_api.Config().DiscoveryEnabled) { @@ -418,9 +418,9 @@ private NodeRecord PrepareNodeRecord(SameKeyGenerator privateKeyProvider) private Task StartSync() { - if (_api.SyncPeerPool == null) throw new StepDependencyException(nameof(_api.SyncPeerPool)); - if (_api.Synchronizer == null) throw new StepDependencyException(nameof(_api.Synchronizer)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.SyncPeerPool is null) throw new StepDependencyException(nameof(_api.SyncPeerPool)); + if (_api.Synchronizer is null) throw new StepDependencyException(nameof(_api.Synchronizer)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); ISyncConfig syncConfig = _api.Config(); if (syncConfig.NetworkingEnabled) @@ -445,24 +445,24 @@ private Task StartSync() private async Task InitPeer() { - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.ReceiptStorage == null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); - if (_api.BlockValidator == null) throw new StepDependencyException(nameof(_api.BlockValidator)); - if (_api.SyncPeerPool == null) throw new StepDependencyException(nameof(_api.SyncPeerPool)); - if (_api.Synchronizer == null) throw new StepDependencyException(nameof(_api.Synchronizer)); - if (_api.Enode == null) throw new StepDependencyException(nameof(_api.Enode)); - if (_api.NodeKey == null) throw new StepDependencyException(nameof(_api.NodeKey)); - if (_api.MainBlockProcessor == null) throw new StepDependencyException(nameof(_api.MainBlockProcessor)); - if (_api.NodeStatsManager == null) throw new StepDependencyException(nameof(_api.NodeStatsManager)); - if (_api.KeyStore == null) throw new StepDependencyException(nameof(_api.KeyStore)); - if (_api.Wallet == null) throw new StepDependencyException(nameof(_api.Wallet)); - if (_api.EthereumEcdsa == null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); - if (_api.TxPool == null) throw new StepDependencyException(nameof(_api.TxPool)); - if (_api.TxSender == null) throw new StepDependencyException(nameof(_api.TxSender)); - if (_api.EthereumJsonSerializer == null) throw new StepDependencyException(nameof(_api.EthereumJsonSerializer)); - if (_api.DiscoveryApp == null) throw new StepDependencyException(nameof(_api.DiscoveryApp)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.ReceiptStorage is null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); + if (_api.BlockValidator is null) throw new StepDependencyException(nameof(_api.BlockValidator)); + if (_api.SyncPeerPool is null) throw new StepDependencyException(nameof(_api.SyncPeerPool)); + if (_api.Synchronizer is null) throw new StepDependencyException(nameof(_api.Synchronizer)); + if (_api.Enode is null) throw new StepDependencyException(nameof(_api.Enode)); + if (_api.NodeKey is null) throw new StepDependencyException(nameof(_api.NodeKey)); + if (_api.MainBlockProcessor is null) throw new StepDependencyException(nameof(_api.MainBlockProcessor)); + if (_api.NodeStatsManager is null) throw new StepDependencyException(nameof(_api.NodeStatsManager)); + if (_api.KeyStore is null) throw new StepDependencyException(nameof(_api.KeyStore)); + if (_api.Wallet is null) throw new StepDependencyException(nameof(_api.Wallet)); + if (_api.EthereumEcdsa is null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.TxPool is null) throw new StepDependencyException(nameof(_api.TxPool)); + if (_api.TxSender is null) throw new StepDependencyException(nameof(_api.TxSender)); + if (_api.EthereumJsonSerializer is null) throw new StepDependencyException(nameof(_api.EthereumJsonSerializer)); + if (_api.DiscoveryApp is null) throw new StepDependencyException(nameof(_api.DiscoveryApp)); /* rlpx */ EciesCipher eciesCipher = new(_api.CryptoRandom); diff --git a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs index 624f498ad39..5eea65cf496 100644 --- a/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs +++ b/src/Nethermind/Nethermind.Init/Steps/LoadGenesisBlock.cs @@ -44,13 +44,13 @@ public async Task Execute(CancellationToken _) _initConfig = _api.Config(); Keccak? expectedGenesisHash = string.IsNullOrWhiteSpace(_initConfig.GenesisHash) ? null : new Keccak(_initConfig.GenesisHash); - if (_api.BlockTree == null) + if (_api.BlockTree is null) { throw new StepDependencyException(); } // if we already have a database with blocks then we do not need to load genesis from spec - if (_api.BlockTree.Genesis == null) + if (_api.BlockTree.Genesis is null) { Load(); } @@ -66,13 +66,13 @@ public async Task Execute(CancellationToken _) protected virtual void Load() { - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.StateProvider == null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.StorageProvider == null) throw new StepDependencyException(nameof(_api.StorageProvider)); - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.TransactionProcessor == null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); + if (_api.StorageProvider is null) throw new StepDependencyException(nameof(_api.StorageProvider)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.TransactionProcessor is null) throw new StepDependencyException(nameof(_api.TransactionProcessor)); Block genesis = new GenesisLoader( _api.ChainSpec, @@ -87,7 +87,7 @@ protected virtual void Load() bool genesisLoaded = false; void GenesisProcessed(object? sender, BlockEventArgs args) { - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); _api.BlockTree.NewHeadBlock -= GenesisProcessed; genesisLoaded = true; genesisProcessedEvent.Set(); @@ -109,8 +109,8 @@ void GenesisProcessed(object? sender, BlockEventArgs args) /// private void ValidateGenesisHash(Keccak? expectedGenesisHash) { - if (_api.StateProvider == null) throw new StepDependencyException(nameof(_api.StateProvider)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.StateProvider is null) throw new StepDependencyException(nameof(_api.StateProvider)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); BlockHeader genesis = _api.BlockTree.Genesis!; if (expectedGenesisHash != null && genesis.Hash != expectedGenesisHash) diff --git a/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs b/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs index 53baecfe5d4..83a29e347b3 100644 --- a/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs +++ b/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs @@ -58,9 +58,9 @@ public BloomMigration(IApiWithNetwork api) public void Run() { - if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage)); - if (_api.Synchronizer == null) throw new StepDependencyException(nameof(_api.Synchronizer)); - if (_api.SyncModeSelector == null) throw new StepDependencyException(nameof(_api.SyncModeSelector)); + if (_api.BloomStorage is null) throw new StepDependencyException(nameof(_api.BloomStorage)); + if (_api.Synchronizer is null) throw new StepDependencyException(nameof(_api.Synchronizer)); + if (_api.SyncModeSelector is null) throw new StepDependencyException(nameof(_api.SyncModeSelector)); IBloomStorage? storage = _api.BloomStorage; if (storage.NeedsMigration) @@ -93,7 +93,7 @@ private void SynchronizerOnSyncModeChanged(object? sender, SyncModeChangedEventA { if (CanMigrate(e.Current)) { - if (_api.SyncModeSelector == null) throw new StepDependencyException(nameof(_api.SyncModeSelector)); + if (_api.SyncModeSelector is null) throw new StepDependencyException(nameof(_api.SyncModeSelector)); RunBloomMigration(); _api.SyncModeSelector.Changed -= SynchronizerOnSyncModeChanged; @@ -102,8 +102,8 @@ private void SynchronizerOnSyncModeChanged(object? sender, SyncModeChangedEventA private void RunBloomMigration() { - if (_api.DisposeStack == null) throw new StepDependencyException(nameof(_api.DisposeStack)); - if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage)); + if (_api.DisposeStack is null) throw new StepDependencyException(nameof(_api.DisposeStack)); + if (_api.BloomStorage is null) throw new StepDependencyException(nameof(_api.BloomStorage)); if (_api.BloomStorage.NeedsMigration) { @@ -126,8 +126,8 @@ private long MinBlockNumber { get { - if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.BloomStorage is null) throw new StepDependencyException(nameof(_api.BloomStorage)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); return _api.BloomStorage.MinBlockNumber == long.MaxValue ? _api.BlockTree.BestKnownNumber @@ -143,9 +143,9 @@ BlockHeader GetMissingBlockHeader(long i) return EmptyHeader; } - if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage)); - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.ChainLevelInfoRepository == null) throw new StepDependencyException(nameof(_api.ChainLevelInfoRepository)); + if (_api.BloomStorage is null) throw new StepDependencyException(nameof(_api.BloomStorage)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.ChainLevelInfoRepository is null) throw new StepDependencyException(nameof(_api.ChainLevelInfoRepository)); IBlockTree blockTree = _api.BlockTree; IBloomStorage storage = _api.BloomStorage; diff --git a/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptFixMigration.cs b/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptFixMigration.cs index 5a1fcd2d7ac..820443c16f6 100644 --- a/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptFixMigration.cs +++ b/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptFixMigration.cs @@ -132,7 +132,7 @@ await Policy.HandleResult(downloaded => !downloaded) private async Task DownloadReceiptsForBlock(Block block) { - if (block.Hash == null) + if (block.Hash is null) { throw new ArgumentException("Cannot download receipts for a block without a known hash."); } diff --git a/src/Nethermind/Nethermind.Init/Steps/RegisterRpcModules.cs b/src/Nethermind/Nethermind.Init/Steps/RegisterRpcModules.cs index 401c213d78e..29f6e34105e 100644 --- a/src/Nethermind/Nethermind.Init/Steps/RegisterRpcModules.cs +++ b/src/Nethermind/Nethermind.Init/Steps/RegisterRpcModules.cs @@ -60,10 +60,10 @@ public RegisterRpcModules(INethermindApi api) public virtual async Task Execute(CancellationToken cancellationToken) { - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); - if (_api.ReceiptFinder == null) throw new StepDependencyException(nameof(_api.ReceiptFinder)); - if (_api.BloomStorage == null) throw new StepDependencyException(nameof(_api.BloomStorage)); - if (_api.LogManager == null) throw new StepDependencyException(nameof(_api.LogManager)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.ReceiptFinder is null) throw new StepDependencyException(nameof(_api.ReceiptFinder)); + if (_api.BloomStorage is null) throw new StepDependencyException(nameof(_api.BloomStorage)); + if (_api.LogManager is null) throw new StepDependencyException(nameof(_api.LogManager)); IJsonRpcConfig jsonRpcConfig = _api.Config(); if (!jsonRpcConfig.Enabled) @@ -71,13 +71,13 @@ public virtual async Task Execute(CancellationToken cancellationToken) return; } - if (_api.FileSystem == null) throw new StepDependencyException(nameof(_api.FileSystem)); - if (_api.TxPool == null) throw new StepDependencyException(nameof(_api.TxPool)); - if (_api.Wallet == null) throw new StepDependencyException(nameof(_api.Wallet)); - if (_api.SpecProvider == null) throw new StepDependencyException(nameof(_api.SpecProvider)); - if (_api.TxSender == null) throw new StepDependencyException(nameof(_api.TxSender)); - if (_api.StateReader == null) throw new StepDependencyException(nameof(_api.StateReader)); - if (_api.PeerManager == null) throw new StepDependencyException(nameof(_api.PeerManager)); + if (_api.FileSystem is null) throw new StepDependencyException(nameof(_api.FileSystem)); + if (_api.TxPool is null) throw new StepDependencyException(nameof(_api.TxPool)); + if (_api.Wallet is null) throw new StepDependencyException(nameof(_api.Wallet)); + if (_api.SpecProvider is null) throw new StepDependencyException(nameof(_api.SpecProvider)); + if (_api.TxSender is null) throw new StepDependencyException(nameof(_api.TxSender)); + if (_api.StateReader is null) throw new StepDependencyException(nameof(_api.StateReader)); + if (_api.PeerManager is null) throw new StepDependencyException(nameof(_api.PeerManager)); if (jsonRpcConfig.Enabled) { @@ -101,10 +101,10 @@ public virtual async Task Execute(CancellationToken cancellationToken) ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads); ThreadPool.SetMinThreads(workerThreads + Environment.ProcessorCount, completionPortThreads + Environment.ProcessorCount); - if (_api.ReceiptStorage == null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); - if (_api.GasPriceOracle == null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); - if (_api.EthSyncingInfo == null) throw new StepDependencyException(nameof(_api.EthSyncingInfo)); - if (_api.ReadOnlyTrieStore == null) throw new StepDependencyException(nameof(_api.ReadOnlyTrieStore)); + if (_api.ReceiptStorage is null) throw new StepDependencyException(nameof(_api.ReceiptStorage)); + if (_api.GasPriceOracle is null) throw new StepDependencyException(nameof(_api.GasPriceOracle)); + if (_api.EthSyncingInfo is null) throw new StepDependencyException(nameof(_api.EthSyncingInfo)); + if (_api.ReadOnlyTrieStore is null) throw new StepDependencyException(nameof(_api.ReadOnlyTrieStore)); EthModuleFactory ethModuleFactory = new( _api.TxPool, @@ -122,13 +122,13 @@ public virtual async Task Execute(CancellationToken cancellationToken) rpcModuleProvider.RegisterBounded(ethModuleFactory, rpcConfig.EthModuleConcurrentInstances ?? Environment.ProcessorCount, rpcConfig.Timeout); - if (_api.DbProvider == null) throw new StepDependencyException(nameof(_api.DbProvider)); - if (_api.BlockPreprocessor == null) throw new StepDependencyException(nameof(_api.BlockPreprocessor)); - if (_api.BlockValidator == null) throw new StepDependencyException(nameof(_api.BlockValidator)); - if (_api.RewardCalculatorSource == null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); - if (_api.KeyStore == null) throw new StepDependencyException(nameof(_api.KeyStore)); - if (_api.PeerPool == null) throw new StepDependencyException(nameof(_api.PeerPool)); - if (_api.WitnessRepository == null) throw new StepDependencyException(nameof(_api.WitnessRepository)); + if (_api.DbProvider is null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.BlockPreprocessor is null) throw new StepDependencyException(nameof(_api.BlockPreprocessor)); + if (_api.BlockValidator is null) throw new StepDependencyException(nameof(_api.BlockValidator)); + if (_api.RewardCalculatorSource is null) throw new StepDependencyException(nameof(_api.RewardCalculatorSource)); + if (_api.KeyStore is null) throw new StepDependencyException(nameof(_api.KeyStore)); + if (_api.PeerPool is null) throw new StepDependencyException(nameof(_api.PeerPool)); + if (_api.WitnessRepository is null) throw new StepDependencyException(nameof(_api.WitnessRepository)); ProofModuleFactory proofModuleFactory = new(_api.DbProvider, _api.BlockTree, _api.ReadOnlyTrieStore, _api.BlockPreprocessor, _api.ReceiptFinder, _api.SpecProvider, _api.LogManager); rpcModuleProvider.RegisterBounded(proofModuleFactory, 2, rpcConfig.Timeout); @@ -161,8 +161,8 @@ public virtual async Task Execute(CancellationToken cancellationToken) rpcModuleProvider.RegisterBoundedByCpuCount(traceModuleFactory, rpcConfig.Timeout); - if (_api.EthereumEcdsa == null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); - if (_api.Wallet == null) throw new StepDependencyException(nameof(_api.Wallet)); + if (_api.EthereumEcdsa is null) throw new StepDependencyException(nameof(_api.EthereumEcdsa)); + if (_api.Wallet is null) throw new StepDependencyException(nameof(_api.Wallet)); PersonalRpcModule personalRpcModule = new( _api.EthereumEcdsa, @@ -170,9 +170,9 @@ public virtual async Task Execute(CancellationToken cancellationToken) _api.KeyStore); rpcModuleProvider.RegisterSingle(personalRpcModule); - if (_api.PeerManager == null) throw new StepDependencyException(nameof(_api.PeerManager)); - if (_api.StaticNodesManager == null) throw new StepDependencyException(nameof(_api.StaticNodesManager)); - if (_api.Enode == null) throw new StepDependencyException(nameof(_api.Enode)); + if (_api.PeerManager is null) throw new StepDependencyException(nameof(_api.PeerManager)); + if (_api.StaticNodesManager is null) throw new StepDependencyException(nameof(_api.StaticNodesManager)); + if (_api.Enode is null) throw new StepDependencyException(nameof(_api.Enode)); ManualPruningTrigger pruningTrigger = new(); _api.PruningTrigger.Add(pruningTrigger); @@ -186,13 +186,13 @@ public virtual async Task Execute(CancellationToken cancellationToken) pruningTrigger); rpcModuleProvider.RegisterSingle(adminRpcModule); - if (_api.TxPoolInfoProvider == null) throw new StepDependencyException(nameof(_api.TxPoolInfoProvider)); + if (_api.TxPoolInfoProvider is null) throw new StepDependencyException(nameof(_api.TxPoolInfoProvider)); TxPoolRpcModule txPoolRpcModule = new(_api.TxPoolInfoProvider, _api.LogManager); rpcModuleProvider.RegisterSingle(txPoolRpcModule); - if (_api.SyncServer == null) throw new StepDependencyException(nameof(_api.SyncServer)); - if (_api.EngineSignerStore == null) throw new StepDependencyException(nameof(_api.EngineSignerStore)); + if (_api.SyncServer is null) throw new StepDependencyException(nameof(_api.SyncServer)); + if (_api.EngineSignerStore is null) throw new StepDependencyException(nameof(_api.EngineSignerStore)); NetRpcModule netRpcModule = new(_api.LogManager, new NetBridge(_api.Enode, _api.SyncServer)); rpcModuleProvider.RegisterSingle(netRpcModule); @@ -212,7 +212,7 @@ public virtual async Task Execute(CancellationToken cancellationToken) WitnessRpcModule witnessRpcModule = new(_api.WitnessRepository, _api.BlockTree); rpcModuleProvider.RegisterSingle(witnessRpcModule); - if (_api.ReceiptMonitor == null) throw new StepDependencyException(nameof(_api.ReceiptMonitor)); + if (_api.ReceiptMonitor is null) throw new StepDependencyException(nameof(_api.ReceiptMonitor)); JsonRpcLocalStats jsonRpcLocalStats = new( _api.Timestamper, diff --git a/src/Nethermind/Nethermind.Init/Steps/ReviewBlockTree.cs b/src/Nethermind/Nethermind.Init/Steps/ReviewBlockTree.cs index a0ab1c27932..5a9ddbe8060 100644 --- a/src/Nethermind/Nethermind.Init/Steps/ReviewBlockTree.cs +++ b/src/Nethermind/Nethermind.Init/Steps/ReviewBlockTree.cs @@ -37,7 +37,7 @@ public ReviewBlockTree(INethermindApi api) public Task Execute(CancellationToken cancellationToken) { - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.DbProvider)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.DbProvider)); if (_api.Config().ProcessingEnabled) { @@ -57,7 +57,7 @@ private async Task RunBlockTreeInitTasks(CancellationToken cancellationToken) return; } - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); if (!syncConfig.FastSync) { diff --git a/src/Nethermind/Nethermind.Init/Steps/StartBlockProcessor.cs b/src/Nethermind/Nethermind.Init/Steps/StartBlockProcessor.cs index 7e20e4b6fc2..2fa86f91362 100644 --- a/src/Nethermind/Nethermind.Init/Steps/StartBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Init/Steps/StartBlockProcessor.cs @@ -32,7 +32,7 @@ public StartBlockProcessor(INethermindApi api) public Task Execute(CancellationToken _) { - if (_api.BlockchainProcessor == null) + if (_api.BlockchainProcessor is null) { throw new StepDependencyException(nameof(_api.BlockchainProcessor)); } diff --git a/src/Nethermind/Nethermind.Init/Steps/StartBlockProducer.cs b/src/Nethermind/Nethermind.Init/Steps/StartBlockProducer.cs index c29728c4af8..635be831790 100644 --- a/src/Nethermind/Nethermind.Init/Steps/StartBlockProducer.cs +++ b/src/Nethermind/Nethermind.Init/Steps/StartBlockProducer.cs @@ -39,7 +39,7 @@ public async Task Execute(CancellationToken _) { if (_api.BlockProductionPolicy.ShouldStartBlockProduction() && _api.BlockProducer != null) { - if (_api.BlockTree == null) throw new StepDependencyException(nameof(_api.BlockTree)); + if (_api.BlockTree is null) throw new StepDependencyException(nameof(_api.BlockTree)); ILogger logger = _api.LogManager.GetClassLogger(); if (logger.IsWarn) logger.Warn($"Starting {_api.SealEngineType} block producer & sealer"); @@ -64,7 +64,7 @@ protected virtual async Task BuildProducer() _api.Config(), _api.LogManager); - if (_api.ChainSpec == null) throw new StepDependencyException(nameof(_api.ChainSpec)); + if (_api.ChainSpec is null) throw new StepDependencyException(nameof(_api.ChainSpec)); IConsensusPlugin? consensusPlugin = _api.GetConsensusPlugin(); if (consensusPlugin is not null) diff --git a/src/Nethermind/Nethermind.Init/Steps/UpdateDiscoveryConfig.cs b/src/Nethermind/Nethermind.Init/Steps/UpdateDiscoveryConfig.cs index dfa138da6c1..7ef62dfb373 100644 --- a/src/Nethermind/Nethermind.Init/Steps/UpdateDiscoveryConfig.cs +++ b/src/Nethermind/Nethermind.Init/Steps/UpdateDiscoveryConfig.cs @@ -41,7 +41,7 @@ public Task Execute(CancellationToken _) private void Update() { - if (_api.ChainSpec == null) + if (_api.ChainSpec is null) { return; } diff --git a/src/Nethermind/Nethermind.JsonRpc.Test/Data/SerializationTestBase.cs b/src/Nethermind/Nethermind.JsonRpc.Test/Data/SerializationTestBase.cs index 70fb1954654..3f99b30b656 100644 --- a/src/Nethermind/Nethermind.JsonRpc.Test/Data/SerializationTestBase.cs +++ b/src/Nethermind/Nethermind.JsonRpc.Test/Data/SerializationTestBase.cs @@ -37,7 +37,7 @@ protected void TestRoundtrip(T item, Func equalityComparer, JsonC string result = serializer.Serialize(item); T deserialized = serializer.Deserialize(result); - if (equalityComparer == null) + if (equalityComparer is null) { Assert.AreEqual(item, deserialized, description); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Data/BlockParameterConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Data/BlockParameterConverter.cs index dd158320816..e394d7209f2 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Data/BlockParameterConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Data/BlockParameterConverter.cs @@ -123,7 +123,7 @@ public override BlockParameter ReadJson(JsonReader reader, Type objectType, Bloc return parameter; } - if (reader.Value == null) + if (reader.Value is null) { return BlockParameter.Latest; } diff --git a/src/Nethermind/Nethermind.JsonRpc/Data/TransactionForRpc.cs b/src/Nethermind/Nethermind.JsonRpc/Data/TransactionForRpc.cs index 340271ca57f..c07ab75f62a 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Data/TransactionForRpc.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Data/TransactionForRpc.cs @@ -168,16 +168,16 @@ public TransactionForRpc() } private AccessList? TryGetAccessList() => - !Type.IsTxTypeWithAccessList() || AccessList == null + !Type.IsTxTypeWithAccessList() || AccessList is null ? null : AccessListItemForRpc.ToAccessList(AccessList); public void EnsureDefaults(long? gasCap) { - if (gasCap == null || gasCap == 0) + if (gasCap is null || gasCap == 0) gasCap = long.MaxValue; - Gas = Gas == null || Gas == 0 + Gas = Gas is null || Gas == 0 ? gasCap : Math.Min(gasCap.Value, Gas.Value); diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcProcessor.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcProcessor.cs index 5a3dbf67b3c..67a227feffb 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcProcessor.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcProcessor.cs @@ -47,7 +47,7 @@ public class JsonRpcProcessor : IJsonRpcProcessor public JsonRpcProcessor(IJsonRpcService jsonRpcService, IJsonSerializer jsonSerializer, IJsonRpcConfig jsonRpcConfig, IFileSystem fileSystem, ILogManager logManager) { _logger = logManager?.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); - if (fileSystem == null) throw new ArgumentNullException(nameof(fileSystem)); + if (fileSystem is null) throw new ArgumentNullException(nameof(fileSystem)); _jsonRpcService = jsonRpcService ?? throw new ArgumentNullException(nameof(jsonRpcService)); _jsonRpcConfig = jsonRpcConfig ?? throw new ArgumentNullException(nameof(jsonRpcConfig)); @@ -109,10 +109,10 @@ private void BuildTraceJsonSerializer() private void UpdateParams(JToken token) { var paramsToken = token.SelectToken("params"); - if (paramsToken == null) + if (paramsToken is null) { paramsToken = token.SelectToken("Params"); - if (paramsToken == null) + if (paramsToken is null) { return; } @@ -216,7 +216,7 @@ public async IAsyncEnumerable ProcessAsync(TextReader request, Js Metrics.JsonRpcRequests++; JsonRpcResponse response = await _jsonRpcService.SendRequestAsync(jsonRpcRequest, context); JsonRpcErrorResponse localErrorResponse = response as JsonRpcErrorResponse; - bool isSuccess = localErrorResponse == null; + bool isSuccess = localErrorResponse is null; if (!isSuccess) { if (_logger.IsWarn) _logger.Warn($"Error when handling {jsonRpcRequest} | {_jsonSerializer.Serialize(localErrorResponse)}"); @@ -240,7 +240,7 @@ public async IAsyncEnumerable ProcessAsync(TextReader request, Js yield return RecordResponse(JsonRpcResult.Collection(responses, reports)); } - if (rpcRequest.Model == null && rpcRequest.Collection == null) + if (rpcRequest.Model is null && rpcRequest.Collection is null) { Metrics.JsonRpcInvalidRequests++; JsonRpcErrorResponse errorResponse = _jsonRpcService.GetErrorResponse(ErrorCodes.InvalidRequest, "Invalid request"); diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcRequest.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcRequest.cs index 9d72a1cc1ee..9128be1a2ae 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcRequest.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcRequest.cs @@ -32,7 +32,7 @@ public class JsonRpcRequest public override string ToString() { - string paramsString = Params == null ? string.Empty : $"{string.Join(",", Params)}"; + string paramsString = Params is null ? string.Empty : $"{string.Join(",", Params)}"; return $"ID {Id}, {Method}({paramsString})"; } } diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs index 41b7a4059f1..42cb842aa1f 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs @@ -170,7 +170,7 @@ private async Task ExecuteAsync(JsonRpcRequest request, string if (expectedParameters.Length > 0) { parameters = DeserializeParameters(expectedParameters, providedParameters, missingParamsCount); - if (parameters == null) + if (parameters is null) { if (_logger.IsWarn) _logger.Warn($"Incorrect JSON RPC parameters when calling {methodName} with params [{string.Join(", ", providedParameters)}]"); return GetErrorResponse(methodName, ErrorCodes.InvalidParams, "Invalid params", null, request.Id); @@ -233,7 +233,7 @@ private async Task ExecuteAsync(JsonRpcRequest request, string } Result? result = resultWrapper.GetResult(); - if (result == null) + if (result is null) { if (_logger.IsError) _logger.Error($"Error during method: {methodName} execution: no result"); return GetErrorResponse(methodName, resultWrapper.GetErrorCode(), "Internal error", resultWrapper.GetData(), request.Id, returnAction); @@ -307,7 +307,7 @@ private void LogRequest(string methodName, string?[] providedParameters, Paramet if (string.IsNullOrWhiteSpace(providedParameter)) { - if (providedParameter == null && IsNullableParameter(expectedParameter)) + if (providedParameter is null && IsNullableParameter(expectedParameter)) { executionParameters.Add(null); } @@ -420,7 +420,7 @@ private JsonRpcErrorResponse GetErrorResponse(string? methodName, int errorCode, private (int? ErrorType, string ErrorMessage) Validate(JsonRpcRequest? rpcRequest, JsonRpcContext context) { - if (rpcRequest == null) + if (rpcRequest is null) { return (ErrorCodes.InvalidRequest, "Invalid request"); } diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrl.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrl.cs index 227ff30d257..15657f83f76 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrl.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrl.cs @@ -38,7 +38,7 @@ public JsonRpcUrl(string scheme, string host, int port, RpcEndpoint rpcEndpoint, public static JsonRpcUrl Parse(string packedUrlValue) { - if (packedUrlValue == null) + if (packedUrlValue is null) throw new ArgumentNullException(nameof(packedUrlValue)); string[] parts = packedUrlValue.Split('|'); @@ -101,7 +101,7 @@ public bool IsModuleEnabled(string moduleName) => public bool Equals(JsonRpcUrl other) { - if (other == null) + if (other is null) return false; if (ReferenceEquals(this, other)) @@ -118,7 +118,7 @@ public bool Equals(JsonRpcUrl other) public override bool Equals(object other) { - if (other == null) + if (other is null) return false; if (ReferenceEquals(this, other)) diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrlCollection.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrlCollection.cs index 862817110e4..8d2300b8472 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrlCollection.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcUrlCollection.cs @@ -86,7 +86,7 @@ private void BuildUrls(bool includeWebSockets) private void BuildEngineUrls(bool includeWebSockets) { - if (_jsonRpcConfig.EnginePort == null) + if (_jsonRpcConfig.EnginePort is null) { return; } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/AdminRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/AdminRpcModule.cs index 978aafa5b06..80577f3cbe2 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/AdminRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/AdminRpcModule.cs @@ -65,7 +65,7 @@ private void BuildNodeInfo() _nodeInfo.Name = ProductInfo.ClientId; _nodeInfo.Enode = _enode.Info; byte[] publicKeyBytes = _enode.PublicKey?.Bytes; - _nodeInfo.Id = (publicKeyBytes == null ? Keccak.Zero : Keccak.Compute(publicKeyBytes)).ToString(false); + _nodeInfo.Id = (publicKeyBytes is null ? Keccak.Zero : Keccak.Compute(publicKeyBytes)).ToString(false); _nodeInfo.Ip = _enode.HostIp?.ToString(); _nodeInfo.ListenAddress = $"{_enode.HostIp}:{_enode.Port}"; _nodeInfo.Ports.Discovery = _networkConfig.DiscoveryPort; diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/PeerInfo.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/PeerInfo.cs index cf50c113528..94e65165c79 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/PeerInfo.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/PeerInfo.cs @@ -42,14 +42,14 @@ public PeerInfo() public PeerInfo(Peer peer, bool includeDetails) { - if (peer.Node == null) + if (peer.Node is null) { throw new ArgumentException( $"{nameof(PeerInfo)} cannot be created for a {nameof(Peer)} with an unknown {peer.Node}"); } ClientId = peer.Node.ClientId; - Host = peer.Node.Host == null ? null : IPAddress.Parse(peer.Node.Host).MapToIPv4().ToString(); + Host = peer.Node.Host is null ? null : IPAddress.Parse(peer.Node.Host).MapToIPv4().ToString(); Port = peer.Node.Port; Address = peer.Node.Address.ToString(); IsBootnode = peer.Node.IsBootnode; diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/BlockFinderExtensions.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/BlockFinderExtensions.cs index 0f6af287a48..533743fb5d1 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/BlockFinderExtensions.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/BlockFinderExtensions.cs @@ -26,7 +26,7 @@ public static class BlockFinderExtensions { public static SearchResult SearchForHeader(this IBlockFinder blockFinder, BlockParameter? blockParameter, bool allowNulls = false) { - if (blockFinder.Head == null) + if (blockFinder.Head is null) { return new SearchResult("Incorrect head block", ErrorCodes.InternalError); } @@ -37,7 +37,7 @@ public static SearchResult SearchForHeader(this IBlockFinder blockF if (blockParameter.RequireCanonical) { header = blockFinder.FindHeader(blockParameter.BlockHash, BlockTreeLookupOptions.RequireCanonical); - if (header == null && !allowNulls) + if (header is null && !allowNulls) { header = blockFinder.FindHeader(blockParameter.BlockHash); if (header != null) @@ -51,7 +51,7 @@ public static SearchResult SearchForHeader(this IBlockFinder blockF header = blockFinder.FindHeader(blockParameter); } - return header == null && !allowNulls + return header is null && !allowNulls ? new SearchResult($"{blockParameter.BlockHash?.ToString() ?? blockParameter.BlockNumber?.ToString() ?? blockParameter.Type.ToString()} could not be found", ErrorCodes.ResourceNotFound) : new SearchResult(header); } @@ -62,7 +62,7 @@ public static SearchResult SearchForBlock(this IBlockFinder blockFinder, if (blockParameter.RequireCanonical) { block = blockFinder.FindBlock(blockParameter.BlockHash, BlockTreeLookupOptions.RequireCanonical); - if (block == null && !allowNulls) + if (block is null && !allowNulls) { BlockHeader? header = blockFinder.FindHeader(blockParameter.BlockHash); if (header != null) @@ -76,7 +76,7 @@ public static SearchResult SearchForBlock(this IBlockFinder blockFinder, block = blockFinder.FindBlock(blockParameter); } - if (block == null) + if (block is null) { if (blockParameter.Equals(BlockParameter.Finalized) || blockParameter.Equals(BlockParameter.Safe)) { @@ -97,12 +97,12 @@ public static SearchResult SearchForBlock(this IBlockFinder blockFinder, public static IEnumerable> SearchForBlocksOnMainChain(this IBlockFinder blockFinder, BlockParameter fromBlock, BlockParameter toBlock) { SearchResult startingBlock = SearchForBlock(blockFinder, fromBlock); - if (startingBlock.IsError || startingBlock.Object == null) + if (startingBlock.IsError || startingBlock.Object is null) yield return startingBlock; else { SearchResult finalBlockHeader = SearchForHeader(blockFinder, toBlock); - if (finalBlockHeader.IsError || finalBlockHeader.Object == null) + if (finalBlockHeader.IsError || finalBlockHeader.Object is null) yield return new SearchResult(finalBlockHeader.Error ?? string.Empty, finalBlockHeader.ErrorCode); bool isFinalBlockOnMainChain = blockFinder.IsMainChain(finalBlockHeader.Object!); bool isStartingBlockOnMainChain = blockFinder.IsMainChain(startingBlock.Object.Header); diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugBridge.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugBridge.cs index e635246e3f2..2a80901b10a 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugBridge.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugBridge.cs @@ -165,7 +165,7 @@ public byte[] GetBlockRlp(Keccak blockHash) public byte[] GetBlockRlp(long number) { Keccak hash = _blockTree.FindHash(number); - return hash == null ? null : _dbMappings[DbNames.Blocks].Get(hash); + return hash is null ? null : _dbMappings[DbNames.Blocks].Get(hash); } public object GetConfigValue(string category, string name) diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugRpcModule.cs index 007c22c2e62..17aac4eb003 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/DebugRpcModule.cs @@ -49,7 +49,7 @@ public DebugRpcModule(ILogManager logManager, IDebugBridge debugBridge, IJsonRpc public ResultWrapper debug_getChainLevel(in long number) { ChainLevelInfo levelInfo = _debugBridge.GetLevelInfo(number); - return levelInfo == null + return levelInfo is null ? ResultWrapper.Fail($"Chain level {number} does not exist", ErrorCodes.ResourceNotFound) : ResultWrapper.Success(new ChainLevelForRpc(levelInfo)); } @@ -64,7 +64,7 @@ public ResultWrapper debug_traceTransaction(Keccak transactionH using CancellationTokenSource cancellationTokenSource = new(_traceTimeout); CancellationToken cancellationToken = cancellationTokenSource.Token; GethLikeTxTrace transactionTrace = _debugBridge.GetTransactionTrace(transactionHash, cancellationToken, options); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Cannot find transactionTrace for hash: {transactionHash}", ErrorCodes.ResourceNotFound); } @@ -82,7 +82,7 @@ public ResultWrapper debug_traceCall(TransactionForRpc call, Bl CancellationToken cancellationToken = cancellationTokenSource.Token; GethLikeTxTrace transactionTrace = _debugBridge.GetTransactionTrace(tx, blockParameter, cancellationToken, options); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Cannot find transactionTrace for hash: {tx.Hash}", ErrorCodes.ResourceNotFound); } @@ -96,7 +96,7 @@ public ResultWrapper debug_traceTransactionByBlockhashAndIndex( using CancellationTokenSource cancellationTokenSource = new(_traceTimeout); CancellationToken cancellationToken = cancellationTokenSource.Token; var transactionTrace = _debugBridge.GetTransactionTrace(blockhash, index, cancellationToken, options); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Cannot find transactionTrace {blockhash}", ErrorCodes.ResourceNotFound); } @@ -116,7 +116,7 @@ public ResultWrapper debug_traceTransactionByBlockAndIndex(Bloc } var transactionTrace = _debugBridge.GetTransactionTrace(blockNo.Value, index, cancellationToken, options); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Cannot find transactionTrace {blockNo}", ErrorCodes.ResourceNotFound); } @@ -130,7 +130,7 @@ public ResultWrapper debug_traceTransactionInBlockByHash(byte[] using CancellationTokenSource cancellationTokenSource = new(_traceTimeout); CancellationToken cancellationToken = cancellationTokenSource.Token; var transactionTrace = _debugBridge.GetTransactionTrace(new Rlp(blockRlp), transactionHash, cancellationToken, options); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Trace is null for RLP {blockRlp.ToHexString()} and transactionTrace hash {transactionHash}", ErrorCodes.ResourceNotFound); } @@ -144,7 +144,7 @@ public ResultWrapper debug_traceTransactionInBlockByIndex(byte[ CancellationToken cancellationToken = cancellationTokenSource.Token; var blockTrace = _debugBridge.GetBlockTrace(new Rlp(blockRlp), cancellationToken, options); var transactionTrace = blockTrace?.ElementAtOrDefault(txIndex); - if (transactionTrace == null) + if (transactionTrace is null) { return ResultWrapper.Fail($"Trace is null for RLP {blockRlp.ToHexString()} and transaction index {txIndex}", ErrorCodes.ResourceNotFound); } @@ -167,7 +167,7 @@ public ResultWrapper debug_traceBlock(byte[] blockRlp, GethTr var cancellationToken = cancellationTokenSource.Token; var blockTrace = _debugBridge.GetBlockTrace(new Rlp(blockRlp), cancellationToken, options); - if (blockTrace == null) + if (blockTrace is null) return ResultWrapper.Fail($"Trace is null for RLP {blockRlp.ToHexString()}", ErrorCodes.ResourceNotFound); if (_logger.IsTrace) _logger.Trace($"{nameof(debug_traceBlock)} request {blockRlp.ToHexString()}, result: {blockTrace}"); @@ -181,7 +181,7 @@ public ResultWrapper debug_traceBlockByNumber(BlockParameter var cancellationToken = cancellationTokenSource.Token; var blockTrace = _debugBridge.GetBlockTrace(blockNumber, cancellationToken, options); - if (blockTrace == null) + if (blockTrace is null) return ResultWrapper.Fail($"Trace is null for block {blockNumber}", ErrorCodes.ResourceNotFound); if (_logger.IsTrace) _logger.Trace($"{nameof(debug_traceBlockByNumber)} request {blockNumber}, result: {blockTrace}"); @@ -195,7 +195,7 @@ public ResultWrapper debug_traceBlockByHash(Keccak blockHash, var cancellationToken = cancellationTokenSource.Token; var blockTrace = _debugBridge.GetBlockTrace(new BlockParameter(blockHash), cancellationToken, options); - if (blockTrace == null) + if (blockTrace is null) return ResultWrapper.Fail($"Trace is null for block {blockHash}", ErrorCodes.ResourceNotFound); if (_logger.IsTrace) _logger.Trace($"{nameof(debug_traceBlockByHash)} request {blockHash}, result: {blockTrace}"); @@ -221,7 +221,7 @@ public ResultWrapper debug_gcStats() public ResultWrapper debug_getBlockRlp(long blockNumber) { byte[] rlp = _debugBridge.GetBlockRlp(blockNumber); - if (rlp == null) + if (rlp is null) { return ResultWrapper.Fail($"Block {blockNumber} was not found", ErrorCodes.ResourceNotFound); } @@ -232,7 +232,7 @@ public ResultWrapper debug_getBlockRlp(long blockNumber) public ResultWrapper debug_getBlockRlpByHash(Keccak hash) { byte[] rlp = _debugBridge.GetBlockRlp(hash); - if (rlp == null) + if (rlp is null) { return ResultWrapper.Fail($"Block {hash} was not found", ErrorCodes.ResourceNotFound); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/GethLikeTxTraceConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/GethLikeTxTraceConverter.cs index f0055f74322..f69f064e79b 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/GethLikeTxTraceConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/DebugModule/GethLikeTxTraceConverter.cs @@ -26,7 +26,7 @@ public class GethLikeTxTraceConverter : JsonConverter { public override void WriteJson(JsonWriter writer, GethLikeTxTrace value, JsonSerializer serializer) { - if (value == null) + if (value is null) { writer.WriteNull(); return; diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs index ddcae3e67b7..0e017c5540a 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs @@ -201,7 +201,7 @@ public ResultWrapper eth_getStorageAt(Address address, UInt256 positionI BlockHeader? header = searchResult.Object; Account account = _stateReader.GetAccount(header.StateRoot, address); - if (account == null) + if (account is null) { return ResultWrapper.Success(Array.Empty()); } @@ -299,7 +299,7 @@ public ResultWrapper eth_getCode(Address address, BlockParameter? blockP } Account account = _stateReader.GetAccount(header.StateRoot, address); - if (account == null) + if (account is null) { return ResultWrapper.Success(Array.Empty()); } @@ -335,7 +335,7 @@ public ResultWrapper eth_sign(Address addressData, byte[] message) public Task> eth_sendTransaction(TransactionForRpc rpcTx) { Transaction tx = rpcTx.ToTransactionWithDefaults(_blockchainBridge.GetChainId()); - TxHandlingOptions options = rpcTx.Nonce == null ? TxHandlingOptions.ManagedNonce : TxHandlingOptions.None; + TxHandlingOptions options = rpcTx.Nonce is null ? TxHandlingOptions.ManagedNonce : TxHandlingOptions.None; return SendTx(tx, options); } @@ -412,7 +412,7 @@ private ResultWrapper GetBlock(BlockParameter blockParameter, bool _blockchainBridge.RecoverTxSenders(block); } - return ResultWrapper.Success(block == null + return ResultWrapper.Success(block is null ? null : new BlockForRpc(block, returnFullTransactionObjects, _specProvider)); } @@ -422,10 +422,10 @@ public Task> eth_getTransactionByHash(Keccak tr UInt256? baseFee = null; _txPoolBridge.TryGetPendingTransaction(transactionHash, out Transaction transaction); TxReceipt receipt = null; // note that if transaction is pending then for sure no receipt is known - if (transaction == null) + if (transaction is null) { (receipt, transaction, baseFee) = _blockchainBridge.GetTransaction(transactionHash); - if (transaction == null) + if (transaction is null) { return Task.FromResult(ResultWrapper.Success(null)); } @@ -507,7 +507,7 @@ public ResultWrapper eth_getTransactionByBlockNumberAndIndex( public Task> eth_getTransactionReceipt(Keccak txHash) { (TxReceipt receipt, UInt256? effectiveGasPrice, int logIndexStart) = _blockchainBridge.GetReceiptAndEffectiveGasPrice(txHash); - if (receipt == null) + if (receipt is null) { return Task.FromResult(ResultWrapper.Success(null)); } @@ -715,7 +715,7 @@ public ResultWrapper eth_getProof(Address accountAddress, UInt256[ try { header = _blockFinder.FindHeader(blockParameter); - if (header == null) + if (header is null) { return ResultWrapper.Fail($"{blockParameter} block not found", ErrorCodes.ResourceNotFound, null); diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/Filter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/Filter.cs index d9e2f92da74..0d33e139f10 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/Filter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/Filter.cs @@ -50,7 +50,7 @@ public void ReadJson(JsonSerializer serializer, string json) var topics = filter["topics"] as JArray; - Topics = topics == null ? null : GetTopics(filter["topics"] as JArray); + Topics = topics is null ? null : GetTopics(filter["topics"] as JArray); } private static object? GetAddress(JToken? token) => GetSingleOrMany(token); diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/ModuleFactoryBase.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/ModuleFactoryBase.cs index 46ca4ff6ab8..d41bc3342f3 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/ModuleFactoryBase.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/ModuleFactoryBase.cs @@ -31,7 +31,7 @@ public ModuleFactoryBase() } RpcModuleAttribute attribute = typeof(T).GetCustomAttribute(); - if (attribute == null) + if (attribute is null) { throw new InvalidOperationException($"RPC module {typeof(T).Name} is missing {nameof(RpcModuleAttribute)}"); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/ParityRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/ParityRpcModule.cs index b5551454baa..b5ffe4c1382 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/ParityRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/ParityRpcModule.cs @@ -69,7 +69,7 @@ public ParityRpcModule( public ResultWrapper parity_pendingTransactions(Address? address = null) { - IEnumerable enumerable = address == null + IEnumerable enumerable = address is null ? _txPool.GetPendingTransactions() : _txPool.GetPendingTransactionsBySender(address); return ResultWrapper.Success(enumerable diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs index fd6909354a7..1cafd57a078 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs @@ -118,7 +118,7 @@ public ResultWrapper proof_call(TransactionForRpc tx, Block public ResultWrapper proof_getTransactionByHash(Keccak txHash, bool includeHeader) { Keccak blockHash = _receiptFinder.FindBlockHash(txHash); - if (blockHash == null) + if (blockHash is null) { return ResultWrapper.Fail($"{txHash} receipt (transaction) could not be found", ErrorCodes.ResourceNotFound); } @@ -148,7 +148,7 @@ public ResultWrapper proof_getTransactionByHash(Keccak txH public ResultWrapper proof_getTransactionReceipt(Keccak txHash, bool includeHeader) { Keccak blockHash = _receiptFinder.FindBlockHash(txHash); - if (blockHash == null) + if (blockHash is null) { return ResultWrapper.Fail($"{txHash} receipt could not be found", ErrorCodes.ResourceNotFound); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/ReceiptFinderExtensions.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/ReceiptFinderExtensions.cs index 1422668d83f..4728128cc0a 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/ReceiptFinderExtensions.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/ReceiptFinderExtensions.cs @@ -27,7 +27,7 @@ public static class ReceiptFinderExtensions public static SearchResult SearchForReceiptBlockHash(this IReceiptFinder receiptFinder, Keccak txHash) { Keccak blockHash = receiptFinder.FindBlockHash(txHash); - return blockHash == null + return blockHash is null ? new SearchResult($"{txHash} receipt could not be found", ErrorCodes.ResourceNotFound) : new SearchResult(blockHash); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs index cbde7716731..9e78908771d 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs @@ -64,7 +64,7 @@ public RpcModuleProvider(IFileSystem fileSystem, IJsonRpcConfig jsonRpcConfig, I public void Register(IRpcModulePool pool) where T : IRpcModule { RpcModuleAttribute attribute = typeof(T).GetCustomAttribute(); - if (attribute == null) + if (attribute is null) { if (_logger.IsWarn) _logger.Warn( $"Cannot register {typeof(T).Name} as a JSON RPC module because it does not have a {nameof(RpcModuleAttribute)} applied."); diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityAccountStateChangeConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityAccountStateChangeConverter.cs index 1bfbbe531fd..115f99d12a4 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityAccountStateChangeConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityAccountStateChangeConverter.cs @@ -33,13 +33,13 @@ public class ParityAccountStateChangeConverter : JsonConverter change, JsonSerializer serializer) { - if (change == null) + if (change is null) { writer.WriteValue("="); } else { - if (change.Before == null) + if (change.Before is null) { writer.WriteStartObject(); writer.WritePropertyName("+"); @@ -63,13 +63,13 @@ private void WriteChange(JsonWriter writer, ParityStateChange change, Js private void WriteChange(JsonWriter writer, ParityStateChange change, JsonSerializer serializer) { - if (change == null) + if (change is null) { writer.WriteValue("="); } else { - if (change.Before == null) + if (change.Before is null) { writer.WriteStartObject(); writer.WritePropertyName("+"); @@ -93,7 +93,7 @@ private void WriteChange(JsonWriter writer, ParityStateChange change, private void WriteStorageChange(JsonWriter writer, ParityStateChange change, bool isNew, JsonSerializer serializer) { - if (change == null) + if (change is null) { writer.WriteValue("="); } @@ -125,7 +125,7 @@ public override void WriteJson(JsonWriter writer, ParityAccountStateChange value { writer.WriteStartObject(); writer.WritePropertyName("balance"); - if (value.Balance == null) + if (value.Balance is null) { writer.WriteValue("="); } @@ -135,7 +135,7 @@ public override void WriteJson(JsonWriter writer, ParityAccountStateChange value } writer.WritePropertyName("code"); - if (value.Code == null) + if (value.Code is null) { writer.WriteValue("="); } @@ -145,7 +145,7 @@ public override void WriteJson(JsonWriter writer, ParityAccountStateChange value } writer.WritePropertyName("nonce"); - if (value.Nonce == null) + if (value.Nonce is null) { writer.WriteValue("="); } @@ -165,7 +165,7 @@ public override void WriteJson(JsonWriter writer, ParityAccountStateChange value trimmedKey = trimmedKey.Substring(trimmedKey.Length - 64, 64); writer.WritePropertyName(string.Concat("0x", trimmedKey)); - WriteStorageChange(writer, pair.Value, value.Balance?.Before == null && value.Balance?.After != null, serializer); + WriteStorageChange(writer, pair.Value, value.Balance?.Before is null && value.Balance?.After != null, serializer); } } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceAddressConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceAddressConverter.cs index 8dbbc4e4ffb..62afbedc5b3 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceAddressConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceAddressConverter.cs @@ -25,7 +25,7 @@ public class ParityTraceAddressConverter : JsonConverter { public override void WriteJson(JsonWriter writer, int[] value, JsonSerializer serializer) { - if (value == null) + if (value is null) { writer.WriteNull(); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceResultConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceResultConverter.cs index e7a57b8b86d..d7bc51ae9aa 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceResultConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTraceResultConverter.cs @@ -34,7 +34,7 @@ public override void WriteJson(JsonWriter writer, ParityTraceResult value, JsonS writer.WriteProperty("gasUsed", string.Concat("0x", value.GasUsed.ToString("x"))); - if (value.Address == null) + if (value.Address is null) { writer.WriteProperty("output", value.Output, serializer); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTxTraceFromReplayConverter.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTxTraceFromReplayConverter.cs index 5e4e6db64d6..502a8a51d0c 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTxTraceFromReplayConverter.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/ParityTxTraceFromReplayConverter.cs @@ -88,7 +88,7 @@ private void WriteJson(JsonWriter writer, ParityTraceAction traceAction, JsonSer writer.WriteStartObject(); writer.WriteProperty("action", traceAction, serializer); - if (traceAction.Error == null) + if (traceAction.Error is null) { writer.WriteProperty("result", traceAction.Result, serializer); } diff --git a/src/Nethermind/Nethermind.KeyStore/ConsolePasswordProvider.cs b/src/Nethermind/Nethermind.KeyStore/ConsolePasswordProvider.cs index 6ad9572989c..bfb75b669c8 100644 --- a/src/Nethermind/Nethermind.KeyStore/ConsolePasswordProvider.cs +++ b/src/Nethermind/Nethermind.KeyStore/ConsolePasswordProvider.cs @@ -33,7 +33,7 @@ public ConsolePasswordProvider(IConsoleUtils consoleUtils) public override SecureString GetPassword(Address address) { var password = _consoleUtils.ReadSecret(Message); - if (password == null && AlternativeProvider != null) + if (password is null && AlternativeProvider != null) password = AlternativeProvider.GetPassword(address); return password; diff --git a/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs b/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs index 82adbd37da8..a4fa0e37bc0 100644 --- a/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs +++ b/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs @@ -115,12 +115,12 @@ public FileKeyStore( } var serializedKey = ReadKey(address); - if (serializedKey == null) + if (serializedKey is null) { return (null, Result.Fail("Cannot find key")); } var keyStoreItem = _jsonSerializer.Deserialize(serializedKey); - if (keyStoreItem?.Crypto == null) + if (keyStoreItem?.Crypto is null) { return (null, Result.Fail("Cannot deserialize key")); } @@ -178,7 +178,7 @@ public FileKeyStore( } byte[] key = _symmetricEncrypter.Decrypt(cipher, decryptKey, iv, cipherType); - if (key == null) + if (key is null) { return (null, Result.Fail("Error during decryption")); } @@ -262,7 +262,7 @@ public Result StoreKey(Address address, byte[] keyContent, SecureString password var iv = _cryptoRandom.GenerateRandomBytes(_config.IVSize); var cipher = _symmetricEncrypter.Encrypt(encryptContent, encryptKey, iv, _config.Cipher); - if (cipher == null) + if (cipher is null) { return Result.Fail("Error during encryption"); } @@ -322,7 +322,7 @@ public Result StoreKey(PrivateKey key, SecureString password) private Result Validate(KeyStoreItem keyStoreItem) { - if (keyStoreItem.Crypto?.CipherParams == null || keyStoreItem.Crypto.KDFParams == null) + if (keyStoreItem.Crypto?.CipherParams is null || keyStoreItem.Crypto.KDFParams is null) { return Result.Fail("Incorrect key"); } diff --git a/src/Nethermind/Nethermind.KeyStore/FilePasswordProvider.cs b/src/Nethermind/Nethermind.KeyStore/FilePasswordProvider.cs index c376d5eee2f..82d0202341f 100644 --- a/src/Nethermind/Nethermind.KeyStore/FilePasswordProvider.cs +++ b/src/Nethermind/Nethermind.KeyStore/FilePasswordProvider.cs @@ -40,7 +40,7 @@ public override SecureString GetPassword(Address address) password = GetPasswordFromFile(fileName); } - if (password == null && AlternativeProvider != null) + if (password is null && AlternativeProvider != null) password = AlternativeProvider.GetPassword(address); return password; diff --git a/src/Nethermind/Nethermind.KeyStore/KeyStorePasswordProvider.cs b/src/Nethermind/Nethermind.KeyStore/KeyStorePasswordProvider.cs index d2007e1db79..1b85a2ba73c 100644 --- a/src/Nethermind/Nethermind.KeyStore/KeyStorePasswordProvider.cs +++ b/src/Nethermind/Nethermind.KeyStore/KeyStorePasswordProvider.cs @@ -61,7 +61,7 @@ public override SecureString GetPassword(Address address) password ??= GetNthOrLast(keyStoreConfigPasswordIndex, _keyStoreConfig.Passwords)?.Secure(); } - if (password == null && AlternativeProvider != null) + if (password is null && AlternativeProvider != null) { password = AlternativeProvider.GetPassword(address); } diff --git a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs index 10b6bf84cc5..954be528691 100644 --- a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs +++ b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs @@ -37,7 +37,7 @@ internal static class StackTraceUsageUtils private static string GetStackFrameMethodClassName(MethodBase method, bool includeNameSpace, bool cleanAsyncMoveNext, bool cleanAnonymousDelegates) { - if (method == null) + if (method is null) { return null; } @@ -101,11 +101,11 @@ private static string GetClassFullName(StackTrace stackTrace) private static Assembly LookupAssemblyFromStackFrame(StackFrame stackFrame) { MethodBase method = stackFrame.GetMethod(); - if (method == null) + if (method is null) return null; Type declaringType = method.DeclaringType; Assembly assembly1 = (object)declaringType != null ? declaringType.Assembly : null; - if ((object)assembly1 == null) + if ((object)assembly1 is null) { Module module = method.Module; assembly1 = (object)module != null ? module.Assembly : null; diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/BlockTreeTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/BlockTreeTests.cs index 749c4edb2c7..8574492e32f 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/BlockTreeTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/BlockTreeTests.cs @@ -491,7 +491,7 @@ public ScenarioBuilder InsertFork(long low, long high, bool moveToBeaconMainChai Block? parent = null; for (long i = low; i <= high; i++) { - if (parent == null) + if (parent is null) parent = SyncedTree.FindBlock(i - 1, BlockTreeLookupOptions.None)!; Block blockToInsert = Build.A.Block.WithNumber(i).WithParent(parent).WithNonce(0).TestObject; NotSyncedTree.Insert(blockToInsert, BlockTreeInsertBlockOptions.SaveHeader, BlockTreeInsertHeaderOptions.BeaconBlockInsert); @@ -519,7 +519,7 @@ public ScenarioBuilder InsertOtherChainToMain(BlockTree blockTree, long low, lon List newBlocks = new(); for (long i = low; i <= high; i++) { - if (parent == null) + if (parent is null) parent = blockTree.FindBlock(i - 1, BlockTreeLookupOptions.None)!; Block blockToInsert = Build.A.Block.WithNumber(i).WithParent(parent).WithNonce(0).TestObject; blockToInsert.Header.TotalDifficulty = parent.TotalDifficulty + blockToInsert.Difficulty; diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs index acdb1e4a7bc..ee945a038f9 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/EngineModuleTests.HelperFunctions.cs @@ -89,7 +89,7 @@ Transaction BuildTransaction(uint index, Account senderAccount) => private ExecutionPayloadV1 CreateParentBlockRequestOnHead(IBlockTree blockTree) { Block? head = blockTree.Head; - if (head == null) throw new NotSupportedException(); + if (head is null) throw new NotSupportedException(); return new ExecutionPayloadV1() { BlockNumber = head.Number, diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/ExternalRpcIntegrationTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/ExternalRpcIntegrationTests.cs index 1ce95682b0a..0fa89a46e02 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/ExternalRpcIntegrationTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/ExternalRpcIntegrationTests.cs @@ -45,7 +45,7 @@ public async Task CanonicalTreeIsConsistent() JsonRpcClient? client = new($"http://127.0.0.1:8545"); do { - string? requestedBlockNumber = currentBlockNumber == null ? "latest" : currentBlockNumber.Value.ToHexString(false); + string? requestedBlockNumber = currentBlockNumber is null ? "latest" : currentBlockNumber.Value.ToHexString(false); JsonRpcResponse? requestResponse = await client.PostAsync("eth_getBlockByNumber", new object[] { requestedBlockNumber!, false }); BlockForRpcForTest? block = jsonSerializer.Deserialize(requestResponse.Result.ToString()); @@ -70,7 +70,7 @@ public async Task ParentTimestampIsAlwaysLowerThanChildTimestamp() JsonRpcClient? client = new($"http://127.0.0.1:8545"); do { - string? requestedBlockNumber = currentBlockNumber == null ? "latest" : currentBlockNumber.Value.ToHexString(false); + string? requestedBlockNumber = currentBlockNumber is null ? "latest" : currentBlockNumber.Value.ToHexString(false); JsonRpcResponse? requestResponse = await client.PostAsync("eth_getBlockByNumber", new object[] { requestedBlockNumber!, false }); BlockForRpcForTest? block = jsonSerializer.Deserialize(requestResponse.Result.ToString()); diff --git a/src/Nethermind/Nethermind.Merge.Plugin.Test/Synchronization/BeaconHeadersSyncTests.cs b/src/Nethermind/Nethermind.Merge.Plugin.Test/Synchronization/BeaconHeadersSyncTests.cs index 8cab3219da9..43f7c86dedd 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin.Test/Synchronization/BeaconHeadersSyncTests.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin.Test/Synchronization/BeaconHeadersSyncTests.cs @@ -53,7 +53,7 @@ public IBlockTree BlockTree { get { - if (_blockTree == null) + if (_blockTree is null) { IDb blockInfoDb = new MemDb(); Block genesis = Build.A.Block.Genesis.TestObject; @@ -110,7 +110,7 @@ public MultiSyncModeSelector Selector { get { - if (_selector == null) + if (_selector is null) { MemDb stateDb = new(); ProgressTracker progressTracker = new(BlockTree, stateDb, LimboLogs.Instance); @@ -146,7 +146,7 @@ public ISyncReport Report { get { - if (_report == null) + if (_report is null) { _report = Substitute.For(); MeasuredProgress measuredProgress = new MeasuredProgress(); @@ -376,7 +376,7 @@ private void BuildHeadersSyncBatchResponse(HeadersSyncBatch batch, IBlockTree bl { batch.MarkSent(); BlockHeader? startHeader = blockTree.FindHeader(batch.StartNumber); - if (startHeader == null) + if (startHeader is null) { return; } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Data/V1/ExecutionPayloadV1.cs b/src/Nethermind/Nethermind.Merge.Plugin/Data/V1/ExecutionPayloadV1.cs index 16c5de3a5ff..f0fed63ade6 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Data/V1/ExecutionPayloadV1.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Data/V1/ExecutionPayloadV1.cs @@ -117,7 +117,7 @@ public bool TryGetBlock(out Block? block, UInt256? totalDifficulty = null) ///
public byte[][] Transactions { get; set; } = Array.Empty(); - public override string ToString() => BlockHash == null ? $"{BlockNumber} null" : $"{BlockNumber} ({BlockHash})"; + public override string ToString() => BlockHash is null ? $"{BlockNumber} null" : $"{BlockNumber} ({BlockHash})"; public void SetTransactions(params Transaction[] transactions) { diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/ForkchoiceUpdatedV1Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/ForkchoiceUpdatedV1Handler.cs index 66c0440fb3b..52d064351b5 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/ForkchoiceUpdatedV1Handler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/ForkchoiceUpdatedV1Handler.cs @@ -108,7 +108,7 @@ public Task> Handle(ForkchoiceStateV1 f } BlockInfo? blockInfo = _blockTree.GetInfo(newHeadBlock.Number, newHeadBlock.GetOrCalculateHash()).Info; - if (blockInfo == null) + if (blockInfo is null) { if (_logger.IsWarn) { _logger.Warn($"Block info for: {requestStr} wasn't found."); } return ForkchoiceUpdatedV1Result.Syncing; @@ -116,7 +116,7 @@ public Task> Handle(ForkchoiceStateV1 f if (!blockInfo.WasProcessed) { BlockHeader? blockParent = _blockTree.FindHeader(newHeadBlock.ParentHash!); - if (blockParent == null) + if (blockParent is null) { if (_logger.IsInfo) _logger.Info($"Parent of block {newHeadBlock} not available. Starting new beacon header. sync."); @@ -345,7 +345,7 @@ private bool TryGetBranch(Block newHeadBlock, out Block[] blocks) while (true) { predecessor = _blockTree.FindParent(predecessor, BlockTreeLookupOptions.DoNotCreateLevelIfMissing); - if (predecessor == null) + if (predecessor is null) { blocks = Array.Empty(); return false; @@ -377,12 +377,12 @@ private BlockInfo[] GetBeaconChainBranch(Block newHeadBlock, BlockInfo newHeadBl { predecessor = _blockTree.FindParent(predecessor, BlockTreeLookupOptions.TotalDifficultyNotNeeded); - if (predecessor == null) + if (predecessor is null) { break; } BlockInfo? predecessorInfo = _blockTree.GetInfo(predecessor.Number, predecessor.GetOrCalculateHash()).Info; - if (predecessorInfo == null) break; + if (predecessorInfo is null) break; predecessorInfo.BlockNumber = predecessor.Number; if (predecessorInfo.IsBeaconMainChain || !predecessorInfo.IsBeaconInfo) break; if (_logger.IsInfo) _logger.Info($"Reorged to beacon block ({predecessorInfo.BlockNumber}) {predecessorInfo.BlockHash} or cache rebuilt"); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/GetPayloadV1Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/GetPayloadV1Handler.cs index 700dcb79674..ec9c482d8d1 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/GetPayloadV1Handler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/GetPayloadV1Handler.cs @@ -55,7 +55,7 @@ public GetPayloadV1Handler(IPayloadPreparationService payloadPreparationService, string payloadStr = payloadId.ToHexString(true); Block? block = await _payloadPreparationService.GetPayload(payloadStr); - if (block == null) + if (block is null) { // The call MUST return -38001: Unknown payload error if the build process identified by the payloadId does not exist. if (_logger.IsWarn) _logger.Warn($"Block production for payload with id={payloadId.ToHexString()} failed - unknown payload."); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/NewPayloadV1Handler.cs b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/NewPayloadV1Handler.cs index 36de8e0faf6..189711de502 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/NewPayloadV1Handler.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Handlers/V1/NewPayloadV1Handler.cs @@ -435,7 +435,7 @@ private bool TryInsertDanglingBlock(Block block) current = parentBlock; } - if (current == null) + if (current is null) { // block not part of beacon pivot chain, save in cache _blockCacheService.BlockCache.TryAdd(block.Hash!, block); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs index 0bb069e064e..10648cdd5b8 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs @@ -139,10 +139,10 @@ public void OnInvalidBlock(Keccak failedBlock, Keccak? parent) if (_logger.IsDebug) _logger.Debug($"OnInvalidBlock: {failedBlock} {parent}"); // TODO: This port can now be removed? We should never get null here? - if (parent == null) + if (parent is null) { BlockHeader? failedBlockHeader = TryGetBlockHeaderIncludingInvalid(failedBlock); - if (failedBlockHeader == null) + if (failedBlockHeader is null) { if (_logger.IsWarn) _logger.Warn($"Unable to resolve block to determine parent. Block {failedBlock}"); return; diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.BlockProducer.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.BlockProducer.cs index a3c5606f171..57eb260daf4 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.BlockProducer.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.BlockProducer.cs @@ -43,21 +43,21 @@ public async Task InitBlockProducer(IConsensusPlugin consensusPl { if (MergeEnabled) { - if (_api.EngineSigner == null) throw new ArgumentNullException(nameof(_api.EngineSigner)); - if (_api.ChainSpec == null) throw new ArgumentNullException(nameof(_api.ChainSpec)); - if (_api.BlockTree == null) throw new ArgumentNullException(nameof(_api.BlockTree)); - if (_api.BlockProcessingQueue == null) throw new ArgumentNullException(nameof(_api.BlockProcessingQueue)); - if (_api.SpecProvider == null) throw new ArgumentNullException(nameof(_api.SpecProvider)); - if (_api.BlockValidator == null) throw new ArgumentNullException(nameof(_api.BlockValidator)); - if (_api.RewardCalculatorSource == null) throw new ArgumentNullException(nameof(_api.RewardCalculatorSource)); - if (_api.ReceiptStorage == null) throw new ArgumentNullException(nameof(_api.ReceiptStorage)); - if (_api.TxPool == null) throw new ArgumentNullException(nameof(_api.TxPool)); - if (_api.DbProvider == null) throw new ArgumentNullException(nameof(_api.DbProvider)); - if (_api.ReadOnlyTrieStore == null) throw new ArgumentNullException(nameof(_api.ReadOnlyTrieStore)); - if (_api.BlockchainProcessor == null) throw new ArgumentNullException(nameof(_api.BlockchainProcessor)); - if (_api.HeaderValidator == null) throw new ArgumentNullException(nameof(_api.HeaderValidator)); - if (_mergeBlockProductionPolicy == null) throw new ArgumentNullException(nameof(_mergeBlockProductionPolicy)); - if (_api.SealValidator == null) throw new ArgumentNullException(nameof(_api.SealValidator)); + if (_api.EngineSigner is null) throw new ArgumentNullException(nameof(_api.EngineSigner)); + if (_api.ChainSpec is null) throw new ArgumentNullException(nameof(_api.ChainSpec)); + if (_api.BlockTree is null) throw new ArgumentNullException(nameof(_api.BlockTree)); + if (_api.BlockProcessingQueue is null) throw new ArgumentNullException(nameof(_api.BlockProcessingQueue)); + if (_api.SpecProvider is null) throw new ArgumentNullException(nameof(_api.SpecProvider)); + if (_api.BlockValidator is null) throw new ArgumentNullException(nameof(_api.BlockValidator)); + if (_api.RewardCalculatorSource is null) throw new ArgumentNullException(nameof(_api.RewardCalculatorSource)); + if (_api.ReceiptStorage is null) throw new ArgumentNullException(nameof(_api.ReceiptStorage)); + if (_api.TxPool is null) throw new ArgumentNullException(nameof(_api.TxPool)); + if (_api.DbProvider is null) throw new ArgumentNullException(nameof(_api.DbProvider)); + if (_api.ReadOnlyTrieStore is null) throw new ArgumentNullException(nameof(_api.ReadOnlyTrieStore)); + if (_api.BlockchainProcessor is null) throw new ArgumentNullException(nameof(_api.BlockchainProcessor)); + if (_api.HeaderValidator is null) throw new ArgumentNullException(nameof(_api.HeaderValidator)); + if (_mergeBlockProductionPolicy is null) throw new ArgumentNullException(nameof(_mergeBlockProductionPolicy)); + if (_api.SealValidator is null) throw new ArgumentNullException(nameof(_api.SealValidator)); if (_logger.IsInfo) _logger.Info("Starting Merge block producer & sealer"); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs index 8ce1a6d0747..6ffc2713eee 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs @@ -85,11 +85,11 @@ public virtual Task Init(INethermindApi nethermindApi) if (MergeEnabled) { - if (_api.DbProvider == null) throw new ArgumentException(nameof(_api.DbProvider)); - if (_api.BlockTree == null) throw new ArgumentException(nameof(_api.BlockTree)); - if (_api.SpecProvider == null) throw new ArgumentException(nameof(_api.SpecProvider)); - if (_api.ChainSpec == null) throw new ArgumentException(nameof(_api.ChainSpec)); - if (_api.SealValidator == null) throw new ArgumentException(nameof(_api.SealValidator)); + if (_api.DbProvider is null) throw new ArgumentException(nameof(_api.DbProvider)); + if (_api.BlockTree is null) throw new ArgumentException(nameof(_api.BlockTree)); + if (_api.SpecProvider is null) throw new ArgumentException(nameof(_api.SpecProvider)); + if (_api.ChainSpec is null) throw new ArgumentException(nameof(_api.ChainSpec)); + if (_api.SealValidator is null) throw new ArgumentException(nameof(_api.SealValidator)); EnsureJsonRpcUrl(); EnsureReceiptAvailable(); @@ -136,7 +136,7 @@ private void FixTransitionBlock() if (block != null) { ChainLevelInfo? level = _api.ChainLevelInfoRepository!.LoadLevel(block.Number); - if (level == null) + if (level is null) { _logger.Warn("Unable to fix transition block. Unable to find chain level info."); return; @@ -234,9 +234,9 @@ public Task InitNetworkProtocol() if (_api.BlockTree is null) throw new ArgumentNullException(nameof(_api.BlockTree)); if (_api.SpecProvider is null) throw new ArgumentNullException(nameof(_api.SpecProvider)); if (_api.UnclesValidator is null) throw new ArgumentNullException(nameof(_api.UnclesValidator)); - if (_api.BlockProductionPolicy == null) throw new ArgumentException(nameof(_api.BlockProductionPolicy)); - if (_api.SealValidator == null) throw new ArgumentException(nameof(_api.SealValidator)); - if (_api.HeaderValidator == null) throw new ArgumentException(nameof(_api.HeaderValidator)); + if (_api.BlockProductionPolicy is null) throw new ArgumentException(nameof(_api.BlockProductionPolicy)); + if (_api.SealValidator is null) throw new ArgumentException(nameof(_api.SealValidator)); + if (_api.HeaderValidator is null) throw new ArgumentException(nameof(_api.HeaderValidator)); MergeHeaderValidator headerValidator = new( _poSSwitcher, diff --git a/src/Nethermind/Nethermind.Merge.Plugin/PoSSwitcher.cs b/src/Nethermind/Nethermind.Merge.Plugin/PoSSwitcher.cs index f6b99d03502..6dd7c4c66ec 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/PoSSwitcher.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/PoSSwitcher.cs @@ -93,7 +93,7 @@ private void Initialize() if (_terminalBlockNumber != null || _finalTotalDifficulty != null) _hasEverReachedTerminalDifficulty = true; - if (_terminalBlockNumber == null) + if (_terminalBlockNumber is null) _blockTree.NewHeadBlock += CheckIfTerminalBlockReached; if (_logger.IsInfo) @@ -177,7 +177,7 @@ public void ForkchoiceUpdated(BlockHeader newHeadHash, Keccak finalizedHash) $"GetBlockConsensusInfo {header.ToString(BlockHeader.Format.FullHashAndNumber)} header.IsPostMerge: {header.IsPostMerge} header.TotalDifficulty {header.TotalDifficulty} header.Difficulty {header.Difficulty} TTD: {_specProvider.TerminalTotalDifficulty} MergeBlockNumber {_specProvider.MergeBlockNumber}, TransitionFinished: {TransitionFinished}"); bool isTerminal = false, isPostMerge; - if (_specProvider.TerminalTotalDifficulty == null) // TTD = null, so everything is preMerge + if (_specProvider.TerminalTotalDifficulty is null) // TTD = null, so everything is preMerge { isTerminal = false; isPostMerge = false; @@ -193,7 +193,7 @@ public void ForkchoiceUpdated(BlockHeader newHeadHash, Keccak finalizedHash) isTerminal = false; isPostMerge = true; } - else if (header.TotalDifficulty == null || (header.TotalDifficulty == 0 && header.IsGenesis == false)) // we don't know header TD, so we consider header.Difficulty + else if (header.TotalDifficulty is null || (header.TotalDifficulty == 0 && header.IsGenesis == false)) // we don't know header TD, so we consider header.Difficulty { isPostMerge = header.Difficulty == 0; isTerminal = false; // we can't say if block isTerminal if we don't have TD diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/BeaconSync.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/BeaconSync.cs index 819f82aad73..6446c2c7aa2 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/BeaconSync.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/BeaconSync.cs @@ -93,7 +93,7 @@ public bool IsBeaconSyncHeadersFinished() ((lowestInsertedBeaconHeader?.Number ?? 0) - 1) <= (_blockTree.BestSuggestedHeader?.Number ?? long.MaxValue) && lowestInsertedBeaconHeader != null && _blockTree.IsKnownBlock(lowestInsertedBeaconHeader.Number - 1, lowestInsertedBeaconHeader.ParentHash!); - bool finished = lowestInsertedBeaconHeader == null + bool finished = lowestInsertedBeaconHeader is null || lowestInsertedBeaconHeader.Number <= _beaconPivot.PivotDestinationNumber || (!_syncConfig.StrictMode && chainMerged); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs index 9f064a040c0..158ca7b4ce8 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/ChainLevelHelper.cs @@ -66,7 +66,7 @@ private void OnMissingBeaconHeader(long blockNumber) public BlockHeader[]? GetNextHeaders(int maxCount, long maxHeaderNumber, int skipLastBlockCount = 0) { long? startingPoint = GetStartingPoint(); - if (startingPoint == null) + if (startingPoint is null) { if (_logger.IsTrace) _logger.Trace($"ChainLevelHelper.GetNextHeaders - starting point is null"); @@ -83,7 +83,7 @@ private void OnMissingBeaconHeader(long blockNumber) { ChainLevelInfo? level = _blockTree.FindLevel(startingPoint!.Value); BlockInfo? beaconMainChainBlock = level?.BeaconMainChainBlock; - if (level == null || beaconMainChainBlock == null) + if (level is null || beaconMainChainBlock is null) { OnMissingBeaconHeader(startingPoint.Value); if (_logger.IsTrace) @@ -94,7 +94,7 @@ private void OnMissingBeaconHeader(long blockNumber) BlockHeader? newHeader = _blockTree.FindHeader(beaconMainChainBlock.BlockHash, BlockTreeLookupOptions.None); - if (newHeader == null) + if (newHeader is null) { OnMissingBeaconHeader(startingPoint.Value); if (_logger.IsTrace) _logger.Trace($"ChainLevelHelper - header {startingPoint} not found"); @@ -170,7 +170,7 @@ public bool TrySetNextBlocks(int maxCount, BlockDownloadContext context) for (int i = 0; i < hashesToRequest.Count; i++) { Block? block = _blockTree.FindBlock(hashesToRequest[i], BlockTreeLookupOptions.None); - if (block == null) return false; + if (block is null) return false; BlockBody blockBody = new(block.Transactions, block.Uncles); context.SetBody(i + offset, blockBody); } @@ -193,7 +193,7 @@ public bool TrySetNextBlocks(int maxCount, BlockDownloadContext context) if (_logger.IsTrace) _logger.Trace($"ChainLevelHelper. starting point's starting point is {startingPoint}. Best known number: {_blockTree.BestKnownNumber}, Process destination: {_beaconPivot.ProcessDestination?.Number}"); BlockInfo? beaconMainChainBlock = GetBeaconMainChainBlockInfo(startingPoint); - if (beaconMainChainBlock == null) + if (beaconMainChainBlock is null) { OnMissingBeaconHeader(startingPoint); return null; @@ -209,14 +209,14 @@ public bool TrySetNextBlocks(int maxCount, BlockDownloadContext context) do { BlockHeader? header = _blockTree.FindHeader(currentHash!, BlockTreeLookupOptions.None); - if (header == null) + if (header is null) { if (_logger.IsTrace) _logger.Trace($"Header for number {startingPoint} was not found"); return null; } BlockInfo? parentBlockInfo = (_blockTree.GetInfo(header.Number - 1, header.ParentHash!)).Info; - if (parentBlockInfo == null) + if (parentBlockInfo is null) { OnMissingBeaconHeader(header.Number); return null; @@ -245,7 +245,7 @@ public bool TrySetNextBlocks(int maxCount, BlockDownloadContext context) { ChainLevelInfo? startingLevel = _blockTree.FindLevel(startingPoint); BlockInfo? beaconMainChainBlock = startingLevel?.BeaconMainChainBlock; - if (beaconMainChainBlock == null) + if (beaconMainChainBlock is null) { if (_logger.IsTrace) _logger.Trace($"Beacon main chain block for number {startingPoint} was not found"); return null; diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlockDownloader.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlockDownloader.cs index 31ea5e29c25..14d323b42d3 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlockDownloader.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlockDownloader.cs @@ -96,7 +96,7 @@ public override async Task DownloadBlocks(PeerInfo? bestPeer, BlocksReques return await base.DownloadBlocks(bestPeer, blocksRequest, cancellation); } - if (bestPeer == null) + if (bestPeer is null) { string message = $"Not expecting best peer to be null inside the {nameof(BlockDownloader)}"; if (_logger.IsError) _logger.Error(message); @@ -125,7 +125,7 @@ bool HasMoreToSync(out BlockHeader[]? headers, out int headersToRequest) $"Full sync request {currentNumber}+{headersToRequest} to peer {bestPeer} with {bestPeer.HeadNumber} blocks. Got {currentNumber} and asking for {headersToRequest} more."); headers = _chainLevelHelper.GetNextHeaders(headersToRequest, bestPeer.HeadNumber, blocksRequest.NumberOfLatestBlocksToBeIgnored ?? 0); - if (headers == null || headers.Length <= 1) + if (headers is null || headers.Length <= 1) { if (_logger.IsTrace) _logger.Trace("Chain level helper got no headers suggestion"); @@ -224,7 +224,7 @@ bool HasMoreToSync(out BlockHeader[]? headers, out int headersToRequest) if (downloadReceipts) { TxReceipt[]? contextReceiptsForBlock = receipts![blockIndex]; - if (currentBlock.Header.HasBody && contextReceiptsForBlock == null) + if (currentBlock.Header.HasBody && contextReceiptsForBlock is null) { throw new EthSyncException($"{bestPeer} didn't send receipts for block {currentBlock.ToString(Block.Format.Short)}."); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs index 7e46bc4e126..5acbb4a0287 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs @@ -43,7 +43,7 @@ public MergeBlocksSyncPeerAllocationStrategyFactory( public IPeerAllocationStrategy Create(BlocksRequest? request) { // because of the way the generics cannot handle T / T? - if (request == null) + if (request is null) { throw new ArgumentNullException( $"NULL received for allocation in {nameof(MergeBlocksSyncPeerAllocationStrategyFactory)}"); diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/PeerRefresher.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/PeerRefresher.cs index d9c3e6d3aa5..5b77683b073 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/PeerRefresher.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/PeerRefresher.cs @@ -147,7 +147,7 @@ internal async Task RefreshPeerForFcu( if (_logger.IsTrace) _logger.Trace($"PeerRefreshForFCU received block info from {syncPeer.Node:c} headHeader: {headBlockHeader} headParentHeader: {headParentBlockHeader} finalizedBlockHeader: {finalizedBlockHeader}"); - if (finalizedBlockhash != Keccak.Zero && finalizedBlockHeader == null) + if (finalizedBlockhash != Keccak.Zero && finalizedBlockHeader is null) { _syncPeerPool.ReportRefreshFailed(syncPeer, "FCU no finalized block header"); return; diff --git a/src/Nethermind/Nethermind.Mev/MevRpcModule.cs b/src/Nethermind/Nethermind.Mev/MevRpcModule.cs index 12bb3ceae5e..11037fdda2a 100644 --- a/src/Nethermind/Nethermind.Mev/MevRpcModule.cs +++ b/src/Nethermind/Nethermind.Mev/MevRpcModule.cs @@ -149,7 +149,7 @@ private static BundleTransaction[] Decode(byte[][] transactions, ISet? r private bool HasStateForBlock(BlockHeader header) { RootCheckVisitor rootCheckVisitor = new(); - if (header.StateRoot == null) return false; + if (header.StateRoot is null) return false; _stateReader.RunTreeVisitor(rootCheckVisitor, header.StateRoot!); return rootCheckVisitor.HasRoot; } diff --git a/src/Nethermind/Nethermind.Monitoring/Metrics/MetricsController.cs b/src/Nethermind/Nethermind.Monitoring/Metrics/MetricsController.cs index 25cfc5bce74..0546e7d47f5 100644 --- a/src/Nethermind/Nethermind.Monitoring/Metrics/MetricsController.cs +++ b/src/Nethermind/Nethermind.Monitoring/Metrics/MetricsController.cs @@ -30,8 +30,6 @@ namespace Nethermind.Monitoring.Metrics { public class MetricsController : IMetricsController { - public static readonly Dictionary StaticTags = new(); - private readonly int _intervalSeconds; private Timer _timer; private Dictionary _gauges = new(); @@ -45,48 +43,49 @@ public void RegisterMetrics(Type type) EnsurePropertiesCached(type); foreach ((PropertyInfo propertyInfo, string gaugeName) in _propertiesCache[type]) { - GetMemberInfoMectricsDescription(propertyInfo, gaugeName); + CreateMemberInfoMectricsGauge(propertyInfo, gaugeName); } foreach ((FieldInfo fieldInfo, string gaugeName) in _fieldsCache[type]) { - GetMemberInfoMectricsDescription(fieldInfo, gaugeName); + CreateMemberInfoMectricsGauge(fieldInfo, gaugeName); } _metricTypes.Add(type); } - private void GetMemberInfoMectricsDescription(MemberInfo propertyInfo, string gaugeName) + private void CreateMemberInfoMectricsGauge(MemberInfo propertyInfo, string gaugeName) { GaugeConfiguration configuration = new(); Dictionary tagValues = new(); - propertyInfo.GetCustomAttributes() - .ForEach(attribute => InsertStaticMemberInfo(attribute.Informer, attribute.Label, tagValues)); - configuration.StaticLabels = tagValues; + configuration.StaticLabels = propertyInfo + .GetCustomAttributes() + .ToDictionary( + attribute => attribute.Label, + attribute => GetStaticMemberInfo(attribute.Informer, attribute.Label)); string description = propertyInfo.GetCustomAttribute()?.Description; _gauges[gaugeName] = CreateGauge(BuildGaugeName(propertyInfo.Name), description, configuration); } - private static void InsertStaticMemberInfo(Type givenInformer, string givenName, Dictionary tagValues) + private static string GetStaticMemberInfo(Type givenInformer, string givenName) { Type type = givenInformer; PropertyInfo[] tagsData = type.GetProperties(BindingFlags.Static | BindingFlags.Public); PropertyInfo info = tagsData.FirstOrDefault(info => info.Name == givenName); - if (info == null) + if (info is null) { - throw new Exception("Developer error: a requested static description field was not implemented!"); + throw new NotSupportedException("Developer error: a requested static description field was not implemented!"); } object value = info.GetValue(null); - if (value == null) + if (value is null) { - throw new Exception("Developer error: a requested static description field was not initialised!"); + throw new NotSupportedException("Developer error: a requested static description field was not initialised!"); } - string data = value.ToString(); - tagValues.Add(info.Name, data); + return value.ToString(); } private void EnsurePropertiesCached(Type type) @@ -167,7 +166,7 @@ private void UpdateMetrics(Type type) double value = Convert.ToDouble(kvp.Value); var gaugeName = GetGaugeNameKey(dict.DictName, kvp.Key); - if (ReplaceValueIfChanged(value, gaugeName) == null) + if (ReplaceValueIfChanged(value, gaugeName) is null) { var gauge = CreateGauge(BuildGaugeName(kvp.Key)); _gauges[gaugeName] = gauge; diff --git a/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs b/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs index 8b9227823d1..6b2cb920dd8 100644 --- a/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs +++ b/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs @@ -59,7 +59,7 @@ public MonitoringService(IMetricsController metricsController, IMetricsConfig me ? throw new ArgumentException($"Invalid monitoring push interval: {intervalSeconds}s") : intervalSeconds; - _logger = logManager == null + _logger = logManager is null ? throw new ArgumentNullException(nameof(logManager)) : logManager.GetClassLogger(); _options = GetOptions(); diff --git a/src/Nethermind/Nethermind.Network.Discovery/DiscoveryApp.cs b/src/Nethermind/Nethermind.Network.Discovery/DiscoveryApp.cs index b19297fb8e8..0e13b81035e 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/DiscoveryApp.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/DiscoveryApp.cs @@ -283,7 +283,7 @@ private void AddPersistedNodes(CancellationToken cancellationToken) } INodeLifecycleManager? manager = _discoveryManager.GetNodeLifecycleManager(node, true); - if (manager == null) + if (manager is null) { if (_logger.IsDebug) { @@ -401,7 +401,7 @@ private async Task StopUdpChannelAsync() } _logger.Info("Stopping discovery udp channel"); - if (_channel == null) + if (_channel is null) { return; } diff --git a/src/Nethermind/Nethermind.Network.Discovery/DiscoveryManager.cs b/src/Nethermind/Nethermind.Network.Discovery/DiscoveryManager.cs index b9e1b24df28..2621d37b014 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/DiscoveryManager.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/DiscoveryManager.cs @@ -69,7 +69,7 @@ public void OnIncomingMsg(DiscoveryMsg msg) Node node = new(msg.FarPublicKey, msg.FarAddress); INodeLifecycleManager? nodeManager = GetNodeLifecycleManager(node); - if (nodeManager == null) + if (nodeManager is null) { return; } @@ -222,7 +222,7 @@ public IReadOnlyCollection GetOrAddNodeLifecycleManagers( private bool ValidatePingAddress(PingMsg msg) { - if (msg.DestinationAddress == null || msg.FarAddress == null) + if (msg.DestinationAddress is null || msg.FarAddress is null) { if (_logger.IsDebug) _logger.Debug($"Received a ping message with empty address, message: {msg}"); return false; diff --git a/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManager.cs b/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManager.cs index 11b8e1dad13..d07c6af1edb 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManager.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManager.cs @@ -138,7 +138,7 @@ public void ProcessEnrRequestMsg(EnrRequestMsg enrRequestMessage) public void ProcessPongMsg(PongMsg pongMsg) { PingMsg? sentPingMsg = Interlocked.Exchange(ref _lastSentPing, null); - if (sentPingMsg == null) + if (sentPingMsg is null) { return; } diff --git a/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManagerFactory.cs b/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManagerFactory.cs index 12635dafb3f..0253fbc6e5b 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManagerFactory.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Lifecycle/NodeLifecycleManagerFactory.cs @@ -54,7 +54,7 @@ public NodeLifecycleManagerFactory(INodeTable nodeTable, public INodeLifecycleManager CreateNodeLifecycleManager(Node node) { - if (DiscoveryManager == null) + if (DiscoveryManager is null) { throw new Exception($"{nameof(DiscoveryManager)} has to be set"); } diff --git a/src/Nethermind/Nethermind.Network.Discovery/NettyDiscoveryHandler.cs b/src/Nethermind/Nethermind.Network.Discovery/NettyDiscoveryHandler.cs index 1c8bb5bdf73..173e5c29542 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/NettyDiscoveryHandler.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/NettyDiscoveryHandler.cs @@ -203,7 +203,7 @@ private bool ValidateMsg(DiscoveryMsg msg, MsgType type, EndPoint address, IChan return false; } - if (msg.FarAddress == null) + if (msg.FarAddress is null) { if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportIncomingMessage(msg.FarAddress, "HANDLER disc v4", $"{msg.MsgType.ToString()} has null far address"); if (_logger.IsDebug) _logger.Debug($"Discovery message without a valid far address {msg.FarAddress}, type: {type}, sender: {address}, message: {msg}"); @@ -217,7 +217,7 @@ private bool ValidateMsg(DiscoveryMsg msg, MsgType type, EndPoint address, IChan return false; } - if (msg.FarPublicKey == null) + if (msg.FarPublicKey is null) { if (NetworkDiagTracer.IsEnabled) NetworkDiagTracer.ReportIncomingMessage(msg.FarAddress, "HANDLER disc v4", $"{msg.MsgType.ToString()} has null far public key"); if (_logger.IsDebug) _logger.Debug($"Discovery message without a valid signature {msg.FarAddress} but was {ctx.Channel.RemoteAddress}, type: {type}, sender: {address}, message: {msg}"); diff --git a/src/Nethermind/Nethermind.Network.Discovery/NodesLocator.cs b/src/Nethermind/Nethermind.Network.Discovery/NodesLocator.cs index 7c46b9d1df4..1cfccbcaf39 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/NodesLocator.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/NodesLocator.cs @@ -54,7 +54,7 @@ public async Task LocateNodesAsync(CancellationToken cancellationToken) public async Task LocateNodesAsync(byte[]? searchedNodeId, CancellationToken cancellationToken) { - if (_masterNode == null) + if (_masterNode is null) { throw new InvalidOperationException("Master node has not been initialized"); } diff --git a/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeTable.cs b/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeTable.cs index 79d99c56911..14feb4d5325 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeTable.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeTable.cs @@ -71,7 +71,7 @@ public void ReplaceNode(Node nodeToRemove, Node nodeToAdd) private void CheckInitialization() { - if (MasterNode == null) + if (MasterNode is null) { throw new InvalidOperationException("Master not has not been initialized"); } diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs index dfb563d566c..0bb9a9a609f 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs @@ -46,7 +46,7 @@ public byte[] Serialize(NeighborsMsg msg) } byte[] data = Rlp.Encode( - nodes == null ? Rlp.OfEmptySequence : Rlp.Encode(nodes), + nodes is null ? Rlp.OfEmptySequence : Rlp.Encode(nodes), Rlp.Encode(msg.ExpirationTime) ).Bytes; diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs index 4a3709afc4e..1f95967aca5 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs @@ -72,7 +72,7 @@ public static EnrTreeBranch ParseBranch(string enrTreeBranchText) public static EnrTreeRoot ParseEnrRoot(string enrTreeRootText) { - if (enrTreeRootText == null) throw new ArgumentNullException(nameof(enrTreeRootText)); + if (enrTreeRootText is null) throw new ArgumentNullException(nameof(enrTreeRootText)); EnrTreeRoot enrTreeRoot = new(); diff --git a/src/Nethermind/Nethermind.Network.Stats/NodeStatsManager.cs b/src/Nethermind/Nethermind.Network.Stats/NodeStatsManager.cs index 6aadd750ba8..e796c9ab61a 100644 --- a/src/Nethermind/Nethermind.Network.Stats/NodeStatsManager.cs +++ b/src/Nethermind/Nethermind.Network.Stats/NodeStatsManager.cs @@ -96,7 +96,7 @@ private INodeStats AddStats(Node node) public INodeStats GetOrAdd(Node node) { - if (node == null) + if (node is null) { return null; } diff --git a/src/Nethermind/Nethermind.Network.Test/P2P/Subprotocols/Eth/V63/ReceiptsMessageSerializerTests.cs b/src/Nethermind/Nethermind.Network.Test/P2P/Subprotocols/Eth/V63/ReceiptsMessageSerializerTests.cs index f75e3e1ea01..42bafd9655d 100644 --- a/src/Nethermind/Nethermind.Network.Test/P2P/Subprotocols/Eth/V63/ReceiptsMessageSerializerTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/P2P/Subprotocols/Eth/V63/ReceiptsMessageSerializerTests.cs @@ -35,7 +35,7 @@ private static void Test(TxReceipt[][] txReceipts) var serialized = serializer.Serialize(message); ReceiptsMessage deserialized = serializer.Deserialize(serialized); - if (txReceipts == null) + if (txReceipts is null) { Assert.AreEqual(0, deserialized.TxReceipts.Length); } @@ -44,7 +44,7 @@ private static void Test(TxReceipt[][] txReceipts) Assert.AreEqual(txReceipts.Length, deserialized.TxReceipts.Length, "length"); for (int i = 0; i < txReceipts.Length; i++) { - if (txReceipts[i] == null) + if (txReceipts[i] is null) { Assert.IsNull(deserialized.TxReceipts[i], $"receipts[{i}]"); } @@ -52,7 +52,7 @@ private static void Test(TxReceipt[][] txReceipts) { for (int j = 0; j < txReceipts[i].Length; j++) { - if (txReceipts[i][j] == null) + if (txReceipts[i][j] is null) { Assert.IsNull(deserialized.TxReceipts[i][j], $"receipts[{i}][{j}]"); } diff --git a/src/Nethermind/Nethermind.Network.Test/PeerManagerTests.cs b/src/Nethermind/Nethermind.Network.Test/PeerManagerTests.cs index 92bc8596640..fa86a914137 100644 --- a/src/Nethermind/Nethermind.Network.Test/PeerManagerTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/PeerManagerTests.cs @@ -328,7 +328,7 @@ public async Task Will_fill_up_over_and_over_again_on_disconnects_and_when_ids_k await ctx.PeerManager.StopAsync(); ctx.DisconnectAllSessions(); - Assert.True(ctx.PeerManager.CandidatePeers.All(p => p.OutSession == null)); + Assert.True(ctx.PeerManager.CandidatePeers.All(p => p.OutSession is null)); } [Test] diff --git a/src/Nethermind/Nethermind.Network.Test/SnapProtocolHandlerTests.cs b/src/Nethermind/Nethermind.Network.Test/SnapProtocolHandlerTests.cs index 9e747483a9e..2ea763d9e89 100644 --- a/src/Nethermind/Nethermind.Network.Test/SnapProtocolHandlerTests.cs +++ b/src/Nethermind/Nethermind.Network.Test/SnapProtocolHandlerTests.cs @@ -48,7 +48,7 @@ public IMessageSerializationService MessageSerializationService { get { - if (_messageSerializationService == null) + if (_messageSerializationService is null) { _messageSerializationService = new MessageSerializationService(); _messageSerializationService.Register(new AccountRangeMessageSerializer()); diff --git a/src/Nethermind/Nethermind.Network/MessageSerializationService.cs b/src/Nethermind/Nethermind.Network/MessageSerializationService.cs index 9ef349ae82c..809cbee7d4f 100644 --- a/src/Nethermind/Nethermind.Network/MessageSerializationService.cs +++ b/src/Nethermind/Nethermind.Network/MessageSerializationService.cs @@ -73,7 +73,7 @@ public void Register(Assembly assembly) if (interfaceGenericDefinition == typeof(IMessageSerializer<>).GetGenericTypeDefinition()) { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); - if (constructor == null) + if (constructor is null) { continue; } @@ -84,7 +84,7 @@ public void Register(Assembly assembly) if (interfaceGenericDefinition == typeof(IZeroMessageSerializer<>).GetGenericTypeDefinition()) { ConstructorInfo constructor = type.GetConstructor(Type.EmptyTypes); - if (constructor == null) + if (constructor is null) { continue; } diff --git a/src/Nethermind/Nethermind.Network/NetworkStorage.cs b/src/Nethermind/Nethermind.Network/NetworkStorage.cs index d3bc5a78d97..fc7002c85e3 100644 --- a/src/Nethermind/Nethermind.Network/NetworkStorage.cs +++ b/src/Nethermind/Nethermind.Network/NetworkStorage.cs @@ -53,7 +53,7 @@ public NetworkNode[] GetPersistedNodes() List nodes = new(); foreach (byte[]? nodeRlp in _fullDb.Values) { - if (nodeRlp == null) + if (nodeRlp is null) { continue; } diff --git a/src/Nethermind/Nethermind.Network/NodesLoader.cs b/src/Nethermind/Nethermind.Network/NodesLoader.cs index f12afa2b712..3a24456b285 100644 --- a/src/Nethermind/Nethermind.Network/NodesLoader.cs +++ b/src/Nethermind/Nethermind.Network/NodesLoader.cs @@ -108,7 +108,7 @@ private void LoadPeersFromDb(List peers) private void LoadConfigPeers(List peers, string? enodesString, Action nodeUpdate) { - if (enodesString == null || !enodesString.Any()) + if (enodesString is null || !enodesString.Any()) { return; } diff --git a/src/Nethermind/Nethermind.Network/P2P/MessageQueue.cs b/src/Nethermind/Nethermind.Network/P2P/MessageQueue.cs index c2ef4ad630d..ed0e6ac3643 100644 --- a/src/Nethermind/Nethermind.Network/P2P/MessageQueue.cs +++ b/src/Nethermind/Nethermind.Network/P2P/MessageQueue.cs @@ -43,7 +43,7 @@ public void Send(Request request) lock (_requestQueue) { - if (_currentRequest == null) + if (_currentRequest is null) { _currentRequest = request; _currentRequest.StartMeasuringTime(); @@ -60,7 +60,7 @@ public void Handle(TData data, long size) { lock (_requestQueue) { - if (_currentRequest == null) + if (_currentRequest is null) { throw new SubprotocolException($"Received a response to {nameof(TMsg)} that has not been requested"); } diff --git a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs index 08bb7ec926d..246d57ce6e2 100644 --- a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs +++ b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs @@ -268,13 +268,13 @@ protected BlockHeadersMessage FulfillBlockHeadersRequest(GetBlockHeadersMessage } Keccak startingHash = msg.StartBlockHash; - if (startingHash == null) + if (startingHash is null) { startingHash = SyncServer.FindHash(msg.StartBlockNumber); } BlockHeader[] headers = - startingHash == null + startingHash is null ? Array.Empty() : SyncServer.FindHeaders(startingHash, (int)msg.MaxHeaders, (int)msg.Skip, msg.Reverse == 1); @@ -374,7 +374,7 @@ private static BlockHeader[] FixHeadersForGeth(BlockHeader[] headers) int emptyBlocksAtTheEnd = 0; for (int i = 0; i < headers.Length; i++) { - if (headers[headers.Length - 1 - i] == null) + if (headers[headers.Length - 1 - i] is null) { emptyBlocksAtTheEnd++; } diff --git a/src/Nethermind/Nethermind.Network/P2P/Session.cs b/src/Nethermind/Nethermind.Network/P2P/Session.cs index c310ea8c896..9b86e319235 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Session.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Session.cs @@ -101,9 +101,9 @@ public Node Node get { //It is needed for lazy creation of Node, in case IN connections, publicKey is available only after handshake - if (_node == null) + if (_node is null) { - if (RemoteNodeId == null || RemoteHost == null || RemotePort == 0) + if (RemoteNodeId is null || RemoteHost is null || RemotePort == 0) { throw new InvalidOperationException("Cannot create a session's node object without knowing remote node details"); } @@ -191,7 +191,7 @@ public void ReceiveMessage(ZeroPacket zeroPacket) _logger.Trace($"{this} received a message of length {zeroPacket.Content.ReadableBytes} " + $"({dynamicMessageCode} => {protocol}.{messageId})"); - if (protocol == null) + if (protocol is null) { if (_logger.IsTrace) _logger.Warn($"Received a message from node: {RemoteNodeId}, " + @@ -259,7 +259,7 @@ public void ReceiveMessage(Packet packet) _logger.Trace($"{this} received a message of length {packet.Data.Length} " + $"({dynamicMessageCode} => {protocol}.{messageId})"); - if (protocol == null) + if (protocol is null) { if (_logger.IsTrace) _logger.Warn($"Received a message from node: {RemoteNodeId}, ({dynamicMessageCode} => {messageId}), " + @@ -285,8 +285,8 @@ public void Init(byte p2PVersion, IChannelHandlerContext context, IPacketSender { if (_logger.IsTrace) _logger.Trace($"{nameof(Init)} called on {this}"); - if (context == null) throw new ArgumentNullException(nameof(context)); - if (packetSender == null) throw new ArgumentNullException(nameof(packetSender)); + if (context is null) throw new ArgumentNullException(nameof(context)); + if (packetSender is null) throw new ArgumentNullException(nameof(packetSender)); P2PVersion = p2PVersion; lock (_sessionStateLock) @@ -330,7 +330,7 @@ public void Handshake(PublicKey? handshakeRemoteNodeId) //For IN connections we don't have NodeId until this moment, so we need to set it in Session //For OUT connections it is possible remote id is different than what we had persisted or received from Discovery //If that is the case we need to set it in the session - if (RemoteNodeId == null) + if (RemoteNodeId is null) { RemoteNodeId = handshakeRemoteNodeId; } @@ -479,7 +479,7 @@ public void MarkDisconnected(DisconnectReason disconnectReason, DisconnectType d Disconnecting?.Invoke(this, new DisconnectEventArgs(disconnectReason, disconnectType, details)); //Possible in case of disconnect before p2p initialization - if (_context == null) + if (_context is null) { //in case pipeline did not get to p2p - no disconnect delay _channel.DisconnectAsync().ContinueWith(x => diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Eth62ProtocolHandler.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Eth62ProtocolHandler.cs index 57ffcb3f75e..cc4e90dcb94 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Eth62ProtocolHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Eth62ProtocolHandler.cs @@ -82,7 +82,7 @@ public override void Init() { if (Logger.IsTrace) Logger.Trace($"{Name} subprotocol initializing with {Node:c}"); - if (SyncServer.Head == null) + if (SyncServer.Head is null) { throw new InvalidOperationException($"Cannot initialize {Name} without the head block set"); } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/MessageSizeEstimator.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/MessageSizeEstimator.cs index ee82c68bb64..d30c93420ac 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/MessageSizeEstimator.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/MessageSizeEstimator.cs @@ -24,7 +24,7 @@ public static class MessageSizeEstimator { public static ulong EstimateSize(BlockHeader blockHeader) { - if (blockHeader == null) + if (blockHeader is null) { return 0; } @@ -34,7 +34,7 @@ public static ulong EstimateSize(BlockHeader blockHeader) public static ulong EstimateSize(Transaction tx) { - if (tx == null) + if (tx is null) { return 0; } @@ -44,7 +44,7 @@ public static ulong EstimateSize(Transaction tx) public static ulong EstimateSize(Block block) { - if (block == null) + if (block is null) { return 0; } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs index 080f3cae614..56615299948 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs @@ -33,7 +33,7 @@ public BlockBodiesMessage(Block[] blocks) Bodies = new BlockBody[blocks.Length]; for (int i = 0; i < blocks.Length; i++) { - Bodies[i] = blocks[i] == null ? null : blocks[i].Body; + Bodies[i] = blocks[i] is null ? null : blocks[i].Body; } } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessageSerializer.cs index fa40282df1f..ad6fc248bc6 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessageSerializer.cs @@ -25,7 +25,7 @@ public class BlockBodiesMessageSerializer : IZeroInnerMessageSerializer b == null + return Rlp.Encode(message.Bodies.Select(b => b is null ? Rlp.OfEmptySequence : Rlp.Encode( Rlp.Encode(b.Transactions), diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/GetBlockHeadersMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/GetBlockHeadersMessageSerializer.cs index 76eb279c656..b929dd934a5 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/GetBlockHeadersMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/GetBlockHeadersMessageSerializer.cs @@ -50,7 +50,7 @@ public void Serialize(IByteBuffer byteBuffer, GetBlockHeadersMessage message) RlpStream rlpStream = new NettyRlpStream(byteBuffer); rlpStream.StartSequence(contentLength); - if (message.StartBlockHash == null) + if (message.StartBlockHash is null) { rlpStream.Encode(message.StartBlockNumber); } @@ -72,7 +72,7 @@ public GetBlockHeadersMessage Deserialize(IByteBuffer byteBuffer) public int GetLength(GetBlockHeadersMessage message, out int contentLength) { - contentLength = message.StartBlockHash == null + contentLength = message.StartBlockHash is null ? Rlp.LengthOf(message.StartBlockNumber) : Rlp.LengthOf(message.StartBlockHash); contentLength += Rlp.LengthOf(message.MaxHeaders); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs index 03c989336a6..edd1cd269d2 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs @@ -37,11 +37,11 @@ public ReceiptsMessageSerializer(ISpecProvider specProvider) public void Serialize(IByteBuffer byteBuffer, ReceiptsMessage message) { Rlp rlp = Rlp.Encode(message.TxReceipts.Select( - b => b == null + b => b is null ? Rlp.OfEmptySequence : Rlp.Encode( b.Select( - n => n == null + n => n is null ? Rlp.OfEmptySequence : _decoder.Encode(n, _specProvider.GetSpec(n.BlockNumber).IsEip658Enabled ? RlpBehaviors.Eip658Receipts : RlpBehaviors.None)).ToArray())).ToArray()); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs index 4b35650c136..03c05093efe 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs @@ -58,7 +58,7 @@ public LesProtocolHandler( public override void Init() { if (Logger.IsTrace) Logger.Trace($"{ProtocolCode} v{ProtocolVersion} subprotocol initializing with {Session.Node:c}"); - if (SyncServer.Head == null) + if (SyncServer.Head is null) { throw new InvalidOperationException($"Cannot initialize {ProtocolCode} v{ProtocolVersion} protocol without the head block set"); } @@ -298,12 +298,12 @@ public override void NotifyOfNewBlock(Block block, SendBlockMode mode) announceMessage.HeadHash = block.Hash; announceMessage.HeadBlockNo = block.Number; announceMessage.TotalDifficulty = block.TotalDifficulty.Value; - if (_lastSentBlock == null || block.ParentHash == _lastSentBlock.Hash) + if (_lastSentBlock is null || block.ParentHash == _lastSentBlock.Hash) announceMessage.ReorgDepth = 0; else { BlockHeader firstCommonAncestor = SyncServer.FindLowestCommonAncestor(block.Header, _lastSentBlock); - if (firstCommonAncestor == null) + if (firstCommonAncestor is null) throw new SubprotocolException($"Unable to send announcment to LES peer - No common ancestor found between {block.Header} and {_lastSentBlock}"); announceMessage.ReorgDepth = _lastSentBlock.Number - firstCommonAncestor.Number; } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/AccountRangeMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/AccountRangeMessageSerializer.cs index bf2f461b48c..fe97bc8c955 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/AccountRangeMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/AccountRangeMessageSerializer.cs @@ -37,7 +37,7 @@ public void Serialize(IByteBuffer byteBuffer, AccountRangeMessage message) stream.StartSequence(contentLength); stream.Encode(message.RequestId); - if (message.PathsWithAccounts == null || message.PathsWithAccounts.Length == 0) + if (message.PathsWithAccounts is null || message.PathsWithAccounts.Length == 0) { stream.EncodeNullObject(); } @@ -57,7 +57,7 @@ public void Serialize(IByteBuffer byteBuffer, AccountRangeMessage message) } } - if (message.Proofs == null || message.Proofs.Length == 0) + if (message.Proofs is null || message.Proofs.Length == 0) { stream.EncodeNullObject(); } @@ -99,7 +99,7 @@ private PathWithAccount DecodePathWithRlpData(RlpStream stream) int contentLength = Rlp.LengthOf(message.RequestId); int pwasLength = 0; - if (message.PathsWithAccounts == null || message.PathsWithAccounts.Length == 0) + if (message.PathsWithAccounts is null || message.PathsWithAccounts.Length == 0) { pwasLength = 1; } @@ -118,7 +118,7 @@ private PathWithAccount DecodePathWithRlpData(RlpStream stream) contentLength += Rlp.LengthOfSequence(pwasLength); int proofsLength = 0; - if (message.Proofs == null || message.Proofs.Length == 0) + if (message.Proofs is null || message.Proofs.Length == 0) { proofsLength = 1; } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs index 330af92ebba..9ccc2ab8389 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs @@ -35,7 +35,7 @@ public void Serialize(IByteBuffer byteBuffer, GetTrieNodesMessage message) stream.Encode(message.RequestId); stream.Encode(message.RootHash); - if (message.Paths == null || message.Paths.Length == 0) + if (message.Paths is null || message.Paths.Length == 0) { stream.EncodeNullObject(); } @@ -91,7 +91,7 @@ private PathGroup DecodeGroup(RlpStream stream) int allPathsLength = 0; int[] pathsLengths = new int[message.Paths.Length]; - if (message.Paths == null || message.Paths.Length == 0) + if (message.Paths is null || message.Paths.Length == 0) { allPathsLength = 1; } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs index 8d36ec7d5b5..a2fa99612cc 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs @@ -37,7 +37,7 @@ public void Serialize(IByteBuffer byteBuffer, StorageRangeMessage message) stream.Encode(message.RequestId); - if (message.Slots == null || message.Slots.Length == 0) + if (message.Slots is null || message.Slots.Length == 0) { stream.EncodeNullObject(); } @@ -65,7 +65,7 @@ public void Serialize(IByteBuffer byteBuffer, StorageRangeMessage message) } } - if (message.Proofs == null || message.Proofs.Length == 0) + if (message.Proofs is null || message.Proofs.Length == 0) { stream.EncodeNullObject(); } @@ -111,7 +111,7 @@ private PathWithStorageSlot DecodeSlot(RlpStream stream) int allSlotsLength = 0; int[] accountSlotsLengths = new int[message.Slots.Length]; - if (message.Slots == null || message.Slots.Length == 0) + if (message.Slots is null || message.Slots.Length == 0) { allSlotsLength = 1; } @@ -136,7 +136,7 @@ private PathWithStorageSlot DecodeSlot(RlpStream stream) contentLength += Rlp.LengthOfSequence(allSlotsLength); int proofsLength = 0; - if (message.Proofs == null || message.Proofs.Length == 0) + if (message.Proofs is null || message.Proofs.Length == 0) { proofsLength = 1; contentLength++; diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Wit/Messages/BlockWitnessHashesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Wit/Messages/BlockWitnessHashesMessageSerializer.cs index 4b9486048d1..0e19c658104 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Wit/Messages/BlockWitnessHashesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Wit/Messages/BlockWitnessHashesMessageSerializer.cs @@ -31,7 +31,7 @@ public void Serialize(IByteBuffer byteBuffer, BlockWitnessHashesMessage message) byteBuffer.EnsureWritable(totalLength, true); nettyRlpStream.StartSequence(contentLength); nettyRlpStream.Encode(message.RequestId); - if (message.Hashes == null) + if (message.Hashes is null) { nettyRlpStream.EncodeNullObject(); } diff --git a/src/Nethermind/Nethermind.Network/PeerManager.cs b/src/Nethermind/Nethermind.Network/PeerManager.cs index 938e81f426e..ff00a85c406 100644 --- a/src/Nethermind/Nethermind.Network/PeerManager.cs +++ b/src/Nethermind/Nethermind.Network/PeerManager.cs @@ -759,7 +759,7 @@ private void OnDisconnected(object sender, DisconnectEventArgs e) if (_logger.IsTrace) _logger.Trace($"|NetworkTrace| peer disconnected event in PeerManager - {session} {e.DisconnectReason} {e.DisconnectType}"); - if (session.RemoteNodeId == null) + if (session.RemoteNodeId is null) { // this happens when we have a disconnect on incoming connection before handshake if (_logger.IsTrace) _logger.Trace($"Disconnect on session with no RemoteNodeId - {session}"); @@ -833,7 +833,7 @@ private void OnHandshakeComplete(object sender, EventArgs args) private void ManageNewRemoteNodeId(ISession session) { - if (session.ObsoleteRemoteNodeId == null) + if (session.ObsoleteRemoteNodeId is null) { return; } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs index b9b77519680..03194d8afdc 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/RlpxHost.cs @@ -146,7 +146,7 @@ public async Task Init() return t.Result; }); - if (_bootstrapChannel == null) + if (_bootstrapChannel is null) { throw new NetworkingException($"Failed to initialize {nameof(_bootstrapChannel)}", NetworkExceptionType.Other); } diff --git a/src/Nethermind/Nethermind.Network/SessionMonitor.cs b/src/Nethermind/Nethermind.Network/SessionMonitor.cs index fe832a4d05a..ea5db6bb40b 100644 --- a/src/Nethermind/Nethermind.Network/SessionMonitor.cs +++ b/src/Nethermind/Nethermind.Network/SessionMonitor.cs @@ -118,7 +118,7 @@ private async Task SendPingMessagesAsync() private async Task SendPingMessage(ISession session) { - if (session.PingSender == null) + if (session.PingSender is null) { /* this would happen when session is initialized already but the protocol is not yet initialized we do not have a separate session state for it at the moment */ diff --git a/src/Nethermind/Nethermind.Overseer.Test/Framework/TestBuilder.cs b/src/Nethermind/Nethermind.Overseer.Test/Framework/TestBuilder.cs index 39c0ad466f9..d45d184ec39 100644 --- a/src/Nethermind/Nethermind.Overseer.Test/Framework/TestBuilder.cs +++ b/src/Nethermind/Nethermind.Overseer.Test/Framework/TestBuilder.cs @@ -248,7 +248,7 @@ private NethermindProcessWrapper GetOrCreateNode(string name, string baseConfigF private string GetNodeKey(string key) { - if (key == null) + if (key is null) { byte[] keyArray = new byte[32]; keyArray[0] = 1; diff --git a/src/Nethermind/Nethermind.Runner.Test/EthereumRunnerTests.cs b/src/Nethermind/Nethermind.Runner.Test/EthereumRunnerTests.cs index abfa7a0c67e..39b455fdfe6 100644 --- a/src/Nethermind/Nethermind.Runner.Test/EthereumRunnerTests.cs +++ b/src/Nethermind/Nethermind.Runner.Test/EthereumRunnerTests.cs @@ -89,7 +89,7 @@ public static IEnumerable ChainSpecRunnerTests [Timeout(300000)] // just to make sure we are not on infinite loop on steps because of incorrect dependencies public async Task Smoke((string file, ConfigProvider configProvider) testCase, int testIndex) { - if (testCase.configProvider == null) + if (testCase.configProvider is null) { // some weird thing, not worth investigating return; @@ -102,7 +102,7 @@ public async Task Smoke((string file, ConfigProvider configProvider) testCase, i [Timeout(30000)] // just to make sure we are not on infinite loop on steps because of incorrect dependencies public async Task Smoke_cancel((string file, ConfigProvider configProvider) testCase, int testIndex) { - if (testCase.configProvider == null) + if (testCase.configProvider is null) { // some weird thing, not worth investigating return; diff --git a/src/Nethermind/Nethermind.Runner/JsonRpc/Startup.cs b/src/Nethermind/Nethermind.Runner/JsonRpc/Startup.cs index b6f748ca3ca..6e9c49a8e5b 100644 --- a/src/Nethermind/Nethermind.Runner/JsonRpc/Startup.cs +++ b/src/Nethermind/Nethermind.Runner/JsonRpc/Startup.cs @@ -51,7 +51,7 @@ public void ConfigureServices(IServiceCollection services) { ServiceProvider sp = Build(services); IConfigProvider? configProvider = sp.GetService(); - if (configProvider == null) + if (configProvider is null) { throw new ApplicationException($"{nameof(IConfigProvider)} could not be resolved"); } @@ -101,7 +101,7 @@ long SerializeTimeoutException(IJsonRpcService service, Stream resultStream) IConfigProvider? configProvider = app.ApplicationServices.GetService(); IRpcAuthentication? rpcAuthentication = app.ApplicationServices.GetService(); - if (configProvider == null) + if (configProvider is null) { throw new ApplicationException($"{nameof(IConfigProvider)} has not been loaded properly"); } diff --git a/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs b/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs index 270980f2630..49a5f0b17af 100644 --- a/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs +++ b/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs @@ -35,7 +35,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - if (formatter == null) + if (formatter is null) { throw new ArgumentNullException(nameof(formatter)); } diff --git a/src/Nethermind/Nethermind.Runner/Program.cs b/src/Nethermind/Nethermind.Runner/Program.cs index fcd3709fbab..7540aabbba1 100644 --- a/src/Nethermind/Nethermind.Runner/Program.cs +++ b/src/Nethermind/Nethermind.Runner/Program.cs @@ -274,7 +274,7 @@ private static void BuildOptionsFromConfigFiles(CommandLineApplication app) foreach (Type configType in configTypes.Where(ct => !ct.IsAssignableTo(typeof(INoCategoryConfig))).OrderBy(c => c.Name)) { - if (configType == null) + if (configType is null) { continue; } @@ -293,7 +293,7 @@ private static void BuildOptionsFromConfigFiles(CommandLineApplication app) ConfigItemAttribute? configItemAttribute = propertyInfo.GetCustomAttribute(); if (!(configItemAttribute?.DisabledForCli ?? false)) { - _ = app.Option($"--{configType.Name[1..].Replace("Config", string.Empty)}.{propertyInfo.Name}", $"{(configItemAttribute == null ? "" : configItemAttribute.Description + $" (DEFAULT: {configItemAttribute.DefaultValue})" ?? "")}", CommandOptionType.SingleValue); + _ = app.Option($"--{configType.Name[1..].Replace("Config", string.Empty)}.{propertyInfo.Name}", $"{(configItemAttribute is null ? "" : configItemAttribute.Description + $" (DEFAULT: {configItemAttribute.DefaultValue})" ?? "")}", CommandOptionType.SingleValue); } } diff --git a/src/Nethermind/Nethermind.Serialization.Json/PublicKeyConverter.cs b/src/Nethermind/Nethermind.Serialization.Json/PublicKeyConverter.cs index 93024535f71..3c97e591a0d 100644 --- a/src/Nethermind/Nethermind.Serialization.Json/PublicKeyConverter.cs +++ b/src/Nethermind/Nethermind.Serialization.Json/PublicKeyConverter.cs @@ -30,7 +30,7 @@ public override void WriteJson(JsonWriter writer, PublicKey value, JsonSerialize public override PublicKey ReadJson(JsonReader reader, Type objectType, PublicKey existingValue, bool hasExistingValue, JsonSerializer serializer) { string s = (string)reader.Value; - return s == null ? null : new PublicKey(s); + return s is null ? null : new PublicKey(s); } } } diff --git a/src/Nethermind/Nethermind.Serialization.Json/UInt256Converter.cs b/src/Nethermind/Nethermind.Serialization.Json/UInt256Converter.cs index 4f76972a7c9..e5f3ed8642e 100644 --- a/src/Nethermind/Nethermind.Serialization.Json/UInt256Converter.cs +++ b/src/Nethermind/Nethermind.Serialization.Json/UInt256Converter.cs @@ -72,7 +72,7 @@ public static UInt256 ReaderJson(JsonReader reader) } string s = reader.Value?.ToString(); - if (s == null) + if (s is null) { throw new JsonException($"{nameof(UInt256)} cannot be deserialized from null"); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs index c8914e3a158..0a2a248e189 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs @@ -72,7 +72,7 @@ public Keccak DecodeStorageRootOnly(RlpStream rlpStream) public void Encode(RlpStream stream, Account? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { stream.EncodeNullObject(); return; @@ -98,7 +98,7 @@ public Rlp Encode(Account? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) public void Encode(Account account, RlpStream rlpStream, int? contentLength = null) { - if (contentLength == null) + if (contentLength is null) { contentLength = GetContentLength(account); } @@ -130,7 +130,7 @@ public int GetLength(Account[] accounts) { int length = 0; - if (accounts == null || accounts.Length == 0) + if (accounts is null || accounts.Length == 0) { return 1; } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs index 348f34171b6..8a7003c5f71 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs @@ -71,7 +71,7 @@ public void Encode(RlpStream stream, BlockInfo item, RlpBehaviors rlpBehaviors = public Rlp Encode(BlockInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs index 829a8d6f281..7240702c465 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs @@ -98,14 +98,14 @@ public void Encode(RlpStream stream, ChainLevelInfo item, RlpBehaviors rlpBehavi public Rlp Encode(ChainLevelInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } for (int i = 0; i < item.BlockInfos.Length; i++) { - if (item.BlockInfos[i] == null) + if (item.BlockInfos[i] is null) { throw new InvalidOperationException($"{nameof(BlockInfo)} is null when encoding {nameof(ChainLevelInfo)}"); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/Eip2930/AccessListDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/Eip2930/AccessListDecoder.cs index 4f701be96cc..5f3cc9ec435 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/Eip2930/AccessListDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/Eip2930/AccessListDecoder.cs @@ -48,7 +48,7 @@ public class AccessListDecoder : IRlpStreamDecoder, IRlpValueDecode { rlpStream.SkipLength(); Address address = rlpStream.DecodeAddress(); - if (address == null) + if (address is null) { throw new RlpException("Invalid tx access list format - address is null"); } @@ -100,7 +100,7 @@ public class AccessListDecoder : IRlpStreamDecoder, IRlpValueDecode { decoderContext.SkipLength(); Address address = decoderContext.DecodeAddress(); - if (address == null) + if (address is null) { throw new RlpException("Invalid tx access list format - address is null"); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs index bbd8cae72b6..6c53e9a08c7 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/HeaderDecoder.cs @@ -211,7 +211,7 @@ public void Encode(RlpStream rlpStream, BlockHeader? header, RlpBehaviors rlpBeh public Rlp Encode(BlockHeader? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { - if (item == null) + if (item is null) { return Rlp.OfEmptySequence; } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/LogEntryDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/LogEntryDecoder.cs index 7c64453a108..255bb1e335e 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/LogEntryDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/LogEntryDecoder.cs @@ -69,7 +69,7 @@ public class LogEntryDecoder : IRlpStreamDecoder, IRlpValueDecoder(this IRlpValueDecoder decoder, ref Rlp.Value public static Rlp Encode(this IRlpObjectDecoder decoder, T?[]? items, RlpBehaviors behaviors = RlpBehaviors.None) { - if (items == null) + if (items is null) { return Rlp.OfEmptySequence; } @@ -52,7 +52,7 @@ public static Rlp Encode(this IRlpObjectDecoder decoder, T?[]? items, RlpB Rlp[] rlpSequence = new Rlp[items.Length]; for (int i = 0; i < items.Length; i++) { - rlpSequence[i] = items[i] == null ? Rlp.OfEmptySequence : decoder.Encode(items[i], behaviors); + rlpSequence[i] = items[i] is null ? Rlp.OfEmptySequence : decoder.Encode(items[i], behaviors); } return Rlp.Encode(rlpSequence); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs index 3cee7de88a1..fa8c532ae91 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs @@ -173,7 +173,7 @@ public bool IsSequenceNext() public void Encode(Keccak? keccak) { - if (keccak == null) + if (keccak is null) { WriteByte(EmptyArrayByte); } @@ -194,7 +194,7 @@ public void Encode(Keccak? keccak) public void Encode(Keccak[] keccaks) { - if (keccaks == null) + if (keccaks is null) { EncodeNullObject(); } @@ -211,7 +211,7 @@ public void Encode(Keccak[] keccaks) public void Encode(Address? address) { - if (address == null) + if (address is null) { WriteByte(EmptyArrayByte); } @@ -224,7 +224,7 @@ public void Encode(Address? address) public void Encode(Rlp? rlp) { - if (rlp == null) + if (rlp is null) { WriteByte(EmptyArrayByte); } @@ -243,7 +243,7 @@ public void Encode(Bloom? bloom) WriteByte(0); WriteZero(256); } - else if (bloom == null) + else if (bloom is null) { WriteByte(EmptyArrayByte); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs index e4889d619bf..aa47d4faa71 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs @@ -461,7 +461,7 @@ private int GetContentLength(T item, bool forSigning, bool isEip155Enabled = fal } else { - bool signatureIsNull = item.Signature == null; + bool signatureIsNull = item.Signature is null; contentLength += signatureIsNull ? 1 : Rlp.LengthOf(item.Type == TxType.Legacy ? item.Signature.V : item.Signature.RecoveryId); contentLength += signatureIsNull ? 1 : Rlp.LengthOf(item.Signature.RAsSpan.WithoutLeadingZeros()); contentLength += signatureIsNull ? 1 : Rlp.LengthOf(item.Signature.SAsSpan.WithoutLeadingZeros()); diff --git a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs index 7c70246d040..c396f8c5f10 100644 --- a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs +++ b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoader.cs @@ -77,7 +77,7 @@ private void LoadParameters(ChainSpecJson chainSpecJson, ChainSpec chainSpec) long? GetTransitions(string builtInName, Predicate> predicate) { var allocation = chainSpecJson.Accounts.Values.FirstOrDefault(v => v.BuiltIn?.Name.Equals(builtInName, StringComparison.InvariantCultureIgnoreCase) == true); - if (allocation == null) return null; + if (allocation is null) return null; KeyValuePair[] pricing = allocation.BuiltIn.Pricing.Where(o => predicate(o)).ToArray(); if (pricing.Length > 0) { @@ -206,7 +206,7 @@ private static void LoadTransitions(ChainSpecJson chainSpecJson, ChainSpec chain chainSpec.SpuriousDragonBlockNumber = chainSpec.Parameters.Eip160Transition; chainSpec.ByzantiumBlockNumber = chainSpec.Parameters.Eip140Transition; chainSpec.ConstantinopleBlockNumber = - chainSpec.Parameters.Eip1283DisableTransition == null + chainSpec.Parameters.Eip1283DisableTransition is null ? null : chainSpec.Parameters.Eip145Transition; chainSpec.ConstantinopleFixBlockNumber = @@ -339,7 +339,7 @@ static AuRaParameters.Validator LoadValidator(ChainSpecJson.AuRaValidatorJson va private static void LoadGenesis(ChainSpecJson chainSpecJson, ChainSpec chainSpec) { - if (chainSpecJson.Genesis == null) + if (chainSpecJson.Genesis is null) { return; } @@ -392,7 +392,7 @@ private static void LoadGenesis(ChainSpecJson chainSpecJson, ChainSpec chainSpec private static void LoadAllocations(ChainSpecJson chainSpecJson, ChainSpec chainSpec) { - if (chainSpecJson.Accounts == null) + if (chainSpecJson.Accounts is null) { return; } @@ -400,7 +400,7 @@ private static void LoadAllocations(ChainSpecJson chainSpecJson, ChainSpec chain chainSpec.Allocations = new Dictionary(); foreach (KeyValuePair account in chainSpecJson.Accounts) { - if (account.Value.BuiltIn != null && account.Value.Balance == null) + if (account.Value.BuiltIn != null && account.Value.Balance is null) { continue; } @@ -416,7 +416,7 @@ private static void LoadAllocations(ChainSpecJson chainSpecJson, ChainSpec chain private static void LoadBootnodes(ChainSpecJson chainSpecJson, ChainSpec chainSpec) { - if (chainSpecJson.Nodes == null) + if (chainSpecJson.Nodes is null) { chainSpec.Bootnodes = Array.Empty(); return; diff --git a/src/Nethermind/Nethermind.Synchronization.Test/AllocationStrategies/BySpeedStrategyTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/AllocationStrategies/BySpeedStrategyTests.cs index 4553de98b92..67aa7a10985 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/AllocationStrategies/BySpeedStrategyTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/AllocationStrategies/BySpeedStrategyTests.cs @@ -128,7 +128,7 @@ public void TestRecalculateSpeedProbability(int peerWithKnownSpeed, int peerWith { PeerInfo? selectedPeer = strategy.Allocate(null, peers, nodeStatsManager, Build.A.BlockTree().TestObject); int selectedPeerIdx = peers.IndexOf(selectedPeer); - if (peerSpeeds[selectedPeerIdx] == null) + if (peerSpeeds[selectedPeerIdx] is null) { peerWithoutSpeedPicked++; } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs index 04ea896c77d..16ceefbd3f6 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs @@ -840,7 +840,7 @@ public async Task Does_throw_on_transaction_count_different_than_receipts_count_ syncPeer.GetReceipts(Arg.Any>(), Arg.Any()) .Returns(ci => ctx.ResponseBuilder.BuildReceiptsResponse(ci.ArgAt>(0), Response.AllCorrect | Response.WithTransactions) - .Result.Select(r => r == null || r.Length == 0 ? r : r.Skip(1).ToArray()).ToArray()); + .Result.Select(r => r is null || r.Length == 0 ? r : r.Skip(1).ToArray()).ToArray()); PeerInfo peerInfo = new(syncPeer); syncPeer.HeadNumber.Returns(1); @@ -1213,7 +1213,7 @@ public async Task BuildBlocksResponse(IList blockHashes, Re } BlockHeader startHeader = _blockTree.FindHeader(blockHashes[0], BlockTreeLookupOptions.None); - if (startHeader == null) startHeader = _headers[blockHashes[0]]; + if (startHeader is null) startHeader = _headers[blockHashes[0]]; BlockHeader[] blockHeaders = new BlockHeader[blockHashes.Count]; BlockBody[] blockBodies = new BlockBody[blockHashes.Count]; diff --git a/src/Nethermind/Nethermind.Synchronization.Test/FastBlocks/FastBlocksFeedTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/FastBlocks/FastBlocksFeedTests.cs index cbfa0e47a6f..66e651814a1 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/FastBlocks/FastBlocksFeedTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/FastBlocks/FastBlocksFeedTests.cs @@ -769,7 +769,7 @@ // if (_pendingResponses.Count < _syncPeers.Count(p => !p.IsReported)) // { // FastBlocksBatch batch = _feed.PrepareRequest(); -// if (batch == null && _pendingResponses.Count == 0) +// if (batch is null && _pendingResponses.Count == 0) // { // TestContext.WriteLine($"STOP - NULL BATCH AND NO PENDING"); // break; @@ -780,7 +780,7 @@ // bool wasAssigned = false; // foreach (LatencySyncPeerMock syncPeer in _syncPeers) // { -// if (syncPeer.BusyUntil == null +// if (syncPeer.BusyUntil is null // && _peerTrees[syncPeer].Head.Number >= (batch.MinNumber ?? 0)) // { // syncPeer.BusyUntil = _time + syncPeer.Latency; @@ -976,7 +976,7 @@ // // Keccak hash = tree.FindHash(startNumber); // -// if (hash == null) +// if (hash is null) // { // TestContext.WriteLine($"{_time,6} | SYNC PEER {syncPeer.Node:s} CANNOT FIND {headersSyncBatch.StartNumber}"); // return; diff --git a/src/Nethermind/Nethermind.Synchronization.Test/FastSync/ReceiptsSyncFeedTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/FastSync/ReceiptsSyncFeedTests.cs index c16ce50451f..adcaaff62ad 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/FastSync/ReceiptsSyncFeedTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/FastSync/ReceiptsSyncFeedTests.cs @@ -270,7 +270,7 @@ private void LoadScenario(Scenario scenario, ISyncConfig syncConfig) ci => { Block block = scenario.Blocks[ci.Arg()]; - if (block == null) + if (block is null) { return null; } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/FastSync/StateSyncFeedTestsBase.cs b/src/Nethermind/Nethermind.Synchronization.Test/FastSync/StateSyncFeedTestsBase.cs index 2bead4d66a6..7973eba432d 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/FastSync/StateSyncFeedTestsBase.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/FastSync/StateSyncFeedTestsBase.cs @@ -301,7 +301,7 @@ public Task GetNodeData(IReadOnlyList hashes, CancellationToke { if (i >= MaxResponseLength) break; - if (_filter == null || _filter.Contains(item)) responses[i] = _stateDb[item.Bytes] ?? _codeDb[item.Bytes]; + if (_filter is null || _filter.Contains(item)) responses[i] = _stateDb[item.Bytes] ?? _codeDb[item.Bytes]; i++; } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/Mocks/FirstFree.cs b/src/Nethermind/Nethermind.Synchronization.Test/Mocks/FirstFree.cs index 4955aa4a173..a4ea768f07c 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/Mocks/FirstFree.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/Mocks/FirstFree.cs @@ -32,7 +32,7 @@ public static FirstFree Instance { get { - if (_instance == null) LazyInitializer.EnsureInitialized(ref _instance, () => new FirstFree()); + if (_instance is null) LazyInitializer.EnsureInitialized(ref _instance, () => new FirstFree()); return _instance; } diff --git a/src/Nethermind/Nethermind.Synchronization.Test/ParallelSync/SyncDispatcherTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/ParallelSync/SyncDispatcherTests.cs index b8ca3406702..7f3724da048 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/ParallelSync/SyncDispatcherTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/ParallelSync/SyncDispatcherTests.cs @@ -179,7 +179,7 @@ public TestSyncFeed(bool isMultiFeed = true) public override SyncResponseHandlingResult HandleResponse(TestBatch response, PeerInfo peer = null) { - if (response.Result == null) + if (response.Result is null) { Console.WriteLine("Handling failed response"); _returned.Enqueue(response); diff --git a/src/Nethermind/Nethermind.Synchronization.Test/TrieScenarios.cs b/src/Nethermind/Nethermind.Synchronization.Test/TrieScenarios.cs index 15e72efd157..107fffdd89f 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/TrieScenarios.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/TrieScenarios.cs @@ -48,7 +48,7 @@ public static class TrieScenarios [MethodImpl(MethodImplOptions.Synchronized)] public static void InitOnce() { - if (Empty == null) + if (Empty is null) { // _logger = new ConsoleAsyncLogger(LogLevel.Debug); // _logManager = new OneLoggerLogManager(_logger); diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloadContext.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloadContext.cs index d27d6db9a3c..8dd509fd2dc 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloadContext.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloadContext.cs @@ -55,7 +55,7 @@ public BlockDownloadContext(ISpecProvider specProvider, PeerInfo syncPeer, Block for (int i = 1; i < headers.Length; i++) { BlockHeader? header = headers[i]; - if (header?.Hash == null) + if (header?.Hash is null) { break; } @@ -101,7 +101,7 @@ public void SetBody(int index, BlockBody body) { int mappedIndex = _indexMapping[index]; Block block = Blocks[mappedIndex]; - if (body == null) + if (body is null) { throw new EthSyncException($"{_syncPeer} sent an empty body for {block.ToString(Block.Format.Short)}."); } diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs index b41e93f7db6..71fedab6f64 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs @@ -112,7 +112,7 @@ protected override async Task Dispatch( BlocksRequest? blocksRequest, CancellationToken cancellation) { - if (blocksRequest == null) + if (blocksRequest is null) { if (Logger.IsWarn) Logger.Warn($"NULL received for dispatch in {nameof(BlockDownloader)}"); return; @@ -152,7 +152,7 @@ await DownloadHeaders(bestPeer, blocksRequest, cancellation) public async Task DownloadHeaders(PeerInfo bestPeer, BlocksRequest blocksRequest, CancellationToken cancellation) { - if (bestPeer == null) + if (bestPeer is null) { string message = $"Not expecting best peer to be null inside the {nameof(BlockDownloader)}"; _logger.Error(message); @@ -210,7 +210,7 @@ bool HasMoreToSync() } BlockHeader? currentHeader = headers[i]; - if (currentHeader == null) + if (currentHeader is null) { if (headersSynced - headersSyncedInPreviousRequests > 0) { @@ -256,7 +256,7 @@ bool HasMoreToSync() public virtual async Task DownloadBlocks(PeerInfo? bestPeer, BlocksRequest blocksRequest, CancellationToken cancellation) { - if (bestPeer == null) + if (bestPeer is null) { string message = $"Not expecting best peer to be null inside the {nameof(BlockDownloader)}"; if (_logger.IsError) _logger.Error(message); @@ -362,7 +362,7 @@ bool HasMoreToSync() if (downloadReceipts) { TxReceipt[]? contextReceiptsForBlock = context.ReceiptsForBlocks![blockIndex]; - if (currentBlock.Header.HasBody && contextReceiptsForBlock == null) + if (currentBlock.Header.HasBody && contextReceiptsForBlock is null) { throw new EthSyncException($"{bestPeer} didn't send receipts for block {currentBlock.ToString(Block.Format.Short)}."); } @@ -466,7 +466,7 @@ protected async Task RequestBodies(PeerInfo peer, CancellationToken cancellation int receivedBodies = 0; for (int i = 0; i < result.Length; i++) { - if (result[i] == null) + if (result[i] is null) { break; } @@ -531,7 +531,7 @@ private void ValidateBatchConsistencyAndSetParents(PeerInfo bestPeer, BlockHeade throw new EthSyncException("Peer sent an inconsistent block list"); } - if (headers[i] == null) + if (headers[i] is null) { break; } @@ -727,7 +727,7 @@ protected void AdjustSyncBatchSize(TimeSpan downloadTime) protected override async Task Allocate(BlocksRequest? request) { - if (request == null) + if (request is null) { throw new InvalidOperationException($"NULL received for dispatch in {nameof(BlockDownloader)}"); } @@ -761,7 +761,7 @@ private void AllocationOnCancelled(object? sender, AllocationChangeEventArgs e) private void AllocationOnReplaced(object? sender, AllocationChangeEventArgs e) { - if (e.Previous == null) + if (e.Previous is null) { if (_logger.IsDebug) _logger.Debug($"Allocating {e.Current} for the blocks sync allocation"); } diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs index 8b5f55d26e0..79f49f81120 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs @@ -43,7 +43,7 @@ public BlocksSyncPeerAllocationStrategy(long? minBlocksAhead) { long? headersSpeed = nodeStatsManager.GetOrAdd(peerInfo.SyncPeer.Node).GetAverageTransferSpeed(TransferSpeedType.Headers); long? bodiesSpeed = nodeStatsManager.GetOrAdd(peerInfo.SyncPeer.Node).GetAverageTransferSpeed(TransferSpeedType.Bodies); - if (headersSpeed == null && bodiesSpeed == null) + if (headersSpeed is null && bodiesSpeed is null) { return null; } @@ -57,7 +57,7 @@ public BlocksSyncPeerAllocationStrategy(long? minBlocksAhead) decimal averageSpeed = 0M; int peersCount = 0; - bool wasNull = currentPeer == null; + bool wasNull = currentPeer is null; long currentSpeed = wasNull ? nullSpeed : @@ -116,7 +116,7 @@ public BlocksSyncPeerAllocationStrategy(long? minBlocksAhead) return currentPeer; } - if (bestDiffPeer.Info == null) + if (bestDiffPeer.Info is null) { return fastestPeer.Info; } diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs index ed7c68458fc..2257b2a3f7c 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs @@ -25,7 +25,7 @@ internal class BlocksSyncPeerAllocationStrategyFactory : IPeerAllocationStrategy public IPeerAllocationStrategy Create(BlocksRequest? request) { // because of the way the generics cannot handle T / T? - if (request == null) + if (request is null) { throw new ArgumentNullException( $"NULL received for allocation in {nameof(BlocksSyncPeerAllocationStrategyFactory)}"); diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/BodiesSyncFeed.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/BodiesSyncFeed.cs index 4c4608814d9..d60767c54cd 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/BodiesSyncFeed.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/BodiesSyncFeed.cs @@ -133,7 +133,7 @@ public override SyncResponseHandlingResult HandleResponse(BodiesSyncBatch? batch batch?.MarkHandlingStart(); try { - if (batch == null) + if (batch is null) { if (_logger.IsDebug) _logger.Debug("Received a NULL batch as a response"); return SyncResponseHandlingResult.InternalError; @@ -180,7 +180,7 @@ private int InsertBodies(BodiesSyncBatch batch) : batch.Response![i]; // last batch - if (blockInfo == null) + if (blockInfo is null) { break; } diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastBlocksSelectionStrategy.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastBlocksSelectionStrategy.cs index 4623e185d21..650b9aebbd6 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastBlocksSelectionStrategy.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastBlocksSelectionStrategy.cs @@ -49,7 +49,7 @@ public FastBlocksAllocationStrategy(TransferSpeedType speedType, long? minNumber IBlockTree blockTree) { IPeerAllocationStrategy strategy = _priority ? _fastest : _slowest; - peers = _minNumber == null ? peers : peers.Where(p => p.HeadNumber >= _minNumber); + peers = _minNumber is null ? peers : peers.Where(p => p.HeadNumber >= _minNumber); PeerInfo? allocated = strategy.Allocate(currentPeer, peers, nodeStatsManager, blockTree); return allocated; } diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs index 9e1569d2ab4..b5e99f300dc 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs @@ -118,7 +118,7 @@ public HeadersSyncFeed( _pivotNumber = _syncConfig.PivotNumberParsed; - bool useSyncPivot = _blockTree.LowestInsertedHeader == null || _blockTree.LowestInsertedHeader.Number > _pivotNumber; + bool useSyncPivot = _blockTree.LowestInsertedHeader is null || _blockTree.LowestInsertedHeader.Number > _pivotNumber; BlockHeader? lowestInserted = _blockTree.LowestInsertedHeader; long startNumber = useSyncPivot ? _pivotNumber : lowestInserted.Number; Keccak startHeaderHash = useSyncPivot ? _syncConfig.PivotHashParsed : lowestInserted.Hash; @@ -269,7 +269,7 @@ private void LogStateOnPrepare() public override SyncResponseHandlingResult HandleResponse(HeadersSyncBatch? batch, PeerInfo peer = null) { - if (batch == null) + if (batch is null) { if (_logger.IsDebug) _logger.Debug("Received a NULL batch as a response"); return SyncResponseHandlingResult.InternalError; @@ -281,7 +281,7 @@ public override SyncResponseHandlingResult HandleResponse(HeadersSyncBatch? batc if (_logger.IsTrace) _logger.Trace($"{batch} - came back EMPTY"); _pending.Enqueue(batch); batch.MarkHandlingEnd(); - return batch.ResponseSourcePeer == null ? SyncResponseHandlingResult.NotAssigned : SyncResponseHandlingResult.NoProgress; + return batch.ResponseSourcePeer is null ? SyncResponseHandlingResult.NotAssigned : SyncResponseHandlingResult.NoProgress; } try @@ -338,7 +338,7 @@ private static HeadersSyncBatch BuildDependentBatch(HeadersSyncBatch batch, long protected virtual int InsertHeaders(HeadersSyncBatch batch) { - if (batch.Response == null) + if (batch.Response is null) { return 0; } diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/MemorySizeEstimator.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/MemorySizeEstimator.cs index 91243d894d2..18d50fea94c 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/MemorySizeEstimator.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/MemorySizeEstimator.cs @@ -24,7 +24,7 @@ internal static class MemorySizeEstimator { public static long EstimateSize(Block? block) { - if (block == null) + if (block is null) { return 0; } @@ -37,7 +37,7 @@ public static long EstimateSize(Block? block) public static long EstimateSize(TxReceipt? txReceipt) { - if (txReceipt == null) + if (txReceipt is null) { return 0; } @@ -53,7 +53,7 @@ public static long EstimateSize(TxReceipt? txReceipt) public static long EstimateSize(BlockBody? blockBody) { - if (blockBody == null) + if (blockBody is null) { return 0; } @@ -82,7 +82,7 @@ public static long EstimateSize(BlockBody? blockBody) /// public static long EstimateSize(BlockHeader? header) { - if (header == null) + if (header is null) { return 8; } @@ -92,7 +92,7 @@ public static long EstimateSize(BlockHeader? header) public static long EstimateSize(Transaction? transaction) { - if (transaction == null) + if (transaction is null) { return 8; } diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/ReceiptsSyncFeed.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/ReceiptsSyncFeed.cs index fca9540f856..4a0ba3f7574 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/ReceiptsSyncFeed.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/ReceiptsSyncFeed.cs @@ -170,7 +170,7 @@ public override SyncResponseHandlingResult HandleResponse(ReceiptsSyncBatch? bat private bool TryPrepareReceipts(BlockInfo blockInfo, TxReceipt[] receipts, out TxReceipt[]? preparedReceipts) { BlockHeader? header = _blockTree.FindHeader(blockInfo.BlockHash); - if (header == null) + if (header is null) { if (_logger.IsWarn) _logger.Warn("Could not find header for requested blockhash."); preparedReceipts = null; @@ -209,7 +209,7 @@ private int InsertReceipts(ReceiptsSyncBatch batch) { TxReceipt[]? prepared = null; // last batch - if (blockInfo == null) + if (blockInfo is null) { break; } @@ -218,7 +218,7 @@ private int InsertReceipts(ReceiptsSyncBatch batch) if (isValid) { Block block = _blockTree.FindBlock(blockInfo.BlockHash); - if (block == null) + if (block is null) { if (blockInfo.BlockNumber >= _barrier) { diff --git a/src/Nethermind/Nethermind.Synchronization/FastSync/DependentItemComparer.cs b/src/Nethermind/Nethermind.Synchronization/FastSync/DependentItemComparer.cs index d48f25e880e..4a202c1f0a5 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastSync/DependentItemComparer.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastSync/DependentItemComparer.cs @@ -32,7 +32,7 @@ public static DependentItemComparer Instance { get { - if (_instance == null) + if (_instance is null) { LazyInitializer.EnsureInitialized(ref _instance, () => new DependentItemComparer()); } diff --git a/src/Nethermind/Nethermind.Synchronization/FastSync/PendingSyncItems.cs b/src/Nethermind/Nethermind.Synchronization/FastSync/PendingSyncItems.cs index 33ecc1704b4..1df158f3323 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastSync/PendingSyncItems.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastSync/PendingSyncItems.cs @@ -93,12 +93,12 @@ public void PushToSelectedStream(StateSyncItem stateSyncItem, decimal progress) { StateItemsPriority0.TryPeek(out StateSyncItem? node); - if (node == null) + if (node is null) { StateItemsPriority1.TryPeek(out node); } - if (node == null) + if (node is null) { StateItemsPriority2.TryPeek(out node); } diff --git a/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs b/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs index 915214f2c33..bc7d93f95c4 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs @@ -158,7 +158,7 @@ void AddAgainAllItems() _handleWatch.Restart(); - bool isMissingRequestData = batch.RequestedNodes == null; + bool isMissingRequestData = batch.RequestedNodes is null; if (isMissingRequestData) { _hintsToResetRoot++; @@ -169,7 +169,7 @@ void AddAgainAllItems() return isMissingRequestData ? SyncResponseHandlingResult.InternalError : SyncResponseHandlingResult.NotAssigned; } - if (batch.Responses == null) + if (batch.Responses is null) { AddAgainAllItems(); if (_logger.IsTrace) _logger.Trace("Batch was not assigned to any peer."); @@ -194,7 +194,7 @@ shorter than the request */ /* if the peer does not have details of this particular node */ byte[] currentResponseItem = batch.Responses[i]; - if (currentResponseItem == null) + if (currentResponseItem is null) { AddNodeToPending(batch.RequestedNodes[i], null, "missing", true); continue; @@ -356,7 +356,7 @@ public void ResetStateRoot(SyncFeedState currentState) public void ResetStateRootToBestSuggested(SyncFeedState currentState) { BlockHeader bestSuggested = _blockTree.BestSuggestedHeader; - if (bestSuggested == null || bestSuggested.Number == 0) + if (bestSuggested is null || bestSuggested.Number == 0) { return; } diff --git a/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs b/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs index 0abd42494b9..bd6744c7404 100644 --- a/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs +++ b/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs @@ -104,7 +104,7 @@ private void SetMaxSectionIndex(long sectionIndex) private static Keccak GetRootHash(IKeyValueStore db, long sectionIndex) { byte[]? hash = db[GetRootHashKey(sectionIndex)]; - return hash == null ? EmptyTreeHash : new Keccak(hash); + return hash is null ? EmptyTreeHash : new Keccak(hash); } private static Keccak GetMaxRootHash(IKeyValueStore db) @@ -126,7 +126,7 @@ public void Set(BlockHeader header) public (Keccak?, UInt256) Get(Span key) { byte[]? val = base.Get(key); - if (val == null) + if (val is null) { throw new InvalidDataException("Missing CHT data"); } diff --git a/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs b/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs index 885590c77b5..1ea82fab434 100644 --- a/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs +++ b/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs @@ -163,7 +163,7 @@ public void Update() bool inBeaconControl = _beaconSyncStrategy.ShouldBeInBeaconModeControl(); (UInt256? peerDifficulty, long? peerBlock) = ReloadDataFromPeers(); // if there are no peers that we could use then we cannot sync - if (peerDifficulty == null || peerBlock == null || peerBlock == 0) + if (peerDifficulty is null || peerBlock is null || peerBlock == 0) { newModes = inBeaconControl ? SyncMode.WaitingForBlock : SyncMode.Disconnected; reason = "No Useful Peers"; diff --git a/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncDispatcher.cs b/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncDispatcher.cs index 89b563e4f34..5a9122ab0ce 100644 --- a/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncDispatcher.cs +++ b/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncDispatcher.cs @@ -69,7 +69,7 @@ public async Task Start(CancellationToken cancellationToken) if (currentStateLocal == SyncFeedState.Dormant) { if (Logger.IsDebug) Logger.Debug($"{GetType().Name} is going to sleep."); - if (dormantTaskLocal == null) + if (dormantTaskLocal is null) { if (Logger.IsWarn) Logger.Warn("Dormant task is NULL when trying to await it"); } @@ -81,7 +81,7 @@ public async Task Start(CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); T request = await (Feed.PrepareRequest(cancellationToken) ?? Task.FromResult(default!)); // just to avoid null refs - if (request == null) + if (request is null) { if (!Feed.IsMultiFeed) { diff --git a/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncProgressResolver.cs b/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncProgressResolver.cs index 9d6c332b50a..c6e8499281e 100644 --- a/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncProgressResolver.cs +++ b/src/Nethermind/Nethermind.Synchronization/ParallelSync/SyncProgressResolver.cs @@ -125,7 +125,7 @@ private long SearchForFullState(BlockHeader startHeader) long bestFullState = 0; for (int i = 0; i < MaxLookupBack; i++) { - if (startHeader == null) + if (startHeader is null) { break; } diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/BySpeedStrategy.cs b/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/BySpeedStrategy.cs index db0dee54922..ba52913f57f 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/BySpeedStrategy.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/BySpeedStrategy.cs @@ -64,11 +64,11 @@ public BySpeedStrategy( List peersAsList = peers.ToList(); long peerCount = peersAsList.Count(); - long noSpeedPeerCount = peersAsList.Count(p => nodeStatsManager.GetOrAdd(p.SyncPeer.Node).GetAverageTransferSpeed(_speedType) == null); + long noSpeedPeerCount = peersAsList.Count(p => nodeStatsManager.GetOrAdd(p.SyncPeer.Node).GetAverageTransferSpeed(_speedType) is null); bool shouldRediscoverSpeed = _random.NextDouble() < _recalculateSpeedProbability; bool shouldDiscoverSpeed = (peerCount - noSpeedPeerCount) < _desiredPeersWithKnownSpeed; - long currentSpeed = currentPeer == null ? nullSpeed : nodeStatsManager.GetOrAdd(currentPeer.SyncPeer.Node).GetAverageTransferSpeed(_speedType) ?? nullSpeed; + long currentSpeed = currentPeer is null ? nullSpeed : nodeStatsManager.GetOrAdd(currentPeer.SyncPeer.Node).GetAverageTransferSpeed(_speedType) ?? nullSpeed; (PeerInfo? Info, long TransferSpeed) bestPeer = (currentPeer, currentSpeed); bool forceTake = false; @@ -80,7 +80,7 @@ public BySpeedStrategy( long? speed = nodeStatsManager.GetOrAdd(info.SyncPeer.Node).GetAverageTransferSpeed(_speedType); long averageTransferSpeed = speed ?? 0; - if (speed == null && shouldDiscoverSpeed) + if (speed is null && shouldDiscoverSpeed) { forceTake = true; } diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/TotalDiffStrategy.cs b/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/TotalDiffStrategy.cs index 880ab5b3ecd..7b453168623 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/TotalDiffStrategy.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/AllocationStrategies/TotalDiffStrategy.cs @@ -49,7 +49,7 @@ public TotalDiffStrategy(IPeerAllocationStrategy strategy, TotalDiffSelectionTyp public PeerInfo? Allocate(PeerInfo? currentPeer, IEnumerable peers, INodeStatsManager nodeStatsManager, IBlockTree blockTree) { UInt256? currentDiffOrNull = blockTree.BestSuggestedHeader?.TotalDifficulty; - if (currentDiffOrNull == null) + if (currentDiffOrNull is null) { return _strategy.Allocate(currentPeer, peers, nodeStatsManager, blockTree); } diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerAllocation.cs b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerAllocation.cs index 9d7b1320d39..45c03f38892 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerAllocation.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerAllocation.cs @@ -75,7 +75,7 @@ public void AllocateBestPeer( public void Cancel() { PeerInfo? current = Current; - if (current == null) + if (current is null) { return; } diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerPool.cs b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerPool.cs index 771d8c83657..b77b313849d 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerPool.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerPool.cs @@ -132,7 +132,7 @@ public void ReportBreachOfProtocol(PeerInfo? peerInfo, string details) public void ReportWeakPeer(PeerInfo? weakPeer, AllocationContexts allocationContexts) { - if (weakPeer == null) + if (weakPeer is null) { /* it may have just got disconnected and in such case the allocation would be nullified * in such case there is no need to talk about whether the peer is good or bad @@ -303,7 +303,7 @@ public void RemovePeer(ISyncPeer syncPeer) } PublicKey id = syncPeer.Node.Id; - if (id == null) + if (id is null) { if (_logger.IsDebug) _logger.Debug("Peer ID was null when removing peer"); return; @@ -590,7 +590,7 @@ private int DropWorstPeer() continue; } - if (worstPeer == null) + if (worstPeer is null) { worstPeer = peerInfo; } @@ -647,7 +647,7 @@ await firstToComplete.ContinueWith( { delaySource.Cancel(); BlockHeader? header = getHeadHeaderTask.Result; - if (header == null) + if (header is null) { ReportRefreshFailed(syncPeer, "null response"); return; diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs index 06b55758f97..c69777ef459 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs @@ -129,7 +129,7 @@ private void AddPeerInfo(PeerInfo peerInfo) private string GetPaddedAverageTransferSpeed(INodeStats nodeStats, TransferSpeedType transferSpeedType) { long? speed = nodeStats.GetAverageTransferSpeed(transferSpeedType); - if (speed == null) + if (speed is null) { return " "; } diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/ProgressTracker.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/ProgressTracker.cs index b7aca4fb25a..e9acbd1e846 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/ProgressTracker.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/ProgressTracker.cs @@ -53,7 +53,7 @@ public ProgressTracker(IBlockTree blockTree, IDb db, ILogManager logManager) public bool CanSync() { BlockHeader? header = _pivot.GetPivotHeader(); - if (header == null || header.Number == 0) + if (header is null || header.Number == 0) { if (_logger.IsInfo) _logger.Info($"No Best Suggested Header available. Snap Sync not started."); diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs index d7b7ae7db35..b3e7bbf8b89 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs @@ -122,7 +122,7 @@ private static (AddRangeResult result, IList sortedBoundaryList, bool return (AddRangeResult.OK, null, false); } - if (tree == null) + if (tree is null) { throw new ArgumentNullException(nameof(tree)); } @@ -253,7 +253,7 @@ private static Dictionary CreateProofDict(byte[][] proofs, ITr private static void StitchBoundaries(IList sortedBoundaryList, ITrieStore store) { - if (sortedBoundaryList == null || sortedBoundaryList.Count == 0) + if (sortedBoundaryList is null || sortedBoundaryList.Count == 0) { return; } diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapSyncFeed.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapSyncFeed.cs index e5f9532e630..ed8f0b49d0d 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapSyncFeed.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapSyncFeed.cs @@ -62,7 +62,7 @@ public SnapSyncFeed(ISyncModeSelector syncModeSelector, ISnapProvider snapProvid { (SnapSyncBatch request, bool finished) = _snapProvider.GetNextRequest(); - if (request == null) + if (request is null) { if (finished) { @@ -83,7 +83,7 @@ public SnapSyncFeed(ISyncModeSelector syncModeSelector, ISnapProvider snapProvid public override SyncResponseHandlingResult HandleResponse(SnapSyncBatch? batch, PeerInfo peer) { - if (batch == null) + if (batch is null) { if (_logger.IsError) _logger.Error("Received empty batch as a response"); return SyncResponseHandlingResult.InternalError; @@ -111,7 +111,7 @@ public override SyncResponseHandlingResult HandleResponse(SnapSyncBatch? batch, { _snapProvider.RetryRequest(batch); - if (peer == null) + if (peer is null) { return SyncResponseHandlingResult.NotAssigned; } @@ -127,7 +127,7 @@ public override SyncResponseHandlingResult HandleResponse(SnapSyncBatch? batch, public SyncResponseHandlingResult AnalyzeResponsePerPeer(AddRangeResult result, PeerInfo peer) { - if (peer == null) + if (peer is null) { return SyncResponseHandlingResult.OK; } diff --git a/src/Nethermind/Nethermind.Synchronization/StateSync/StateSyncDispatcher.cs b/src/Nethermind/Nethermind.Synchronization/StateSync/StateSyncDispatcher.cs index 78599ac243d..133a89e953f 100644 --- a/src/Nethermind/Nethermind.Synchronization/StateSync/StateSyncDispatcher.cs +++ b/src/Nethermind/Nethermind.Synchronization/StateSync/StateSyncDispatcher.cs @@ -40,7 +40,7 @@ public StateSyncDispatcher(ISyncFeed syncFeed, ISyncPeerPool syn protected override async Task Dispatch(PeerInfo peerInfo, StateSyncBatch batch, CancellationToken cancellationToken) { - if (batch?.RequestedNodes == null || batch.RequestedNodes.Length == 0) + if (batch?.RequestedNodes is null || batch.RequestedNodes.Length == 0) { return; } diff --git a/src/Nethermind/Nethermind.Synchronization/SyncServer.cs b/src/Nethermind/Nethermind.Synchronization/SyncServer.cs index 7815778f543..3cb17a12a7b 100644 --- a/src/Nethermind/Nethermind.Synchronization/SyncServer.cs +++ b/src/Nethermind/Nethermind.Synchronization/SyncServer.cs @@ -112,7 +112,7 @@ public BlockHeader? Head { get { - if (_blockTree.Head == null) + if (_blockTree.Head is null) { return null; } @@ -146,12 +146,12 @@ public void AddNewBlock(Block block, ISyncPeer nodeWhoSentTheBlock) if (!_gossipPolicy.CanGossipBlocks) return; if (block.Difficulty == 0) return; // don't gossip post merge blocks - if (block.TotalDifficulty == null) + if (block.TotalDifficulty is null) { throw new InvalidDataException("Cannot add a block with unknown total difficulty"); } - if (block.Hash == null) + if (block.Hash is null) { throw new InvalidDataException("Cannot add a block with unknown hash"); } @@ -411,7 +411,7 @@ public BlockHeader[] FindHeaders(Keccak hash, int numberOfBlocks, int skip, bool values[i] = _stateDb[keys[i].Bytes]; } - if (values[i] == null && (includedTypes & NodeDataType.Code) == NodeDataType.Code) + if (values[i] is null && (includedTypes & NodeDataType.Code) == NodeDataType.Code) { values[i] = _codeDb[keys[i].Bytes]; } @@ -497,7 +497,7 @@ public Task BuildCHT() { lock (_chtLock) { - if (_cht == null) + if (_cht is null) { throw new InvalidAsynchronousStateException("CHT reference is null when building CHT."); } diff --git a/src/Nethermind/Nethermind.Trie/NodeCommitInfo.cs b/src/Nethermind/Nethermind.Trie/NodeCommitInfo.cs index 75b2b15e68f..8ff9fb947cc 100644 --- a/src/Nethermind/Nethermind.Trie/NodeCommitInfo.cs +++ b/src/Nethermind/Nethermind.Trie/NodeCommitInfo.cs @@ -25,9 +25,9 @@ public NodeCommitInfo( public int ChildPositionAtParent { get; } - public bool IsEmptyBlockMarker => Node == null; + public bool IsEmptyBlockMarker => Node is null; - public bool IsRoot => !IsEmptyBlockMarker && NodeParent == null; + public bool IsRoot => !IsEmptyBlockMarker && NodeParent is null; public override string ToString() { diff --git a/src/Nethermind/Nethermind.Trie/TreeDumper.cs b/src/Nethermind/Nethermind.Trie/TreeDumper.cs index d6cac824bd1..565d8e0c4d4 100644 --- a/src/Nethermind/Nethermind.Trie/TreeDumper.cs +++ b/src/Nethermind/Nethermind.Trie/TreeDumper.cs @@ -51,7 +51,7 @@ public void VisitTree(Keccak rootHash, TrieVisitContext trieVisitContext) private string GetPrefix(TrieVisitContext context) => string.Concat($"{GetIndent(context.Level)}", context.IsStorage ? "STORAGE " : string.Empty, $"{GetChildIndex(context)}"); private string GetIndent(int level) => new('+', level * 2); - private string GetChildIndex(TrieVisitContext context) => context.BranchChildIndex == null ? string.Empty : $"{context.BranchChildIndex:x2} "; + private string GetChildIndex(TrieVisitContext context) => context.BranchChildIndex is null ? string.Empty : $"{context.BranchChildIndex:x2} "; public void VisitMissingNode(Keccak nodeHash, TrieVisitContext trieVisitContext) { diff --git a/src/Nethermind/Nethermind.Trie/TrieNode.Visitor.cs b/src/Nethermind/Nethermind.Trie/TrieNode.Visitor.cs index 868245d209b..9a2a7bcffe9 100644 --- a/src/Nethermind/Nethermind.Trie/TrieNode.Visitor.cs +++ b/src/Nethermind/Nethermind.Trie/TrieNode.Visitor.cs @@ -137,7 +137,7 @@ void VisitMultiThread(ITreeVisitor treeVisitor, ITrieNodeResolver trieNodeResolv { visitor.VisitExtension(this, trieVisitContext); TrieNode child = GetChild(nodeResolver, 0); - if (child == null) + if (child is null) { throw new InvalidDataException($"Child of an extension {Key} should not be null."); } diff --git a/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs b/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs index 3f63adb42df..46bd71c025f 100644 --- a/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs +++ b/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs @@ -117,7 +117,7 @@ public IDictionary GetBucketSnapshot(Predicate? [MethodImpl(MethodImplOptions.Synchronized)] public TValue[] GetBucketSnapshot(TGroupKey group) { - if (group == null) throw new ArgumentNullException(nameof(group)); + if (group is null) throw new ArgumentNullException(nameof(group)); return _buckets.TryGetValue(group, out EnhancedSortedSet bucket) ? bucket.ToArray() : Array.Empty(); } @@ -127,7 +127,7 @@ public TValue[] GetBucketSnapshot(TGroupKey group) [MethodImpl(MethodImplOptions.Synchronized)] public int GetBucketCount(TGroupKey group) { - if (group == null) throw new ArgumentNullException(nameof(group)); + if (group is null) throw new ArgumentNullException(nameof(group)); return _buckets.TryGetValue(group, out EnhancedSortedSet bucket) ? bucket.Count : 0; } @@ -386,7 +386,7 @@ public void UpdatePool(Func, IEnumerable<( [MethodImpl(MethodImplOptions.Synchronized)] public void UpdateGroup(TGroupKey groupKey, Func, IEnumerable<(TValue Tx, Action? Change)>> changingElements) { - if (groupKey == null) throw new ArgumentNullException(nameof(groupKey)); + if (groupKey is null) throw new ArgumentNullException(nameof(groupKey)); if (_buckets.TryGetValue(groupKey, out EnhancedSortedSet bucket)) { UpdateGroup(groupKey, bucket, changingElements); diff --git a/src/Nethermind/Nethermind.TxPool/TxPool.cs b/src/Nethermind/Nethermind.TxPool/TxPool.cs index 866facfc85f..ed7ff4f9282 100644 --- a/src/Nethermind/Nethermind.TxPool/TxPool.cs +++ b/src/Nethermind/Nethermind.TxPool/TxPool.cs @@ -365,7 +365,7 @@ private AcceptTxResult AddCore(Transaction tx, bool isPersistentBroadcast) } else { - if (previousTxBottleneck == null) + if (previousTxBottleneck is null) { previousTxBottleneck = tx.CalculateAffordableGasPrice(_specProvider.GetCurrentHeadSpec().IsEip1559Enabled, _headInfo.CurrentBaseFee, balance); diff --git a/src/Nethermind/Nethermind.TxPool/TxSealer.cs b/src/Nethermind/Nethermind.TxPool/TxSealer.cs index 4c2b2c78643..c19e9486172 100644 --- a/src/Nethermind/Nethermind.TxPool/TxSealer.cs +++ b/src/Nethermind/Nethermind.TxPool/TxSealer.cs @@ -36,7 +36,7 @@ public TxSealer(ITxSigner txSigner, ITimestamper timestamper) public virtual ValueTask Seal(Transaction tx, TxHandlingOptions txHandlingOptions) { bool allowChangeExistingSignature = (txHandlingOptions & TxHandlingOptions.AllowReplacingSignature) == TxHandlingOptions.AllowReplacingSignature; - if (tx.Signature == null || allowChangeExistingSignature) + if (tx.Signature is null || allowChangeExistingSignature) { _txSigner.Sign(tx); } diff --git a/src/Nethermind/Nethermind.Wallet/DevKeyStoreWallet.cs b/src/Nethermind/Nethermind.Wallet/DevKeyStoreWallet.cs index 2f31a2d8af8..c7d789a5dca 100644 --- a/src/Nethermind/Nethermind.Wallet/DevKeyStoreWallet.cs +++ b/src/Nethermind/Nethermind.Wallet/DevKeyStoreWallet.cs @@ -109,7 +109,7 @@ public Signature Sign(Keccak message, Address address, SecureString passphrase) } else { - if (passphrase == null) throw new SecurityException("Passphrase missing when trying to sign a message"); + if (passphrase is null) throw new SecurityException("Passphrase missing when trying to sign a message"); key = _keyStore.GetKey(address, passphrase).PrivateKey; } diff --git a/src/Nethermind/Nethermind.Wallet/ProtectedKeyStoreWallet.cs b/src/Nethermind/Nethermind.Wallet/ProtectedKeyStoreWallet.cs index 3971aa15fb3..df652821476 100644 --- a/src/Nethermind/Nethermind.Wallet/ProtectedKeyStoreWallet.cs +++ b/src/Nethermind/Nethermind.Wallet/ProtectedKeyStoreWallet.cs @@ -102,7 +102,7 @@ public bool LockAccount(Address address) public Signature Sign(Keccak message, Address address, SecureString passphrase) => SignCore(message, address, () => { - if (passphrase == null) throw new SecurityException("Passphrase missing when trying to sign a message"); + if (passphrase is null) throw new SecurityException("Passphrase missing when trying to sign a message"); return _keyStore.GetKey(address, passphrase).PrivateKey; });