From 88d28e5a59cf1aed66ab717d8b667cd389b8034f Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:30:31 +0000 Subject: [PATCH 1/9] Make methods static and/or readonly --- .../Json/AbiDefinitionParserTests.cs | 4 +- src/Nethermind/Nethermind.Abi/AbiTuple.cs | 2 +- ...sts.TestAccountAbstractionRpcBlockchain.cs | 2 +- .../AccountAbstractionRpcModuleTests.cs | 2 +- .../AccountAbstractionPlugin.cs | 4 +- .../UserOperationsMessageSerializer.cs | 2 +- .../Source/PaymasterThrottler.cs | 2 +- .../Source/UserOperationTxSource.cs | 2 +- .../Receipts/ReceiptsIteratorTests.cs | 2 +- .../Blocks/BlockStore.cs | 2 +- .../Contracts/CallableContract.cs | 2 +- .../Contracts/Contract.ConstantContract.cs | 2 +- .../Contracts/Json/AbiDefinitionParser.cs | 4 +- .../ReadOnlyBlockTree.cs | 2 +- .../Receipts/NullReceiptStorage.cs | 2 +- .../Receipts/PersistentReceiptStorage.cs | 4 +- .../Receipts/ReceiptsIterator.cs | 8 ++-- .../Nethermind.Cli/Console/CliConsole.cs | 4 +- .../Console/ColorfulCliConsole.cs | 2 +- .../Nethermind.Cli/Modules/NodeCliModule.cs | 2 +- .../Nethermind.Cli/Modules/SystemCliModule.cs | 4 +- .../Nethermind.Cli/Modules/Web3CliModule.cs | 2 +- .../AuRaStepCalculator.cs | 2 +- .../TxPriorityContract.Destination.cs | 8 ++-- .../Contracts/TxPriorityContract.cs | 2 +- .../Rewards/AuRaRewardCalculator.cs | 2 +- .../Rewards/StaticRewardCalculator.cs | 2 +- .../Transactions/TxPermissionFilter.cs | 2 +- .../Validators/PendingValidatorsDecoder.cs | 4 +- .../SnapshotDecoder.cs | 20 ++++---- .../SnapshotManager.cs | 2 +- .../Nethermind.Consensus.Ethash/Ethash.cs | 2 +- .../EthashDifficultyCalculator.cs | 4 +- ...cessor.BlockProductionTransactionPicker.cs | 2 +- .../Producers/TxPoolTxSource.cs | 2 +- .../Rewards/RewardCalculator.cs | 2 +- .../Validators/NeverValidBlockValidator.cs | 2 +- .../Nethermind.Core.Test/SignerTests.cs | 2 +- src/Nethermind/Nethermind.Core/Address.cs | 18 +++---- src/Nethermind/Nethermind.Core/Bloom.cs | 24 +++++----- .../Nethermind.Core/Buffers/CappedArray.cs | 13 +++-- .../Caching/MemCountingCache.cs | 2 +- .../Collections/ArrayPoolList.cs | 6 +-- .../LockableConcurrentDictionary.cs | 2 +- .../Collections/SpanDictionary.cs | 24 +++++----- .../Nethermind.Core/Crypto/Hash256.cs | 24 +++++----- .../Nethermind.Core/Eip2930/AccessList.cs | 17 ++++--- .../Nethermind.Core/Extensions/Bytes.cs | 2 +- src/Nethermind/Nethermind.Crypto/Ecdsa.cs | 2 +- .../Nethermind.Crypto/EciesCipher.cs | 6 +-- src/Nethermind/Nethermind.Crypto/Keccak512.cs | 6 +-- .../Nethermind.Crypto/OptimizedKdf.cs | 2 +- .../ProtectedData.AspNetWrapper.cs | 4 +- .../Nethermind.Db.Rocks/DbOnTheRocks.cs | 8 ++-- .../Statistics/DbMetricsUpdater.cs | 2 +- .../Nethermind.Db/Blooms/BloomStorage.cs | 2 +- .../Nethermind.Db/StandardDbInitializer.cs | 2 +- src/Nethermind/Nethermind.Evm/EvmStack.cs | 2 +- .../JavaScript/GethLikeJavaScriptTxTracer.cs | 2 +- .../ParityAccountStateChangeJsonConverter.cs | 4 +- .../Tracing/ParityStyle/ParityLikeTxTracer.cs | 4 +- .../ParityStyle/ParityTraceActionConverter.cs | 4 +- .../Nethermind.Evm/TransactionSubstate.cs | 2 +- .../Nethermind.Facade/Eth/EthSyncingInfo.cs | 2 +- .../Nethermind.Facade/Eth/SyncingResult.cs | 2 +- .../Filters/FilterManager.cs | 2 +- .../Nethermind.Facade/Filters/FilterStore.cs | 4 +- .../Nethermind.Facade/Filters/LogFinder.cs | 2 +- .../NodeHealthService.cs | 2 +- src/Nethermind/Nethermind.Hive/HiveRunner.cs | 4 +- .../Nethermind.Init/Cpu/SectionsHelper.cs | 6 ++- .../Nethermind.Init/MemoryHintMan.cs | 16 +++---- .../Steps/Migrations/BloomMigration.cs | 2 +- .../Steps/Migrations/ReceiptMigration.cs | 4 +- .../Nethermind.Init/VersionToMetrics.cs | 4 +- .../TraceStoreRpcModule.cs | 4 +- .../Data/AccessListItemForRpc.cs | 4 +- .../Nethermind.JsonRpc/JsonRpcLocalStats.cs | 2 +- .../Nethermind.JsonRpc/JsonRpcService.cs | 6 +-- .../Eth/EthRpcModule.TransactionExecutor.cs | 2 +- .../Modules/Eth/EthRpcModule.cs | 2 +- .../Eth/FeeHistory/FeeHistoryOracle.cs | 2 +- .../Modules/Eth/GasPrice/GasPriceOracle.cs | 4 +- .../Modules/Proof/ProofRpcModule.cs | 2 +- .../Modules/RpcModuleProvider.cs | 2 +- .../Modules/SearchResult.cs | 2 +- .../Subscribe/JsonRpcSubscriptionResponse.cs | 2 +- .../Modules/Trace/TraceRpcModule.cs | 2 +- .../Nethermind.KeyStore/AesEncrypter.cs | 2 +- .../BaseKeyStoreIOSettingsProvider.cs | 2 +- .../Nethermind.Logging.NLog/NLogManager.cs | 10 ++-- .../StackTraceUtils.cs | 2 +- .../Nethermind.Logging/SimpleConsoleLogger.cs | 2 +- .../BlockProduction/Boost/BoostRelay.cs | 2 +- .../Nethermind.Merkleization/Merkleizer.cs | 4 +- .../Execution/CallTxBundleExecutor.cs | 2 +- .../Nethermind.Mev/Source/BundlePool.cs | 6 +-- .../Serializers/DiscoveryMsgSerializerBase.cs | 2 +- .../Serializers/NeighborsMsgSerializer.cs | 4 +- .../Serializers/PingMsgSerializer.cs | 2 +- .../Serializers/PongMsgSerializer.cs | 2 +- .../Nethermind.Network.Dns/EnrDiscovery.cs | 2 +- .../Nethermind.Network.Dns/EnrRecordParser.cs | 2 +- .../Nethermind.Network.Dns/EnrTreeParser.cs | 2 +- src/Nethermind/Nethermind.Network/ForkInfo.cs | 2 +- .../Nethermind.Network/NetworkNodeDecoder.cs | 2 +- .../AddCapabilityMessageSerializer.cs | 2 +- .../Messages/DisconnectMessageSerializer.cs | 2 +- .../P2P/Messages/HelloMessageSerializer.cs | 2 +- .../Subprotocols/Eth/PooledTxsRequestor.cs | 4 +- .../Messages/TransactionsMessageSerializer.cs | 2 +- .../Messages/GetReceiptsMessageSerializer.cs | 2 +- .../PooledTransactionsMessageSerializer.cs | 2 +- .../Subprotocols/Les/LesProtocolHandler.cs | 2 +- .../Les/Messages/AnnounceMessageSerializer.cs | 2 +- .../GetHelperTrieProofsMessageSerializer.cs | 2 +- .../HelperTrieProofsMessageSerializer.cs | 2 +- .../Messages/ByteCodesMessageSerializer.cs | 2 +- .../Messages/GetTrieNodesMessageSerializer.cs | 2 +- .../StorageRangesMessageSerializer.cs | 2 +- .../Messages/TrieNodesMessageSerializer.cs | 2 +- .../Subprotocols/Snap/SnapProtocolHandler.cs | 2 +- .../Nethermind.Network/ProtocolValidator.cs | 2 +- .../Rlpx/FrameMacProcessor.cs | 2 +- .../Handshake/AuthEip8MessageSerializer.cs | 2 +- .../Rlpx/ZeroPacketSplitter.cs | 2 +- .../StaticNodes/StaticNodesManager.cs | 4 +- .../BufferSegmentStack.cs | 2 +- .../BlockDecoder.cs | 2 +- .../BlockInfoDecoder.cs | 2 +- .../ChainLevelDecoder.cs | 4 +- .../CompactLogEntryDecoder.cs | 10 ++-- .../CompactReceiptStorageDecoder.cs | 14 +++--- .../KeccakDecoder.cs | 2 +- .../ReceiptArrayStorageDecoder.cs | 4 +- .../ReceiptMessageDecoder.cs | 4 +- .../ReceiptRecoveryBlock.cs | 6 +-- .../ReceiptStorageDecoder.cs | 4 +- .../Nethermind.Serialization.Rlp/Rlp.cs | 16 +++---- .../Nethermind.Serialization.Rlp/TxDecoder.cs | 48 +++++++++---------- .../Nethermind.Specs/FrontierSpecProvider.cs | 2 +- .../Nethermind.State/StateProvider.cs | 2 +- .../Blocks/BlockDownloader.cs | 4 +- .../Blocks/BlocksSyncPeerSelectionStrategy.cs | 2 +- .../Blocks/SyncBatchSize.cs | 4 +- .../LesSync/CanonicalHashTrie.cs | 8 ++-- .../LesSync/ChtDecoder.cs | 2 +- .../ParallelSync/MultiSyncModeSelector.cs | 8 ++-- .../Peers/PeerInfo.cs | 2 +- .../Peers/SyncPeersReport.cs | 6 +-- .../SnapSync/SnapProviderHelper.cs | 8 ++-- .../Nethermind.Synchronization/SyncServer.cs | 4 +- .../Synchronizer.cs | 2 +- src/Nethermind/Nethermind.Trie/Nibbles.cs | 2 +- .../Nethermind.Trie/PatriciaTree.cs | 2 +- .../Nethermind.Trie/Pruning/NullTrieStore.cs | 4 +- .../Pruning/ReadOnlyTrieStore.cs | 2 +- src/Nethermind/Nethermind.Trie/TreeDumper.cs | 8 ++-- .../Nethermind.Trie/TrieNode.Decoder.cs | 2 +- src/Nethermind/Nethermind.Trie/TrieNode.cs | 2 +- .../Nethermind.Trie/VisitContext.cs | 6 +-- .../Nethermind.TxPool/BlobTxStorage.cs | 6 +-- .../Nethermind.TxPool/LightTxDecoder.cs | 6 +-- .../Nethermind.TxPool/NonceLocker.cs | 2 +- .../Nethermind.TxPool/NullTxPool.cs | 2 +- 165 files changed, 357 insertions(+), 349 deletions(-) diff --git a/src/Nethermind/Nethermind.Abi.Test/Json/AbiDefinitionParserTests.cs b/src/Nethermind/Nethermind.Abi.Test/Json/AbiDefinitionParserTests.cs index 933838bfccd..86ea610c66b 100644 --- a/src/Nethermind/Nethermind.Abi.Test/Json/AbiDefinitionParserTests.cs +++ b/src/Nethermind/Nethermind.Abi.Test/Json/AbiDefinitionParserTests.cs @@ -20,9 +20,9 @@ public class AbiDefinitionParserTests public void Can_load_contract(Type contractType) { var parser = new AbiDefinitionParser(); - var json = parser.LoadContract(contractType); + var json = AbiDefinitionParser.LoadContract(contractType); var contract = parser.Parse(json); - var serialized = parser.Serialize(contract); + var serialized = AbiDefinitionParser.Serialize(contract); JToken.Parse(serialized).Should().ContainSubtree(json); } } diff --git a/src/Nethermind/Nethermind.Abi/AbiTuple.cs b/src/Nethermind/Nethermind.Abi/AbiTuple.cs index 3a6ec98590c..e35d58d3c7d 100644 --- a/src/Nethermind/Nethermind.Abi/AbiTuple.cs +++ b/src/Nethermind/Nethermind.Abi/AbiTuple.cs @@ -47,7 +47,7 @@ public override (object, int) Decode(byte[] data, int position, bool packed) public override byte[] Encode(object? arg, bool packed) { - IEnumerable GetEnumerable(ITuple tuple) + static IEnumerable GetEnumerable(ITuple tuple) { for (int i = 0; i < tuple.Length; i++) { diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs index 78ef9773988..c56265edd8a 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.TestAccountAbstractionRpcBlockchain.cs @@ -195,7 +195,7 @@ protected override BlockProcessor CreateBlockProcessor() AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple())); var parser = new AbiDefinitionParser(); - var json = parser.LoadContract(typeof(EntryPoint)); + var json = AbiDefinitionParser.LoadContract(typeof(EntryPoint)); EntryPointContractAbi = parser.Parse(json); foreach (Address entryPoint in entryPointContractAddresses) diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs index fca2101ad3f..b9b1e0947dd 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/AccountAbstractionRpcModuleTests.cs @@ -61,7 +61,7 @@ private AbiDefinition LoadContract(Type contractType) AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple())); var parser = new AbiDefinitionParser(); - var json = parser.LoadContract(contractType); + var json = AbiDefinitionParser.LoadContract(contractType); return parser.Parse(json); } diff --git a/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs b/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs index 8d11df268bb..1f3f1e473c8 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs @@ -386,12 +386,12 @@ public Task InitBlockProducer(IConsensusPlugin consensusPlugin) public bool BundleMiningEnabled => _accountAbstractionConfig.Enabled && (_nethermindApi.Config().IsMining || _nethermindApi.Config().Enabled); public bool Enabled => BundleMiningEnabled && !MevPluginEnabled; // IConsensusWrapperPlugin.Enabled - private AbiDefinition LoadEntryPointContract() + private static AbiDefinition LoadEntryPointContract() { AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple())); AbiDefinitionParser parser = new(); - string json = parser.LoadContract(typeof(EntryPoint)); + string json = AbiDefinitionParser.LoadContract(typeof(EntryPoint)); return parser.Parse(json); } } diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Network/UserOperationsMessageSerializer.cs b/src/Nethermind/Nethermind.AccountAbstraction/Network/UserOperationsMessageSerializer.cs index 1a3e9de316b..33b17626ae9 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Network/UserOperationsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Network/UserOperationsMessageSerializer.cs @@ -43,7 +43,7 @@ public int GetLength(UserOperationsMessage message, out int contentLength) return Rlp.LengthOfSequence(contentLength); } - private UserOperationWithEntryPoint[] DeserializeUOps(NettyRlpStream rlpStream) + private static UserOperationWithEntryPoint[] DeserializeUOps(NettyRlpStream rlpStream) { return Rlp.DecodeArray(rlpStream); } diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Source/PaymasterThrottler.cs b/src/Nethermind/Nethermind.AccountAbstraction/Source/PaymasterThrottler.cs index 471c0058890..646d9ea795f 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Source/PaymasterThrottler.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Source/PaymasterThrottler.cs @@ -165,7 +165,7 @@ protected void UpdateUserOperationMaps(object source, EventArgs args) * @param dividend: Dividend, or numerator of the division. * @param divisor: Divisor, or denominator of the division. */ - private uint FloorDivision(uint dividend, uint divisor) + private static uint FloorDivision(uint dividend, uint divisor) { if (divisor == 0) throw new Exception("PaymasterThrottler: Divisor cannot be == 0"); diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Source/UserOperationTxSource.cs b/src/Nethermind/Nethermind.AccountAbstraction/Source/UserOperationTxSource.cs index 323507e0cc2..ec6def2cd1e 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Source/UserOperationTxSource.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Source/UserOperationTxSource.cs @@ -200,7 +200,7 @@ public IEnumerable GetTransactions(BlockHeader parent, long gasLimi } } - private UInt256 CalculateUserOperationPremiumGasPrice(UserOperation op, UInt256 baseFeePerGas) + private static UInt256 CalculateUserOperationPremiumGasPrice(UserOperation op, UInt256 baseFeePerGas) { return UInt256.Min(op.MaxPriorityFeePerGas, op.MaxFeePerGas - baseFeePerGas); } diff --git a/src/Nethermind/Nethermind.Blockchain.Test/Receipts/ReceiptsIteratorTests.cs b/src/Nethermind/Nethermind.Blockchain.Test/Receipts/ReceiptsIteratorTests.cs index da658279ddc..e56498db73a 100644 --- a/src/Nethermind/Nethermind.Blockchain.Test/Receipts/ReceiptsIteratorTests.cs +++ b/src/Nethermind/Nethermind.Blockchain.Test/Receipts/ReceiptsIteratorTests.cs @@ -112,7 +112,7 @@ private ReceiptsIterator CreateIterator(TxReceipt[] receipts, Block block) false ); - ReceiptsIterator iterator = new ReceiptsIterator(span, blockDb, () => recovery.CreateRecoveryContext(new ReceiptRecoveryBlock(block)), _decoder.GetRefDecoder(span)); + ReceiptsIterator iterator = new ReceiptsIterator(span, blockDb, () => recovery.CreateRecoveryContext(new ReceiptRecoveryBlock(block)), ReceiptArrayStorageDecoder.GetRefDecoder(span)); return iterator; } } diff --git a/src/Nethermind/Nethermind.Blockchain/Blocks/BlockStore.cs b/src/Nethermind/Nethermind.Blockchain/Blocks/BlockStore.cs index e61f76a9486..830223ec0ab 100644 --- a/src/Nethermind/Nethermind.Blockchain/Blocks/BlockStore.cs +++ b/src/Nethermind/Nethermind.Blockchain/Blocks/BlockStore.cs @@ -81,7 +81,7 @@ public void Delete(long blockNumber, Hash256 blockHash) memoryOwner = _blockDb.GetOwnedMemory(blockHash.Bytes); } - return _blockDecoder.DecodeToReceiptRecoveryBlock(memoryOwner, memoryOwner?.Memory ?? Memory.Empty, RlpBehaviors.None); + return BlockDecoder.DecodeToReceiptRecoveryBlock(memoryOwner, memoryOwner?.Memory ?? Memory.Empty, RlpBehaviors.None); } public void Cache(Block block) diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs index 5d3964f7204..54ddaf92945 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/CallableContract.cs @@ -117,7 +117,7 @@ protected bool TryCall(BlockHeader header, string functionName, Address sender, /// Creates account if its not in current state. /// /// State provider. - protected void EnsureSystemAccount(IWorldState stateProvider) + protected static void EnsureSystemAccount(IWorldState stateProvider) { if (!stateProvider.AccountExists(Address.SystemUser)) { diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs index a6011af9a03..2d2255b0045 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/Contract.ConstantContract.cs @@ -81,7 +81,7 @@ public ConstantContract(Contract contract, IReadOnlyTxProcessorSource readOnlyTx public override object[] Call(CallInfo callInfo) { - Hash256 GetState(BlockHeader parentHeader) => parentHeader?.StateRoot ?? Keccak.EmptyTreeHash; + static Hash256 GetState(BlockHeader parentHeader) => parentHeader?.StateRoot ?? Keccak.EmptyTreeHash; lock (_readOnlyTxProcessorSource) { diff --git a/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionParser.cs b/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionParser.cs index 50b1b83f623..60d2e69fe06 100644 --- a/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionParser.cs +++ b/src/Nethermind/Nethermind.Blockchain/Contracts/Json/AbiDefinitionParser.cs @@ -39,13 +39,13 @@ public void RegisterAbiTypeFactory(IAbiTypeFactory abiTypeFactory) _abiTypeFactories.Add(abiTypeFactory); } - public string LoadContract(Type type) + public static string LoadContract(Type type) { using var reader = new StreamReader(LoadResource(type)); return reader.ReadToEnd(); } - public string Serialize(AbiDefinition contract) + public static string Serialize(AbiDefinition contract) { return JsonSerializer.Serialize(contract, SourceGenerationContext.Default.AbiDefinition); } diff --git a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs index 8280eaa4906..ddec2fca480 100644 --- a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs +++ b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs @@ -57,7 +57,7 @@ public BlockHeader? LowestInsertedBeaconHeader public Block Head => _wrapped.Head; public void MarkChainAsProcessed(IReadOnlyList blocks) => throw new InvalidOperationException($"{nameof(ReadOnlyBlockTree)} does not expect {nameof(MarkChainAsProcessed)} calls"); public (BlockInfo Info, ChainLevelInfo Level) GetInfo(long number, Hash256 blockHash) => _wrapped.GetInfo(number, blockHash); - public UInt256? UpdateTotalDifficulty(Block block, UInt256 totalDifficulty) => throw new InvalidOperationException(); + public static UInt256? UpdateTotalDifficulty(Block block, UInt256 totalDifficulty) => throw new InvalidOperationException(); public bool CanAcceptNewBlocks { get; } = false; public async Task Accept(IBlockTreeVisitor blockTreeVisitor, CancellationToken cancellationToken) diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs index 0f8526b68e3..bc50321c05e 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs @@ -37,7 +37,7 @@ public long? LowestInsertedReceiptBlockNumber public long MigratedBlockNumber { get; set; } = 0; - public event EventHandler ReceiptsInserted + public static event EventHandler ReceiptsInserted { add { } remove { } diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs index c35bc4ca19c..ca972f1aa9a 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/PersistentReceiptStorage.cs @@ -233,7 +233,7 @@ public bool TryGetReceiptsIterator(long blockNumber, Hash256 blockHash, out Rece Func recoveryContextFactory = () => null; - if (_storageDecoder.IsCompactEncoding(receiptsData)) + if (ReceiptArrayStorageDecoder.IsCompactEncoding(receiptsData)) { recoveryContextFactory = () => { @@ -248,7 +248,7 @@ public bool TryGetReceiptsIterator(long blockNumber, Hash256 blockHash, out Rece }; } - IReceiptRefDecoder refDecoder = _storageDecoder.GetRefDecoder(receiptsData); + IReceiptRefDecoder refDecoder = ReceiptArrayStorageDecoder.GetRefDecoder(receiptsData); iterator = result ? new ReceiptsIterator(receiptsData, _blocksDb, recoveryContextFactory, refDecoder) : new ReceiptsIterator(); return result; diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs index 141952a117d..269d53a1f43 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/ReceiptsIterator.cs @@ -104,7 +104,7 @@ public void RecoverIfNeeded(ref TxReceiptStructRef current) _recoveryContextConfigured = true; } - public void Dispose() + public readonly void Dispose() { if (_receipts is null && !_decoderContext.Data.IsEmpty) { @@ -113,16 +113,16 @@ public void Dispose() _recoveryContext?.Dispose(); } - public LogEntriesIterator IterateLogs(TxReceiptStructRef receipt) + public readonly LogEntriesIterator IterateLogs(TxReceiptStructRef receipt) { return receipt.Logs is null ? new LogEntriesIterator(receipt.LogsRlp, _receiptRefDecoder) : new LogEntriesIterator(receipt.Logs); } - public Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) + public readonly Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) { return _receiptRefDecoder.DecodeTopics(valueDecoderContext); } - public bool CanDecodeBloom => _receiptRefDecoder == null || _receiptRefDecoder.CanDecodeBloom; + public readonly bool CanDecodeBloom => _receiptRefDecoder == null || _receiptRefDecoder.CanDecodeBloom; } } diff --git a/src/Nethermind/Nethermind.Cli/Console/CliConsole.cs b/src/Nethermind/Nethermind.Cli/Console/CliConsole.cs index 274d5ed0284..0e25699087d 100644 --- a/src/Nethermind/Nethermind.Cli/Console/CliConsole.cs +++ b/src/Nethermind/Nethermind.Cli/Console/CliConsole.cs @@ -40,7 +40,7 @@ public CliConsole() System.Console.WriteLine(); } - protected Terminal GetTerminal() + protected static Terminal GetTerminal() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { @@ -60,7 +60,7 @@ protected Terminal GetTerminal() return Terminal.Unknown; } - protected Terminal PrepareConsoleForTerminal() + protected static Terminal PrepareConsoleForTerminal() { _terminal = GetTerminal(); if (_terminal != Terminal.Powershell) diff --git a/src/Nethermind/Nethermind.Cli/Console/ColorfulCliConsole.cs b/src/Nethermind/Nethermind.Cli/Console/ColorfulCliConsole.cs index 0544a46ebf6..1b77627d8f7 100644 --- a/src/Nethermind/Nethermind.Cli/Console/ColorfulCliConsole.cs +++ b/src/Nethermind/Nethermind.Cli/Console/ColorfulCliConsole.cs @@ -37,7 +37,7 @@ public ColorfulCliConsole(ColorScheme colorScheme) Colorful.Console.WriteLine(); } - private Color GetColor(Color defaultColor) + private static Color GetColor(Color defaultColor) { return _terminal == Terminal.LinuxBash ? _colorScheme.Text : defaultColor; } diff --git a/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs b/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs index 5046f5a2ed2..1afe8fe60ec 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs @@ -14,7 +14,7 @@ namespace Nethermind.Cli.Modules public class NodeCliModule : CliModuleBase { [CliFunction("node", "setNodeKey")] - public string SetNodeKey(string key) + public static string SetNodeKey(string key) { string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, "node.key.plain"); File.WriteAllBytes("node.key.plain", new PrivateKey(Bytes.FromHexString(key)).KeyBytes); diff --git a/src/Nethermind/Nethermind.Cli/Modules/SystemCliModule.cs b/src/Nethermind/Nethermind.Cli/Modules/SystemCliModule.cs index 7e38480f89f..d98b3428e42 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/SystemCliModule.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/SystemCliModule.cs @@ -9,14 +9,14 @@ namespace Nethermind.Cli.Modules public class SystemCliModule : CliModuleBase { [CliFunction("system", "getVariable")] - public string? GetVariable(string name, string defaultValue) + public static string? GetVariable(string name, string defaultValue) { var value = Environment.GetEnvironmentVariable(name.ToUpperInvariant()); return string.IsNullOrWhiteSpace(value) ? value : defaultValue; } [CliProperty("system", "memory")] - public string Memory(string name, string defaultValue) + public static string Memory(string name, string defaultValue) { return $"Allocated: {GC.GetTotalMemory(false)}, GC0: {GC.CollectionCount(0)}, GC1: {GC.CollectionCount(1)}, GC2: {GC.CollectionCount(2)}"; } diff --git a/src/Nethermind/Nethermind.Cli/Modules/Web3CliModule.cs b/src/Nethermind/Nethermind.Cli/Modules/Web3CliModule.cs index 5445e55b7b7..b1635399b7c 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/Web3CliModule.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/Web3CliModule.cs @@ -24,6 +24,6 @@ public Web3CliModule(ICliEngine cliEngine, INodeManager nodeManager) : base(cliE public JsValue ToDecimal(string hex) => Engine.Execute(hex); [CliFunction("web3", "abi")] - public string Abi(string name) => new AbiSignature(name).Address.ToHexString(); + public static string Abi(string name) => new AbiSignature(name).Address.ToHexString(); } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaStepCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaStepCalculator.cs index 3cdbcf38e65..4a16da5fd85 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaStepCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaStepCalculator.cs @@ -106,7 +106,7 @@ private void ValidateStepDurations(IDictionary stepDurations) } } - private IList CreateStepDurations(IDictionary stepDurations) + private static IList CreateStepDurations(IDictionary stepDurations) { StepDurationInfo[] result = new StepDurationInfo[stepDurations.Count]; KeyValuePair firstStep = stepDurations.First(); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.Destination.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.Destination.cs index 099fb2c0b91..6962374c822 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.Destination.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.Destination.cs @@ -58,11 +58,11 @@ public static Destination GetTransactionKey(Transaction tx) return new Destination(tx.To, fnSignature, UInt256.Zero); } - public bool Equals(Destination x, Destination y) => Equals(x.Target, y.Target) && Equals(x.FnSignature, y.FnSignature); + public readonly bool Equals(Destination x, Destination y) => Equals(x.Target, y.Target) && Equals(x.FnSignature, y.FnSignature); - public int GetHashCode(Destination obj) => HashCode.Combine(obj.Target, obj.FnSignature); + public readonly int GetHashCode(Destination obj) => HashCode.Combine(obj.Target, obj.FnSignature); - public override string ToString() => $"{Target}.{FnSignature.ToHexString()}={Value}@{Source}.{BlockNumber}"; + public override readonly string ToString() => $"{Target}.{FnSignature.ToHexString()}={Value}@{Source}.{BlockNumber}"; } public class ValueDestinationMethodComparer : IComparer @@ -93,7 +93,7 @@ public int Compare(Destination x, Destination y) // if same method, we want to treat destinations as same - to be unique int targetComparison = Comparer
.Default.Compare(x.Target, y.Target); if (targetComparison != 0) return targetComparison; - return Bytes.Comparer.Compare(x.FnSignature, y.FnSignature); + return Bytes.BytesComparer.Compare(x.FnSignature, y.FnSignature); } public bool Equals(Destination x, Destination y) => diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.cs index 40d31e2d346..2f6b9bd5c8d 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/TxPriorityContract.cs @@ -88,7 +88,7 @@ public Address[] DecodeAddresses(byte[] data) return (Address[])objects[0]; } - private Destination DecodeDestination(LogEntry log, BlockHeader blockHeader) => + private static Destination DecodeDestination(LogEntry log, BlockHeader blockHeader) => new Destination( new Address(log.Topics[1]), log.Topics[2].Bytes.Slice(0, 4).ToArray(), diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs index ddb4590435d..9a650df6063 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs @@ -66,7 +66,7 @@ public BlockReward[] CalculateRewards(Block block) } - private BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract) + private static BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract) { (Address[] beneficieries, ushort[] kinds) GetBeneficiaries() { diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs index 4f0acedf20e..26f376b5ab6 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/StaticRewardCalculator.cs @@ -24,7 +24,7 @@ public BlockReward[] CalculateRewards(Block block) return new[] { new BlockReward(block.Beneficiary, blockReward.Reward) }; } - private IList CreateBlockRewards(IDictionary? blockRewards) + private static IList CreateBlockRewards(IDictionary? blockRewards) { List blockRewardInfos = new(); if (blockRewards?.Count > 0) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs index 482b4f9d4ad..86dfeeb51e8 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs @@ -92,7 +92,7 @@ public AcceptTxResult IsAllowed(Transaction tx, BlockHeader parentHeader) private ITransactionPermissionContract? GetVersionedContract(BlockHeader blockHeader) => _contract.ResolveVersion(blockHeader); - private ITransactionPermissionContract.TxPermissions GetTxType(Transaction tx, bool contractExists) => + private static ITransactionPermissionContract.TxPermissions GetTxType(Transaction tx, bool contractExists) => tx.IsContractCreation ? ITransactionPermissionContract.TxPermissions.Create : contractExists diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs index 31c721b93eb..2fdbab10969 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/PendingValidatorsDecoder.cs @@ -72,7 +72,7 @@ public void Encode(RlpStream rlpStream, PendingValidators item, RlpBehaviors rlp public int GetLength(PendingValidators item, RlpBehaviors rlpBehaviors) => item is null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total); - private (int Total, int Addresses) GetContentLength(PendingValidators item, RlpBehaviors rlpBehaviors) + private static (int Total, int Addresses) GetContentLength(PendingValidators item, RlpBehaviors rlpBehaviors) { int contentLength = Rlp.LengthOf(item.BlockNumber) + Rlp.LengthOf(item.BlockHash) @@ -84,6 +84,6 @@ public int GetLength(PendingValidators item, RlpBehaviors rlpBehaviors) => return (contentLength, addressesLength); } - private int GetAddressesLength(Address[] addresses) => addresses.Sum(Rlp.LengthOf); + private static int GetAddressesLength(Address[] addresses) => addresses.Sum(Rlp.LengthOf); } } diff --git a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotDecoder.cs b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotDecoder.cs index dc9cb1097e8..87156c1e43b 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotDecoder.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotDecoder.cs @@ -50,7 +50,7 @@ public int GetLength(Snapshot item, RlpBehaviors rlpBehaviors) return Rlp.LengthOfSequence(contentLength); } - private (int contentLength, int signersLength, int votesLength, int tallyLength) GetContentLength(Snapshot item, + private static (int contentLength, int signersLength, int votesLength, int tallyLength) GetContentLength(Snapshot item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { int signersLength = GetSignersContentLength(item.Signers); @@ -66,7 +66,7 @@ public int GetLength(Snapshot item, RlpBehaviors rlpBehaviors) return (contentLength, signersLength, votesLength, tallyLength); } - private SortedList DecodeSigners(RlpStream rlpStream) + private static SortedList DecodeSigners(RlpStream rlpStream) { rlpStream.ReadSequenceLength(); SortedList signers = new SortedList(AddressComparer.Instance); @@ -81,7 +81,7 @@ private SortedList DecodeSigners(RlpStream rlpStream) return signers; } - private List DecodeVotes(RlpStream rlpStream) + private static List DecodeVotes(RlpStream rlpStream) { rlpStream.ReadSequenceLength(); List votes = new List(); @@ -98,7 +98,7 @@ private List DecodeVotes(RlpStream rlpStream) return votes; } - private Dictionary DecodeTally(RlpStream rlpStream) + private static Dictionary DecodeTally(RlpStream rlpStream) { rlpStream.ReadSequenceLength(); Dictionary tally = new Dictionary(); @@ -115,7 +115,7 @@ private Dictionary DecodeTally(RlpStream rlpStream) return tally; } - private int GetSignersContentLength(SortedList signers) + private static int GetSignersContentLength(SortedList signers) { int signerCount = signers.Count; int contentLength = Rlp.LengthOf(signerCount); @@ -129,7 +129,7 @@ private int GetSignersContentLength(SortedList signers) return contentLength; } - private void EncodeSigners(RlpStream stream, SortedList signers, int contentLength) + private static void EncodeSigners(RlpStream stream, SortedList signers, int contentLength) { stream.StartSequence(contentLength); int signerCount = signers.Count; @@ -143,7 +143,7 @@ private void EncodeSigners(RlpStream stream, SortedList signers, } } - private int GetVotesContentLength(List votes) + private static int GetVotesContentLength(List votes) { int voteCount = votes.Count; int contentLength = Rlp.LengthOf(voteCount); @@ -158,7 +158,7 @@ private int GetVotesContentLength(List votes) return contentLength; } - private void EncodeVotes(RlpStream stream, List votes, int contentLength) + private static void EncodeVotes(RlpStream stream, List votes, int contentLength) { stream.StartSequence(contentLength); int voteCount = votes.Count; @@ -174,7 +174,7 @@ private void EncodeVotes(RlpStream stream, List votes, int contentLength) } } - private int GetTallyContentLength(Dictionary tally) + private static int GetTallyContentLength(Dictionary tally) { int tallyCount = tally.Count; int contentLength = Rlp.LengthOf(tallyCount); @@ -189,7 +189,7 @@ private int GetTallyContentLength(Dictionary tally) return contentLength; } - private void EncodeTally(RlpStream stream, Dictionary tally, int contentLength) + private static void EncodeTally(RlpStream stream, Dictionary tally, int contentLength) { stream.StartSequence(contentLength); int tallyCount = tally.Count; diff --git a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs index caf51543a52..5b841911fe8 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs @@ -368,7 +368,7 @@ private bool Cast(Snapshot snapshot, Address address, bool authorize) return true; } - private bool Uncast(Snapshot snapshot, Address address, bool authorize) + private static bool Uncast(Snapshot snapshot, Address address, bool authorize) { // If there's no tally, it's a dangling vote, just drop if (!snapshot.Tally.TryGetValue(address, out Tally? value)) return true; diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/Ethash.cs b/src/Nethermind/Nethermind.Consensus.Ethash/Ethash.cs index f3f5813e2eb..ad57e69a64a 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/Ethash.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/Ethash.cs @@ -260,7 +260,7 @@ private static Hash256 GetTruncatedHash(BlockHeader header) return headerHashed; } - public (byte[], ValueHash256, bool) Hashimoto(ulong fullSize, IEthashDataSet dataSet, Hash256 headerHash, Hash256 expectedMixHash, ulong nonce) + public static (byte[], ValueHash256, bool) Hashimoto(ulong fullSize, IEthashDataSet dataSet, Hash256 headerHash, Hash256 expectedMixHash, ulong nonce) { uint hashesInFull = (uint)(fullSize / HashBytes); // TODO: at current rate would cover around 200 years... but will the block rate change? what with private chains with shorter block times? const uint wordsInMix = MixBytes / WordBytes; diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs b/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs index d996c365e6a..aedb99cc03c 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs @@ -56,7 +56,7 @@ public UInt256 Calculate( timeBomb); } - private BigInteger TimeAdjustment( + private static BigInteger TimeAdjustment( IReleaseSpec spec, BigInteger parentTimestamp, BigInteger currentTimestamp, @@ -80,7 +80,7 @@ private BigInteger TimeAdjustment( return currentTimestamp < parentTimestamp + 7 ? BigInteger.One : BigInteger.MinusOne; } - private BigInteger TimeBomb(IReleaseSpec spec, long blockNumber) + private static BigInteger TimeBomb(IReleaseSpec spec, long blockNumber) { blockNumber -= spec.DifficultyBombDelay; diff --git a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs index 98b4ea3049b..10aa4a3a9e2 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/BlockProcessor.BlockProductionTransactionPicker.cs @@ -84,7 +84,7 @@ public virtual AddingTxEventArgs CanAddTransaction(Block block, Transaction curr return args; } - private bool HasEnoughFounds(Transaction transaction, in UInt256 senderBalance, AddingTxEventArgs e, Block block, IReleaseSpec releaseSpec) + private static bool HasEnoughFounds(Transaction transaction, in UInt256 senderBalance, AddingTxEventArgs e, Block block, IReleaseSpec releaseSpec) { bool eip1559Enabled = releaseSpec.IsEip1559Enabled; UInt256 transactionPotentialCost = transaction.CalculateTransactionPotentialCost(eip1559Enabled, block.BaseFeePerGas); diff --git a/src/Nethermind/Nethermind.Consensus/Producers/TxPoolTxSource.cs b/src/Nethermind/Nethermind.Consensus/Producers/TxPoolTxSource.cs index c91c8461203..15433d060eb 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/TxPoolTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/TxPoolTxSource.cs @@ -102,7 +102,7 @@ public IEnumerable GetTransactions(BlockHeader parent, long gasLimi if (_logger.IsDebug) _logger.Debug($"Potentially selected {selectedTransactions} out of {checkedTransactions} pending transactions checked."); } - private IEnumerable PickBlobTxsBetterThanCurrentTx(ArrayPoolList selectedBlobTxs, Transaction tx, IComparer comparer) + private static IEnumerable PickBlobTxsBetterThanCurrentTx(ArrayPoolList selectedBlobTxs, Transaction tx, IComparer comparer) { while (selectedBlobTxs.Count > 0) { diff --git a/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs b/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs index 48d5f08cbfa..bd0f6cad29e 100644 --- a/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus/Rewards/RewardCalculator.cs @@ -47,7 +47,7 @@ public BlockReward[] CalculateRewards(Block block) return rewards; } - private UInt256 GetUncleReward(UInt256 blockReward, BlockHeader blockHeader, BlockHeader uncle) + private static UInt256 GetUncleReward(UInt256 blockReward, BlockHeader blockHeader, BlockHeader uncle) { return blockReward - ((uint)(blockHeader.Number - uncle.Number) * blockReward >> 3); } diff --git a/src/Nethermind/Nethermind.Consensus/Validators/NeverValidBlockValidator.cs b/src/Nethermind/Nethermind.Consensus/Validators/NeverValidBlockValidator.cs index d70f10eacd9..233119ae23f 100644 --- a/src/Nethermind/Nethermind.Consensus/Validators/NeverValidBlockValidator.cs +++ b/src/Nethermind/Nethermind.Consensus/Validators/NeverValidBlockValidator.cs @@ -7,7 +7,7 @@ namespace Nethermind.Consensus.Validators { public class NeverValidBlockValidator : IBlockValidator { - public bool ValidateHash(BlockHeader header) + public static bool ValidateHash(BlockHeader header) { return false; } diff --git a/src/Nethermind/Nethermind.Core.Test/SignerTests.cs b/src/Nethermind/Nethermind.Core.Test/SignerTests.cs index f517dec5ed0..42e2c036366 100644 --- a/src/Nethermind/Nethermind.Core.Test/SignerTests.cs +++ b/src/Nethermind/Nethermind.Core.Test/SignerTests.cs @@ -47,7 +47,7 @@ public void Decompress() PrivateKey privateKey = Build.A.PrivateKey.TestObject; CompressedPublicKey compressedPublicKey = privateKey.CompressedPublicKey; PublicKey expected = privateKey.PublicKey; - PublicKey actual = ethereumEcdsa.Decompress(compressedPublicKey); + PublicKey actual = EthereumEcdsa.Decompress(compressedPublicKey); Assert.That(actual, Is.EqualTo(expected)); } } diff --git a/src/Nethermind/Nethermind.Core/Address.cs b/src/Nethermind/Nethermind.Core/Address.cs index a2b0d6d1afd..3edfee8d79f 100644 --- a/src/Nethermind/Nethermind.Core/Address.cs +++ b/src/Nethermind/Nethermind.Core/Address.cs @@ -227,7 +227,7 @@ public AddressStructRef(Hash256StructRef keccak) : this(keccak.Bytes.Slice(12, B public AddressStructRef(in ValueHash256 keccak) : this(keccak.BytesAsSpan.Slice(12, ByteLength).ToArray()) { } - public byte this[int index] => Bytes[index]; + public readonly byte this[int index] => Bytes[index]; public static bool IsValidAddress(string hexString, bool allowPrefix) { @@ -279,25 +279,25 @@ public static AddressStructRef FromNumber(in UInt256 number) return new AddressStructRef(addressBytes); } - public override string ToString() => ToString(true, false); + public override readonly string ToString() => ToString(true, false); /// /// https://github.com/ethereum/EIPs/issues/55 /// /// - public string ToString(bool withEip55Checksum) => ToString(true, withEip55Checksum); + public readonly string ToString(bool withEip55Checksum) => ToString(true, withEip55Checksum); /// /// https://github.com/ethereum/EIPs/issues/55 /// /// - public string ToString(bool withZeroX, bool withEip55Checksum) => Bytes.ToHexString(withZeroX, false, withEip55Checksum); + public readonly string ToString(bool withZeroX, bool withEip55Checksum) => Bytes.ToHexString(withZeroX, false, withEip55Checksum); - public bool Equals(Address? other) => other is not null && Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); + public readonly bool Equals(Address? other) => other is not null && Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); - public bool Equals(AddressStructRef other) => Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); + public readonly bool Equals(AddressStructRef other) => Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); - public override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { if (obj is null) { @@ -307,7 +307,7 @@ public override bool Equals(object? obj) return obj.GetType() == typeof(Address) && Equals((Address)obj); } - public override int GetHashCode() => MemoryMarshal.Read(Bytes); + public override readonly int GetHashCode() => MemoryMarshal.Read(Bytes); public static bool operator ==(AddressStructRef a, Address? b) => a.Equals(b); @@ -321,6 +321,6 @@ public override bool Equals(object? obj) public static bool operator !=(AddressStructRef a, AddressStructRef b) => !(a == b); - public Address ToAddress() => new(Bytes.ToArray()); + public readonly Address ToAddress() => new(Bytes.ToArray()); } } diff --git a/src/Nethermind/Nethermind.Core/Bloom.cs b/src/Nethermind/Nethermind.Core/Bloom.cs index fdaa7523006..8624a3a69a7 100644 --- a/src/Nethermind/Nethermind.Core/Bloom.cs +++ b/src/Nethermind/Nethermind.Core/Bloom.cs @@ -188,7 +188,7 @@ public void Set(int index) private static BloomExtract GetExtract(ReadOnlySpan sequence) { - int GetIndex(ReadOnlySpan bytes, int index1, int index2) + static int GetIndex(ReadOnlySpan bytes, int index1, int index2) { return 2047 - ((bytes[index1] << 8) + bytes[index2]) % 2048; } @@ -247,7 +247,7 @@ public void Set(ReadOnlySpan sequence) Set(sequence, null); } - private void Set(ReadOnlySpan sequence, Bloom? masterBloom = null) + private readonly void Set(ReadOnlySpan sequence, Bloom? masterBloom = null) { Bloom.BloomExtract indexes = GetExtract(sequence); Set(indexes.Index1); @@ -267,7 +267,7 @@ public bool Matches(ReadOnlySpan sequence) return Matches(in indexes); } - public override string ToString() + public override readonly string ToString() { return Bytes.ToHexString(); } @@ -282,26 +282,26 @@ public override string ToString() public static bool operator ==(BloomStructRef a, BloomStructRef b) => a.Equals(b); - public bool Equals(Bloom? other) + public readonly bool Equals(Bloom? other) { if (other is null) return false; return Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); } - public bool Equals(BloomStructRef other) + public readonly bool Equals(BloomStructRef other) { return Nethermind.Core.Extensions.Bytes.AreEqual(Bytes, other.Bytes); } - public override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { if (obj is null) return false; if (obj.GetType() != typeof(BloomStructRef)) return false; return Equals((Bloom)obj); } - public override int GetHashCode() + public override readonly int GetHashCode() { return Core.Extensions.Bytes.GetSimplifiedHashCode(Bytes); } @@ -321,7 +321,7 @@ public void Add(LogEntry[] logEntries, Bloom? blockBloom) } } - public void Accumulate(BloomStructRef bloom) + public readonly void Accumulate(BloomStructRef bloom) { Bytes.Or(bloom.Bytes); } @@ -344,14 +344,14 @@ public bool Matches(LogEntry logEntry) return false; } - private bool Get(int index) + private readonly bool Get(int index) { int bytePosition = index / 8; int shift = index % 8; return Bytes[bytePosition].GetBit(shift); } - private void Set(int index) + private readonly void Set(int index) { int bytePosition = index / 8; int shift = index % 8; @@ -362,7 +362,7 @@ private void Set(int index) public bool Matches(Hash256 topic) => Matches(topic.Bytes); - public bool Matches(in Bloom.BloomExtract extract) => Get(extract.Index1) && Get(extract.Index2) && Get(extract.Index3); + public readonly bool Matches(in Bloom.BloomExtract extract) => Get(extract.Index1) && Get(extract.Index2) && Get(extract.Index3); public static Bloom.BloomExtract GetExtract(Address address) => GetExtract(address.Bytes); @@ -370,7 +370,7 @@ private void Set(int index) private static Bloom.BloomExtract GetExtract(ReadOnlySpan sequence) { - int GetIndex(Span bytes, int index1, int index2) + static int GetIndex(Span bytes, int index1, int index2) { return 2047 - ((bytes[index1] << 8) + bytes[index2]) % 2048; } diff --git a/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs b/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs index c6e4ba1ab39..19c9be22f84 100644 --- a/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs +++ b/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs @@ -45,17 +45,16 @@ public static implicit operator CappedArray(T[]? array) } public int Length - { - get => _length; + { readonly get => _length; set => _length = value; } - public T[]? Array => _array; - public bool IsUncapped => _length == _array?.Length; - public bool IsNull => _array is null; - public bool IsNotNull => _array is not null; + public readonly T[]? Array => _array; + public readonly bool IsUncapped => _length == _array?.Length; + public readonly bool IsNull => _array is null; + public readonly bool IsNotNull => _array is not null; - public Span AsSpan() + public readonly Span AsSpan() { return _array.AsSpan()[..Length]; } diff --git a/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs b/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs index 347a71416d8..42cc51a2e31 100644 --- a/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs +++ b/src/Nethermind/Nethermind.Core/Caching/MemCountingCache.cs @@ -171,7 +171,7 @@ public LruCacheItem(ValueHash256 k, byte[] v) public readonly ValueHash256 Key; public byte[] Value; - public long MemorySize => FindMemorySize(Value); + public readonly long MemorySize => FindMemorySize(Value); public static long FindMemorySize(byte[] withValue) { diff --git a/src/Nethermind/Nethermind.Core/Collections/ArrayPoolList.cs b/src/Nethermind/Nethermind.Core/Collections/ArrayPoolList.cs index 47550ede5ad..fce08a7b53a 100644 --- a/src/Nethermind/Nethermind.Core/Collections/ArrayPoolList.cs +++ b/src/Nethermind/Nethermind.Core/Collections/ArrayPoolList.cs @@ -254,11 +254,11 @@ public ArrayPoolListEnumerator(T[] array, int count) public void Reset() => _index = -1; - public T Current => _array[_index]; + public readonly T Current => _array[_index]; - object IEnumerator.Current => Current!; + readonly object IEnumerator.Current => Current!; - public void Dispose() { } + public readonly void Dispose() { } } public void Dispose() diff --git a/src/Nethermind/Nethermind.Core/Collections/LockableConcurrentDictionary.cs b/src/Nethermind/Nethermind.Core/Collections/LockableConcurrentDictionary.cs index 0c0daa476a1..0247c6aca22 100644 --- a/src/Nethermind/Nethermind.Core/Collections/LockableConcurrentDictionary.cs +++ b/src/Nethermind/Nethermind.Core/Collections/LockableConcurrentDictionary.cs @@ -40,7 +40,7 @@ public static class ConcurrentDictionaryLock where TKey : notnull /// Thrown when private members of changed and we cannot create delegates. static ConcurrentDictionaryLock() { - TDelegate CreateDelegate(TType? target = default, string? methodName = null) where TDelegate : Delegate + static TDelegate CreateDelegate(TType? target = default, string? methodName = null) where TDelegate : Delegate { Type type = typeof(TType); Type delegateType = typeof(TDelegate); diff --git a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs index e7e634550f2..1fef9002e45 100644 --- a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs +++ b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs @@ -1195,11 +1195,11 @@ public bool MoveNext() return false; } - public KeyValuePair Current => _current; + public readonly KeyValuePair Current => _current; - public void Dispose() { } + public readonly void Dispose() { } - object? IEnumerator.Current + readonly object? IEnumerator.Current { get { @@ -1228,7 +1228,7 @@ void IEnumerator.Reset() _current = default; } - DictionaryEntry IDictionaryEnumerator.Entry + readonly DictionaryEntry IDictionaryEnumerator.Entry { get { @@ -1241,7 +1241,7 @@ DictionaryEntry IDictionaryEnumerator.Entry } } - object IDictionaryEnumerator.Key + readonly object IDictionaryEnumerator.Key { get { @@ -1254,7 +1254,7 @@ object IDictionaryEnumerator.Key } } - object? IDictionaryEnumerator.Value + readonly object? IDictionaryEnumerator.Value { get { @@ -1395,7 +1395,7 @@ internal Enumerator(SpanDictionary dictionary) _currentKey = default; } - public void Dispose() { } + public readonly void Dispose() { } public bool MoveNext() { @@ -1420,9 +1420,9 @@ public bool MoveNext() return false; } - public TKey[] Current => _currentKey!; + public readonly TKey[] Current => _currentKey!; - object? IEnumerator.Current + readonly object? IEnumerator.Current { get { @@ -1572,7 +1572,7 @@ internal Enumerator(SpanDictionary dictionary) _currentValue = default; } - public void Dispose() { } + public readonly void Dispose() { } public bool MoveNext() { @@ -1596,9 +1596,9 @@ public bool MoveNext() return false; } - public TValue Current => _currentValue!; + public readonly TValue Current => _currentValue!; - object? IEnumerator.Current + readonly object? IEnumerator.Current { get { diff --git a/src/Nethermind/Nethermind.Core/Crypto/Hash256.cs b/src/Nethermind/Nethermind.Core/Crypto/Hash256.cs index 3eb5d3191d5..54db0ce1d5a 100644 --- a/src/Nethermind/Nethermind.Core/Crypto/Hash256.cs +++ b/src/Nethermind/Nethermind.Core/Crypto/Hash256.cs @@ -20,7 +20,7 @@ namespace Nethermind.Core.Crypto private readonly Vector256 _bytes; public const int MemorySize = 32; - public int Length => MemorySize; + public static int Length => MemorySize; public Span BytesAsSpan => MemoryMarshal.AsBytes(MemoryMarshal.CreateSpan(ref Unsafe.AsRef(in _bytes), 1)); public ReadOnlySpan Bytes => MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in _bytes), 1)); @@ -74,12 +74,12 @@ public override int GetHashCode() public int CompareTo(ValueHash256 other) { - return Extensions.Bytes.Comparer.Compare(Bytes, other.Bytes); + return Extensions.Bytes.BytesComparer.Compare(Bytes, other.Bytes); } public int CompareTo(in ValueHash256 other) { - return Extensions.Bytes.Comparer.Compare(Bytes, other.Bytes); + return Extensions.Bytes.BytesComparer.Compare(Bytes, other.Bytes); } public override string ToString() @@ -280,7 +280,7 @@ public ref struct Hash256StructRef { public const int Size = 32; - public int MemorySize => MemorySizes.ArrayOverhead + Size; + public static int MemorySize => MemorySizes.ArrayOverhead + Size; public Span Bytes { get; } @@ -294,23 +294,23 @@ public Hash256StructRef(Span bytes) Bytes = bytes; } - public override string ToString() + public override readonly string ToString() { return ToString(true); } - public string ToShortString(bool withZeroX = true) + public readonly string ToShortString(bool withZeroX = true) { string hash = Bytes.ToHexString(withZeroX); return $"{hash[..(withZeroX ? 8 : 6)]}...{hash[^6..]}"; } - public string ToString(bool withZeroX) + public readonly string ToString(bool withZeroX) { return Bytes.ToHexString(withZeroX); } - public bool Equals(Hash256? other) + public readonly bool Equals(Hash256? other) { if (other is null) { @@ -320,14 +320,14 @@ public bool Equals(Hash256? other) return Extensions.Bytes.AreEqual(other.Bytes, Bytes); } - public bool Equals(Hash256StructRef other) => Extensions.Bytes.AreEqual(other.Bytes, Bytes); + public readonly bool Equals(Hash256StructRef other) => Extensions.Bytes.AreEqual(other.Bytes, Bytes); - public override bool Equals(object? obj) + public override readonly bool Equals(object? obj) { return obj?.GetType() == typeof(Hash256) && Equals((Hash256)obj); } - public override int GetHashCode() + public override readonly int GetHashCode() { return MemoryMarshal.Read(Bytes); } @@ -372,6 +372,6 @@ public override int GetHashCode() return !(a == b); } - public Hash256 ToCommitment() => new(Bytes); + public readonly Hash256 ToCommitment() => new(Bytes); } } diff --git a/src/Nethermind/Nethermind.Core/Eip2930/AccessList.cs b/src/Nethermind/Nethermind.Core/Eip2930/AccessList.cs index abe0233978b..f60888623c3 100644 --- a/src/Nethermind/Nethermind.Core/Eip2930/AccessList.cs +++ b/src/Nethermind/Nethermind.Core/Eip2930/AccessList.cs @@ -70,10 +70,12 @@ public bool MoveNext() } public void Reset() => _index = -1; - public (Address Address, StorageKeysEnumerable StorageKeys) Current => ((Address)_items[_index], new StorageKeysEnumerable(_items, _index)); - (Address Address, IEnumerable StorageKeys) IEnumerator<(Address Address, IEnumerable StorageKeys)>.Current => Current; - object IEnumerator.Current => Current; - public void Dispose() { } + public readonly (Address Address, StorageKeysEnumerable StorageKeys) Current => ((Address)_items[_index], new StorageKeysEnumerable(_items, _index)); + + readonly (Address Address, IEnumerable StorageKeys) IEnumerator<(Address Address, IEnumerable StorageKeys)>.Current => Current; + + readonly object IEnumerator.Current => Current; + public readonly void Dispose() { } } public readonly struct StorageKeysEnumerable : IEnumerable @@ -106,8 +108,9 @@ public StorageKeysEnumerator(List items, int index) public bool MoveNext() => ++_index < _items.Count && _items[_index] is UInt256; public void Reset() => _index = _startingIndex; - public UInt256 Current => (UInt256)_items[_index]; - object IEnumerator.Current => Current; - public void Dispose() { } + public readonly UInt256 Current => (UInt256)_items[_index]; + + readonly object IEnumerator.Current => Current; + public readonly void Dispose() { } } } diff --git a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs index bb514e056e0..7978ad40043 100644 --- a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs +++ b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs @@ -99,7 +99,7 @@ public override int Compare(byte[]? x, byte[]? y) return y.Length > x.Length ? 1 : 0; } - public int Compare(ReadOnlySpan x, ReadOnlySpan y) + public static int Compare(ReadOnlySpan x, ReadOnlySpan y) { if (Unsafe.AreSame(ref MemoryMarshal.GetReference(x), ref MemoryMarshal.GetReference(y)) && x.Length == y.Length) diff --git a/src/Nethermind/Nethermind.Crypto/Ecdsa.cs b/src/Nethermind/Nethermind.Crypto/Ecdsa.cs index bed33180d2c..1cb2ef22a22 100644 --- a/src/Nethermind/Nethermind.Crypto/Ecdsa.cs +++ b/src/Nethermind/Nethermind.Crypto/Ecdsa.cs @@ -72,7 +72,7 @@ public Signature Sign(PrivateKey privateKey, Hash256 message) return new CompressedPublicKey(publicKey); } - public PublicKey Decompress(CompressedPublicKey compressedPublicKey) + public static PublicKey Decompress(CompressedPublicKey compressedPublicKey) { byte[] deserialized = SecP256k1.Decompress(compressedPublicKey.Bytes); return new PublicKey(deserialized); diff --git a/src/Nethermind/Nethermind.Crypto/EciesCipher.cs b/src/Nethermind/Nethermind.Crypto/EciesCipher.cs index 9dadad24833..078ccd9666b 100644 --- a/src/Nethermind/Nethermind.Crypto/EciesCipher.cs +++ b/src/Nethermind/Nethermind.Crypto/EciesCipher.cs @@ -70,7 +70,7 @@ public byte[] Encrypt(PublicKey recipientPublicKey, byte[] plainText, byte[] mac private readonly OptimizedKdf _optimizedKdf = new(); - private byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte[] iv, byte[] ciphertextBody, byte[] macData) + private static byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte[] iv, byte[] ciphertextBody, byte[] macData) { IIesEngine iesEngine = MakeIesEngine(false, ephemeralPublicKey, privateKey, iv); return iesEngine.ProcessBlock(ciphertextBody, 0, ciphertextBody.Length, macData); @@ -78,7 +78,7 @@ private byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte private static readonly IesParameters _iesParameters = new IesWithCipherParameters(Array.Empty(), Array.Empty(), KeySize, KeySize); - private IIesEngine MakeIesEngine(bool isEncrypt, PublicKey publicKey, PrivateKey privateKey, byte[] iv) + private static IIesEngine MakeIesEngine(bool isEncrypt, PublicKey publicKey, PrivateKey privateKey, byte[] iv) { IBlockCipher aesFastEngine = AesEngineX86Intrinsic.IsSupported ? new AesEngineX86Intrinsic() : new AesEngine(); @@ -89,7 +89,7 @@ private IIesEngine MakeIesEngine(bool isEncrypt, PublicKey publicKey, PrivateKey ParametersWithIV parametersWithIV = new(_iesParameters, iv); byte[] secret = SecP256k1.EcdhSerialized(publicKey.Bytes, privateKey.KeyBytes); - iesEngine.Init(isEncrypt, _optimizedKdf.Derive(secret), parametersWithIV); + iesEngine.Init(isEncrypt, OptimizedKdf.Derive(secret), parametersWithIV); return iesEngine; } } diff --git a/src/Nethermind/Nethermind.Crypto/Keccak512.cs b/src/Nethermind/Nethermind.Crypto/Keccak512.cs index a3c12b804f3..b8a7eb42233 100644 --- a/src/Nethermind/Nethermind.Crypto/Keccak512.cs +++ b/src/Nethermind/Nethermind.Crypto/Keccak512.cs @@ -37,7 +37,7 @@ public override string ToString() return ToString(true); } - public string ToString(bool withZeroX) + public readonly string ToString(bool withZeroX) { if (Bytes is null) { @@ -107,7 +107,7 @@ public static Keccak512 Compute(string? input) return InternalCompute(System.Text.Encoding.UTF8.GetBytes(input)); } - public bool Equals(Keccak512 other) + public readonly bool Equals(Keccak512 other) { return Core.Extensions.Bytes.AreEqual(other.Bytes, Bytes); } @@ -117,7 +117,7 @@ public override bool Equals(object obj) return obj?.GetType() == typeof(Keccak512) && Equals((Keccak512)obj); } - public override int GetHashCode() + public override readonly int GetHashCode() { return BinaryPrimitives.ReadInt32LittleEndian(Bytes); } diff --git a/src/Nethermind/Nethermind.Crypto/OptimizedKdf.cs b/src/Nethermind/Nethermind.Crypto/OptimizedKdf.cs index 60c7cea8447..a11f93b65c0 100644 --- a/src/Nethermind/Nethermind.Crypto/OptimizedKdf.cs +++ b/src/Nethermind/Nethermind.Crypto/OptimizedKdf.cs @@ -27,7 +27,7 @@ private static byte[] BuildDataToHash() /// /// The base key to derive another key from. /// Returns the key derived from the provided base key and hash algorithm. - public byte[] Derive(byte[] key) + public static byte[] Derive(byte[] key) { byte[] dataToHash = _dataToHash.Value; key.AsSpan().CopyTo(dataToHash.AsSpan(4, 32)); diff --git a/src/Nethermind/Nethermind.Crypto/ProtectedData.AspNetWrapper.cs b/src/Nethermind/Nethermind.Crypto/ProtectedData.AspNetWrapper.cs index 1cb14f20c76..21bc6e23575 100644 --- a/src/Nethermind/Nethermind.Crypto/ProtectedData.AspNetWrapper.cs +++ b/src/Nethermind/Nethermind.Crypto/ProtectedData.AspNetWrapper.cs @@ -52,14 +52,14 @@ private IDataProtector GetUserProtector(byte[] optionalEntropy) return provider.CreateProtector(purpose); } - private IDataProtector GetMachineProtector(byte[] optionalEntropy) + private static IDataProtector GetMachineProtector(byte[] optionalEntropy) { var provider = DataProtectionProvider.Create(AppName); var purpose = CreatePurpose(optionalEntropy); return provider.CreateProtector(purpose); } - private string CreatePurpose(byte[] optionalEntropy) + private static string CreatePurpose(byte[] optionalEntropy) { var result = BaseName + Convert.ToBase64String(optionalEntropy); return Uri.EscapeDataString(result); diff --git a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs index c3ad62fc85f..d17d4179436 100644 --- a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs +++ b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs @@ -459,7 +459,7 @@ protected virtual void BuildOptions(PerTableDbConfig dbConfig, Options opt } } - private WriteOptions CreateWriteOptions(PerTableDbConfig dbConfig) + private static WriteOptions CreateWriteOptions(PerTableDbConfig dbConfig) { WriteOptions options = new(); // potential fix for corruption on hard process termination, may cause performance degradation @@ -1156,7 +1156,7 @@ private IDictionary GetStandardOptions() /// This caps the maximum allowed number of l0 files, which is also the read response time amplification. /// /// - private IDictionary GetHeavyWriteOptions(ulong l0FileNumTarget) + private static IDictionary GetHeavyWriteOptions(ulong l0FileNumTarget) { // Make buffer (probably) smaller so that it does not take too much memory to have many of them. // More buffer means more parallel flush, but each read have to go through all buffer one by one much like l0 @@ -1190,7 +1190,7 @@ private IDictionary GetHeavyWriteOptions(ulong l0FileNumTarget) }; } - private IDictionary GetDisableCompactionOptions() + private static IDictionary GetDisableCompactionOptions() { IDictionary heavyWriteOption = GetHeavyWriteOptions(2048); @@ -1205,7 +1205,7 @@ private IDictionary GetDisableCompactionOptions() } - private IDictionary GetBlobFilesOptions() + private static IDictionary GetBlobFilesOptions() { // Enable blob files, see: https://rocksdb.org/blog/2021/05/26/integrated-blob-db.html // This is very useful for blocks, as it almost eliminate 95% of the compaction as the main db no longer diff --git a/src/Nethermind/Nethermind.Db.Rocks/Statistics/DbMetricsUpdater.cs b/src/Nethermind/Nethermind.Db.Rocks/Statistics/DbMetricsUpdater.cs index 5801411b08e..f92d5d3a9b9 100644 --- a/src/Nethermind/Nethermind.Db.Rocks/Statistics/DbMetricsUpdater.cs +++ b/src/Nethermind/Nethermind.Db.Rocks/Statistics/DbMetricsUpdater.cs @@ -98,7 +98,7 @@ private void UpdateMetricsFromList(List<(string Name, long Value)> levelStats) /// Example line: /// L0 2/0 1.77 MB 0.5 0.0 0.0 0.0 0.4 0.4 0.0 1.0 0.0 44.6 9.83 0.00 386 0.025 0 0 /// - private List<(string Name, long Value)> ExtractStatsPerLevel(string compactionStatsDump) + private static List<(string Name, long Value)> ExtractStatsPerLevel(string compactionStatsDump) { var stats = new List<(string Name, long Value)>(5); diff --git a/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs b/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs index 15e25f0a127..d801f521148 100644 --- a/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs +++ b/src/Nethermind/Nethermind.Db/Blooms/BloomStorage.cs @@ -360,7 +360,7 @@ public BloomEnumerator(BloomStorageLevel[] storageLevels, in long fromBlock, in Reset(); } - private (BloomStorageLevel Storage, IFileReader Reader)[] GetStorageLevels(BloomStorageLevel[] storageLevels, long fromBlock, long toBlock) + private static (BloomStorageLevel Storage, IFileReader Reader)[] GetStorageLevels(BloomStorageLevel[] storageLevels, long fromBlock, long toBlock) { // Skip higher levels if we would do only 1 or 2 lookups in them. Thanks to that we can skip a lot of IO operations on that file IList levels = new List(storageLevels.Length); diff --git a/src/Nethermind/Nethermind.Db/StandardDbInitializer.cs b/src/Nethermind/Nethermind.Db/StandardDbInitializer.cs index 609775c410b..543f9adf8ea 100644 --- a/src/Nethermind/Nethermind.Db/StandardDbInitializer.cs +++ b/src/Nethermind/Nethermind.Db/StandardDbInitializer.cs @@ -69,7 +69,7 @@ private void RegisterAll(bool useReceiptsDb, bool useBlobsDb) } } - private RocksDbSettings BuildRocksDbSettings(string dbName, Action updateReadsMetrics, Action updateWriteMetrics, bool deleteOnStart = false) + private static RocksDbSettings BuildRocksDbSettings(string dbName, Action updateReadsMetrics, Action updateWriteMetrics, bool deleteOnStart = false) { return new(GetTitleDbName(dbName), dbName) { diff --git a/src/Nethermind/Nethermind.Evm/EvmStack.cs b/src/Nethermind/Nethermind.Evm/EvmStack.cs index 7e1622744c6..48dc9ae49a2 100644 --- a/src/Nethermind/Nethermind.Evm/EvmStack.cs +++ b/src/Nethermind/Nethermind.Evm/EvmStack.cs @@ -273,7 +273,7 @@ public void PopUInt256(out UInt256 result) } } - public bool PeekUInt256IsZero() + public readonly bool PeekUInt256IsZero() { int head = Head; if (head-- == 0) diff --git a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/GethLikeJavaScriptTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/GethLikeJavaScriptTxTracer.cs index c63203dfd40..225d91fc8de 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/GethLikeJavaScriptTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/GethLikeJavaScriptTxTracer.cs @@ -235,7 +235,7 @@ public override void ReportRefund(long refund) _log.refund += refund; } - private TracerFunctions GetAvailableFunctions(ICollection functions) + private static TracerFunctions GetAvailableFunctions(ICollection functions) { const TracerFunctions required = TracerFunctions.result; diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityAccountStateChangeJsonConverter.cs b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityAccountStateChangeJsonConverter.cs index af98fb2662b..44cf1ac8bee 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityAccountStateChangeJsonConverter.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityAccountStateChangeJsonConverter.cs @@ -21,7 +21,7 @@ public override ParityAccountStateChange Read( Type typeToConvert, JsonSerializerOptions options) => throw new NotImplementedException(); - private void WriteChange(Utf8JsonWriter writer, ParityStateChange change, JsonSerializerOptions options) + private static void WriteChange(Utf8JsonWriter writer, ParityStateChange change, JsonSerializerOptions options) { if (change is null) { @@ -51,7 +51,7 @@ private void WriteChange(Utf8JsonWriter writer, ParityStateChange change } } - private void WriteChange(Utf8JsonWriter writer, ParityStateChange change, JsonSerializerOptions options) + private static void WriteChange(Utf8JsonWriter writer, ParityStateChange change, JsonSerializerOptions options) { if (change is null) { diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs index 08fde62852a..908a90527d8 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs @@ -89,7 +89,7 @@ private static string GetCallType(ExecutionType executionType) } } - private string GetActionType(ExecutionType executionType) + private static string GetActionType(ExecutionType executionType) { switch (executionType) { @@ -413,7 +413,7 @@ public override void ReportAction(long gas, UInt256 value, Address from, Address PushAction(action); } - private string? GetCreateMethod(ExecutionType callType) + private static string? GetCreateMethod(ExecutionType callType) { switch (callType) { diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityTraceActionConverter.cs b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityTraceActionConverter.cs index 3feb7a025bf..919af532be5 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityTraceActionConverter.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityTraceActionConverter.cs @@ -173,7 +173,7 @@ public override void Write( writer.WriteEndObject(); } - private void WriteSelfDestructJson(Utf8JsonWriter writer, ParityTraceAction value, JsonSerializerOptions options) + private static void WriteSelfDestructJson(Utf8JsonWriter writer, ParityTraceAction value, JsonSerializerOptions options) { writer.WriteStartObject(); @@ -189,7 +189,7 @@ private void WriteSelfDestructJson(Utf8JsonWriter writer, ParityTraceAction valu writer.WriteEndObject(); } - private void WriteRewardJson(Utf8JsonWriter writer, ParityTraceAction value, JsonSerializerOptions options) + private static void WriteRewardJson(Utf8JsonWriter writer, ParityTraceAction value, JsonSerializerOptions options) { writer.WriteStartObject(); diff --git a/src/Nethermind/Nethermind.Evm/TransactionSubstate.cs b/src/Nethermind/Nethermind.Evm/TransactionSubstate.cs index 7fd3bc11835..a5368120981 100644 --- a/src/Nethermind/Nethermind.Evm/TransactionSubstate.cs +++ b/src/Nethermind/Nethermind.Evm/TransactionSubstate.cs @@ -91,7 +91,7 @@ public TransactionSubstate( ); } - private string DefaultErrorMessage(ReadOnlySpan span) => span.ToHexString(true); + private static string DefaultErrorMessage(ReadOnlySpan span) => span.ToHexString(true); private string? TryGetErrorMessage(ReadOnlySpan span) { diff --git a/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs b/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs index 06cbb64ba24..ca3f943ee5f 100644 --- a/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs +++ b/src/Nethermind/Nethermind.Facade/Eth/EthSyncingInfo.cs @@ -75,7 +75,7 @@ public SyncingResult GetFullInfo() return SyncingResult.NotSyncing; } - private SyncingResult ReturnSyncing(long headNumberOrZero, long bestSuggestedNumber, SyncMode syncMode) + private static SyncingResult ReturnSyncing(long headNumberOrZero, long bestSuggestedNumber, SyncMode syncMode) { return new SyncingResult { diff --git a/src/Nethermind/Nethermind.Facade/Eth/SyncingResult.cs b/src/Nethermind/Nethermind.Facade/Eth/SyncingResult.cs index 518eb44678a..978bf36bd66 100644 --- a/src/Nethermind/Nethermind.Facade/Eth/SyncingResult.cs +++ b/src/Nethermind/Nethermind.Facade/Eth/SyncingResult.cs @@ -17,7 +17,7 @@ public struct SyncingResult public long HighestBlock { get; set; } public SyncMode SyncMode { get; set; } - public override string ToString() + public override readonly string ToString() { return $"IsSyncing: {IsSyncing}, StartingBlock: {StartingBlock}, CurrentBlock {CurrentBlock}, HighestBlock {HighestBlock}"; } diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs index f8b1c84b50d..8a1c1079809 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs @@ -217,7 +217,7 @@ private void StoreLogs(LogFilter filter, TxReceipt txReceipt, ref long logIndex) if (_logger.IsDebug) _logger.Debug($"Filter with id: {filter.Id} contains {logs.Count} logs."); } - private FilterLog? CreateLog(LogFilter logFilter, TxReceipt txReceipt, LogEntry logEntry, long index, int transactionLogIndex) + private static FilterLog? CreateLog(LogFilter logFilter, TxReceipt txReceipt, LogEntry logEntry, long index, int transactionLogIndex) { if (logFilter.FromBlock.Type == BlockParameterType.BlockNumber && logFilter.FromBlock.BlockNumber > txReceipt.BlockNumber) diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs index b6af25caa12..8d89c046ce6 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs @@ -119,7 +119,7 @@ private int GetFilterId(bool generateId) return 0; } - private TopicsFilter GetTopicsFilter(IEnumerable? topics = null) + private static TopicsFilter GetTopicsFilter(IEnumerable? topics = null) { if (topics is null) { @@ -137,7 +137,7 @@ private TopicsFilter GetTopicsFilter(IEnumerable? topics = null) return new SequenceTopicsFilter(expressions.ToArray()); } - private TopicExpression GetTopicExpression(FilterTopic? filterTopic) + private static TopicExpression GetTopicExpression(FilterTopic? filterTopic) { if (filterTopic is null) { diff --git a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs index 4ff23807849..8ef6790b9a4 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs @@ -84,7 +84,7 @@ BlockHeader FindHeader(BlockParameter blockParameter, string name, bool headLimi : FilterLogsIteratively(filter, fromBlock, toBlock, cancellationToken); } - private bool ShouldUseBloomDatabase(BlockHeader fromBlock, BlockHeader toBlock) + private static bool ShouldUseBloomDatabase(BlockHeader fromBlock, BlockHeader toBlock) { var blocksToSearch = toBlock.Number - fromBlock.Number + 1; return blocksToSearch > 1; // if we are searching only in 1 block skip bloom index altogether, this can be tweaked diff --git a/src/Nethermind/Nethermind.HealthChecks/NodeHealthService.cs b/src/Nethermind/Nethermind.HealthChecks/NodeHealthService.cs index 9688d6629fc..f31ca24636f 100644 --- a/src/Nethermind/Nethermind.HealthChecks/NodeHealthService.cs +++ b/src/Nethermind/Nethermind.HealthChecks/NodeHealthService.cs @@ -144,7 +144,7 @@ public CheckHealthResult CheckHealth() _healthHintService.MaxSecondsIntervalForProducingBlocksHint(); } - private bool CheckSyncPostMerge(ICollection<(string Description, string LongDescription)> messages, + private static bool CheckSyncPostMerge(ICollection<(string Description, string LongDescription)> messages, ICollection errors, SyncingResult syncingResult) { if (syncingResult.IsSyncing) diff --git a/src/Nethermind/Nethermind.Hive/HiveRunner.cs b/src/Nethermind/Nethermind.Hive/HiveRunner.cs index ce5006938e7..2f0ad1e2aba 100644 --- a/src/Nethermind/Nethermind.Hive/HiveRunner.cs +++ b/src/Nethermind/Nethermind.Hive/HiveRunner.cs @@ -112,7 +112,7 @@ private void ListEnvironmentVariables() } } - public async Task StopAsync() + public static async Task StopAsync() { await Task.CompletedTask; } @@ -191,7 +191,7 @@ private Block DecodeBlock(string file) return Rlp.Decode(blockRlp); } - private async Task WaitForBlockProcessing(SemaphoreSlim semaphore) + private static async Task WaitForBlockProcessing(SemaphoreSlim semaphore) { if (!await semaphore.WaitAsync(5000)) { diff --git a/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs b/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs index 6d305b5c8e0..18a2c7c7bf1 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs @@ -13,13 +13,15 @@ namespace Nethermind.Init.Cpu; internal static partial class SectionsHelper { + internal static readonly char[] separator = new[] { '\r', '\n' }; + public static Dictionary ParseSection(string? content, char separator) { var values = new Dictionary(); - var list = content?.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + var list = content?.Split(separator, StringSplitOptions.RemoveEmptyEntries); if (list != null) foreach (string line in list) - if (line.IndexOf(separator) != -1) + if (line.Contains(separator)) { var lineParts = line.Split(separator); if (lineParts.Length >= 2) diff --git a/src/Nethermind/Nethermind.Init/MemoryHintMan.cs b/src/Nethermind/Nethermind.Init/MemoryHintMan.cs index 62927f0d803..d811ed619cb 100644 --- a/src/Nethermind/Nethermind.Init/MemoryHintMan.cs +++ b/src/Nethermind/Nethermind.Init/MemoryHintMan.cs @@ -89,7 +89,7 @@ private void SetupMallocOpts(IInitConfig initConfig) // On 16C/32T machine, this reduces memory usage by about 7GB. // There aren't much difference between 16KB to 64KB, but the system cpu time increase slightly as threshold // lowers. 4k significantly increase cpu system time. - bool success = _mallocHelper.MallOpt(MallocHelper.Option.M_MMAP_THRESHOLD, (int)64.KiB()); + bool success = MallocHelper.Instance.MallOpt(MallocHelper.Option.M_MMAP_THRESHOLD, (int)64.KiB()); if (!success && _logger.IsDebug) _logger.Debug("Unable to set M_MAP_THRESHOLD"); } @@ -293,7 +293,7 @@ public DbNeeds( public decimal PreferredMemoryPercentage { get; set; } } - private DbNeeds GetStateNeeds(uint cpuCount) + private static DbNeeds GetStateNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); // remove optimize for point lookup here? @@ -306,7 +306,7 @@ private DbNeeds GetStateNeeds(uint cpuCount) 1m); // db memory % } - private DbNeeds GetBlockInfosNeeds(uint cpuCount) + private static DbNeeds GetBlockInfosNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); // remove optimize for point lookup here? @@ -319,7 +319,7 @@ private DbNeeds GetBlockInfosNeeds(uint cpuCount) 0.02m); // db memory % } - private DbNeeds GetHeaderNeeds(uint cpuCount) + private static DbNeeds GetHeaderNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); return new DbNeeds( @@ -331,7 +331,7 @@ private DbNeeds GetHeaderNeeds(uint cpuCount) 0.05m); // db memory % } - private DbNeeds GetBlocksNeeds(uint cpuCount) + private static DbNeeds GetBlocksNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); return new DbNeeds( @@ -343,7 +343,7 @@ private DbNeeds GetBlocksNeeds(uint cpuCount) 0.04m); // db memory % } - private DbNeeds GetReceiptsNeeds(uint cpuCount) + private static DbNeeds GetReceiptsNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); return new DbNeeds( @@ -355,7 +355,7 @@ private DbNeeds GetReceiptsNeeds(uint cpuCount) 0.01m); // db memory % } - private DbNeeds GetPendingTxNeeds(uint cpuCount) + private static DbNeeds GetPendingTxNeeds(uint cpuCount) { return new DbNeeds( 4, @@ -366,7 +366,7 @@ private DbNeeds GetPendingTxNeeds(uint cpuCount) 0.01m); // db memory % } - private DbNeeds GetCodeNeeds(uint cpuCount) + private static DbNeeds GetCodeNeeds(uint cpuCount) { uint preferredBuffers = Math.Min(cpuCount, 2u); return new DbNeeds( diff --git a/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs b/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs index 22305635d92..ad89f596e61 100644 --- a/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs +++ b/src/Nethermind/Nethermind.Init/Steps/Migrations/BloomMigration.cs @@ -74,7 +74,7 @@ public void Run() } } - private bool CanMigrate(SyncMode syncMode) => syncMode.NotSyncing(); + private static bool CanMigrate(SyncMode syncMode) => syncMode.NotSyncing(); private void SynchronizerOnSyncModeChanged(object? sender, SyncModeChangedEventArgs e) { diff --git a/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptMigration.cs b/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptMigration.cs index 5aae75750a3..7b49097bbdd 100644 --- a/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptMigration.cs +++ b/src/Nethermind/Nethermind.Init/Steps/Migrations/ReceiptMigration.cs @@ -139,7 +139,7 @@ private void DoRun() } } - private bool CanMigrate(SyncMode syncMode) => syncMode.NotSyncing(); + private static bool CanMigrate(SyncMode syncMode) => syncMode.NotSyncing(); private void OnSyncModeChanged(object? sender, SyncModeChangedEventArgs e) { @@ -404,7 +404,7 @@ private bool IsMigrationNeeded(long blockNumber, Hash256 blockHash, TxReceipt[] return true; } - bool isCompactEncoding = _storageDecoder.IsCompactEncoding(receiptData!); + bool isCompactEncoding = ReceiptArrayStorageDecoder.IsCompactEncoding(receiptData!); return _receiptConfig.CompactReceiptStore != isCompactEncoding; } diff --git a/src/Nethermind/Nethermind.Init/VersionToMetrics.cs b/src/Nethermind/Nethermind.Init/VersionToMetrics.cs index c0f290b2a98..8b567ac0126 100644 --- a/src/Nethermind/Nethermind.Init/VersionToMetrics.cs +++ b/src/Nethermind/Nethermind.Init/VersionToMetrics.cs @@ -8,11 +8,13 @@ namespace Nethermind.Init; public static class VersionToMetrics { + private static readonly char[] anyOf = new[] { '-', '+' }; + public static int ConvertToNumber(string version) { try { - var index = version.IndexOfAny(new[] { '-', '+' }); + var index = version.IndexOfAny(anyOf); if (index != -1) version = version[..index]; diff --git a/src/Nethermind/Nethermind.JsonRpc.TraceStore/TraceStoreRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc.TraceStore/TraceStoreRpcModule.cs index 236b4123fbc..b01b95b265d 100644 --- a/src/Nethermind/Nethermind.JsonRpc.TraceStore/TraceStoreRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc.TraceStore/TraceStoreRpcModule.cs @@ -242,13 +242,13 @@ private bool TryGetBlockTraces(BlockHeader block, out List? t } } - private ParityLikeTxTrace? GetTxTrace(Block block, Hash256 txHash, List traces) + private static ParityLikeTxTrace? GetTxTrace(Block block, Hash256 txHash, List traces) { int index = traces.FindIndex(t => t.TransactionHash == txHash); return index != -1 ? traces[index] : null; } - private void FilterTraces(List traces, ParityTraceTypes traceTypes) + private static void FilterTraces(List traces, ParityTraceTypes traceTypes) { for (int i = 0; i < traces.Count; i++) { diff --git a/src/Nethermind/Nethermind.JsonRpc/Data/AccessListItemForRpc.cs b/src/Nethermind/Nethermind.JsonRpc/Data/AccessListItemForRpc.cs index b0fc6893087..9961cbc75a2 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Data/AccessListItemForRpc.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Data/AccessListItemForRpc.cs @@ -50,8 +50,8 @@ public static AccessList ToAccessList(IEnumerable accessLi return builder.Build(); } - public bool Equals(AccessListItemForRpc other) => Equals(Address, other.Address) && StorageKeys.NullableSequenceEqual(other.StorageKeys); + public readonly bool Equals(AccessListItemForRpc other) => Equals(Address, other.Address) && StorageKeys.NullableSequenceEqual(other.StorageKeys); public override bool Equals(object? obj) => obj is AccessListItemForRpc other && Equals(other); - public override int GetHashCode() => HashCode.Combine(Address, StorageKeys); + public override readonly int GetHashCode() => HashCode.Combine(Address, StorageKeys); } } diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcLocalStats.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcLocalStats.cs index 91000449525..e5335ba9873 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcLocalStats.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcLocalStats.cs @@ -177,7 +177,7 @@ private void Swap() } [Pure] - private string PrepareReportLine(in string key, MethodStats methodStats) => + private static string PrepareReportLine(in string key, MethodStats methodStats) => $"{key,-40}| " + $"{methodStats.Successes.ToString(),9} | " + $"{methodStats.AvgTimeOfSuccesses.ToString("0", CultureInfo.InvariantCulture),14} | " + diff --git a/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs b/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs index bea90a5b9a4..1cc38b65707 100644 --- a/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs +++ b/src/Nethermind/Nethermind.JsonRpc/JsonRpcService.cs @@ -269,7 +269,7 @@ private void LogRequest(string methodName, JsonElement providedParameters, Param } } - private object? DeserializeParameter(JsonElement providedParameter, ParameterInfo expectedParameter) + private static object? DeserializeParameter(JsonElement providedParameter, ParameterInfo expectedParameter) { Type paramType = expectedParameter.ParameterType; if (paramType.IsByRef) @@ -370,7 +370,7 @@ private void LogRequest(string methodName, JsonElement providedParameters, Param } } - private bool IsNullableParameter(ParameterInfo parameterInfo) + private static bool IsNullableParameter(ParameterInfo parameterInfo) { Type parameterType = parameterInfo.ParameterType; if (parameterType.IsValueType) @@ -391,7 +391,7 @@ private bool IsNullableParameter(ParameterInfo parameterInfo) return false; } - private JsonRpcResponse GetSuccessResponse(string methodName, object result, object id, Action? disposableAction) + private static JsonRpcResponse GetSuccessResponse(string methodName, object result, object id, Action? disposableAction) { JsonRpcResponse response = new JsonRpcSuccessResponse(disposableAction) { diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs index b571e34068d..4bf43eb3605 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.TransactionExecutor.cs @@ -63,7 +63,7 @@ public ResultWrapper ExecuteTx( protected abstract ResultWrapper ExecuteTx(BlockHeader header, Transaction tx, CancellationToken token); - protected ResultWrapper GetInputError(BlockchainBridge.CallOutput result) => + protected static ResultWrapper GetInputError(BlockchainBridge.CallOutput result) => ResultWrapper.Fail(result.Error, ErrorCodes.InvalidInput); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs index aef4c841ce5..ca479e41535 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/EthRpcModule.cs @@ -690,7 +690,7 @@ private void RecoverTxSenderIfNeeded(Transaction transaction) transaction.SenderAddress ??= _blockchainBridge.RecoverTxSender(transaction); } - private IEnumerable GetLogs(IEnumerable logs, CancellationTokenSource cancellationTokenSource) + private static IEnumerable GetLogs(IEnumerable logs, CancellationTokenSource cancellationTokenSource) { using (cancellationTokenSource) { diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/FeeHistory/FeeHistoryOracle.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/FeeHistory/FeeHistoryOracle.cs index 34e2c07a05d..4484e2040e3 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/FeeHistory/FeeHistoryOracle.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/FeeHistory/FeeHistoryOracle.cs @@ -119,7 +119,7 @@ private static List CalculatePercentileValues(Block block, double[] rew return percentileValues; } - private ResultWrapper Validate(ref long blockCount, BlockParameter newestBlock, double[]? rewardPercentiles) + private static ResultWrapper Validate(ref long blockCount, BlockParameter newestBlock, double[]? rewardPercentiles) { if (newestBlock.Type == BlockParameterType.BlockHash) { diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/GasPrice/GasPriceOracle.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/GasPrice/GasPriceOracle.cs index f31a86f85df..47242f2e164 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/GasPrice/GasPriceOracle.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Eth/GasPrice/GasPriceOracle.cs @@ -154,7 +154,7 @@ private IEnumerable GetGasPricesFromRecentBlocks(IEnumerable blo } } - private UInt256? GetGasPriceAtPercentile(List txGasPriceList) + private static UInt256? GetGasPriceAtPercentile(List txGasPriceList) { int roundedIndex = GetRoundedIndexAtPercentile(txGasPriceList.Count); @@ -188,7 +188,7 @@ public void Set(Hash256 headHash, UInt256 price) LastPrice = price; } - public bool TryGetPrice(Hash256 headHash, out UInt256? price) + public readonly bool TryGetPrice(Hash256 headHash, out UInt256? price) { if (headHash == LastHeadHash) { diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs index b5c548ee873..c7995bf60bf 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Proof/ProofRpcModule.cs @@ -198,7 +198,7 @@ private byte[][] CollectHeaderBytes(ProofTxTracer proofTxTracer, BlockHeader tra .Select(h => _headerDecoder.Encode(h).Bytes).ToArray(); } - private byte[][] BuildTxProofs(Transaction[] txs, IReleaseSpec releaseSpec, int index) + private static byte[][] BuildTxProofs(Transaction[] txs, IReleaseSpec releaseSpec, int index) { return new TxTrie(txs, true).BuildProof(index); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs index 72921c8ae10..fa3f6fb1774 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/RpcModuleProvider.cs @@ -134,7 +134,7 @@ public void Return(string methodName, IRpcModule rpcModule) public IRpcModulePool? GetPool(string moduleType) => _pools.TryGetValue(moduleType, out var poolInfo) ? poolInfo.ModulePool : null; - private IDictionary GetMethodDict(Type type) + private static IDictionary GetMethodDict(Type type) { var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); return methods.ToDictionary( diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/SearchResult.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/SearchResult.cs index 7c0b04e6343..8b51847dbc9 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/SearchResult.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/SearchResult.cs @@ -28,6 +28,6 @@ public SearchResult(T @object) public int ErrorCode { get; set; } - public bool IsError => ErrorCode != 0; + public readonly bool IsError => ErrorCode != 0; } } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs index 5c791e392a0..54694343907 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs @@ -12,7 +12,7 @@ public class JsonRpcSubscriptionResponse : JsonRpcResponse [JsonPropertyName("method")] [JsonPropertyOrder(1)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public new string MethodName => "eth_subscription"; + public new static string MethodName => "eth_subscription"; [JsonPropertyName("params")] [JsonPropertyOrder(2)] diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/TraceRpcModule.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/TraceRpcModule.cs index c01c65396ca..9417709fc67 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/TraceRpcModule.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Trace/TraceRpcModule.cs @@ -338,7 +338,7 @@ private IReadOnlyCollection ExecuteBlock(Block block, ParityL return tracer.BuildResult(); } - private ResultWrapper GetStateFailureResult(BlockHeader header) => + private static ResultWrapper GetStateFailureResult(BlockHeader header) => ResultWrapper.Fail($"No state available for block {header.ToString(BlockHeader.Format.FullHashAndNumber)}", ErrorCodes.ResourceUnavailable); } } diff --git a/src/Nethermind/Nethermind.KeyStore/AesEncrypter.cs b/src/Nethermind/Nethermind.KeyStore/AesEncrypter.cs index 40984d11355..f61ba351a58 100644 --- a/src/Nethermind/Nethermind.KeyStore/AesEncrypter.cs +++ b/src/Nethermind/Nethermind.KeyStore/AesEncrypter.cs @@ -94,7 +94,7 @@ public byte[] Decrypt(byte[] cipher, byte[] key, byte[] iv, string cipherType) } } - private byte[] Execute(ICryptoTransform cryptoTransform, byte[] data) + private static byte[] Execute(ICryptoTransform cryptoTransform, byte[] data) { using (var memoryStream = new MemoryStream()) { diff --git a/src/Nethermind/Nethermind.KeyStore/BaseKeyStoreIOSettingsProvider.cs b/src/Nethermind/Nethermind.KeyStore/BaseKeyStoreIOSettingsProvider.cs index 0e3ed33a1af..332f6345888 100644 --- a/src/Nethermind/Nethermind.KeyStore/BaseKeyStoreIOSettingsProvider.cs +++ b/src/Nethermind/Nethermind.KeyStore/BaseKeyStoreIOSettingsProvider.cs @@ -8,7 +8,7 @@ namespace Nethermind.KeyStore { public class BaseKeyStoreIOSettingsProvider { - public string GetStoreDirectory(string keyStoreFolderName) + public static string GetStoreDirectory(string keyStoreFolderName) { // TODO - we should have a file system implementation that does this var directory = keyStoreFolderName.GetApplicationResourcePath(); diff --git a/src/Nethermind/Nethermind.Logging.NLog/NLogManager.cs b/src/Nethermind/Nethermind.Logging.NLog/NLogManager.cs index 0b25b336fc0..c5d0bf537bd 100644 --- a/src/Nethermind/Nethermind.Logging.NLog/NLogManager.cs +++ b/src/Nethermind/Nethermind.Logging.NLog/NLogManager.cs @@ -27,7 +27,7 @@ public NLogManager(string logFileName, string logDirectory = null, string logRul LogManager.ConfigurationChanged += _logManagerOnConfigurationChanged; } - private void Setup(string logFileName, string logDirectory = null, string logRules = null) + private static void Setup(string logFileName, string logDirectory = null, string logRules = null) { logDirectory = SetupLogDirectory(logDirectory); SetupLogFile(logFileName, logDirectory); @@ -75,7 +75,7 @@ public void SetGlobalVariable(string name, object value) GlobalDiagnosticsContext.Set(name, value); } - private void SetupLogRules(string logRules) + private static void SetupLogRules(string logRules) { //Add rules here for e.g. 'JsonRpc.*: Warn; Block.*: Error;', if (logRules is not null) @@ -94,10 +94,10 @@ private void SetupLogRules(string logRules) } } - private Target[] GetTargets(IList configurationLoggingRules) => + private static Target[] GetTargets(IList configurationLoggingRules) => configurationLoggingRules.SelectMany(r => r.Targets).Distinct().ToArray(); - private void RemoveOverridenRules(IList configurationLoggingRules, LoggingRule loggingRule) + private static void RemoveOverridenRules(IList configurationLoggingRules, LoggingRule loggingRule) { string reqexPattern = $"^{loggingRule.LoggerNamePattern.Replace(".", "\\.").Replace("*", ".*")}$"; for (int j = 0; j < configurationLoggingRules.Count;) @@ -113,7 +113,7 @@ private void RemoveOverridenRules(IList configurationLoggingRules, } } - private IEnumerable ParseRules(string logRules, Target[] targets) + private static IEnumerable ParseRules(string logRules, Target[] targets) { string[] rules = logRules.Split(";", StringSplitOptions.RemoveEmptyEntries); foreach (string rule in rules) diff --git a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs index 888865df81b..7eb4aee313f 100644 --- a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs +++ b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs @@ -30,7 +30,7 @@ private static string GetStackFrameMethodClassName(MethodBase method, bool inclu } Type declaringType = method.DeclaringType; - if (cleanAsyncMoveNext && method.Name == "MoveNext" && (declaringType?.DeclaringType) is not null && declaringType.Name.StartsWith("<") && declaringType.Name.IndexOf('>', 1) > 1) + if (cleanAsyncMoveNext && method.Name == "MoveNext" && (declaringType?.DeclaringType) is not null && declaringType.Name.StartsWith('<') && declaringType.Name.IndexOf('>', 1) > 1) declaringType = declaringType.DeclaringType; string str = includeNameSpace ? ((object)declaringType is not null ? declaringType.FullName : (string)null) : ((object)declaringType is not null ? declaringType.Name : (string)null); if (cleanAnonymousDelegates && str is not null) diff --git a/src/Nethermind/Nethermind.Logging/SimpleConsoleLogger.cs b/src/Nethermind/Nethermind.Logging/SimpleConsoleLogger.cs index e90e7dc40f4..1e7882fcb16 100644 --- a/src/Nethermind/Nethermind.Logging/SimpleConsoleLogger.cs +++ b/src/Nethermind/Nethermind.Logging/SimpleConsoleLogger.cs @@ -41,7 +41,7 @@ public void Error(string text, Exception ex = null) WriteEntry(text + " " + ex); } - private void WriteEntry(string text) + private static void WriteEntry(string text) { Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss.ffff|") + text); } diff --git a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/Boost/BoostRelay.cs b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/Boost/BoostRelay.cs index 862e323c9e4..de8e60908e3 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/Boost/BoostRelay.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/BlockProduction/Boost/BoostRelay.cs @@ -28,5 +28,5 @@ public Task GetPayloadAttributes(PayloadAttributes paylo public Task SendPayload(BoostExecutionPayloadV1 executionPayloadV1, CancellationToken cancellationToken) => _httpClient.PostJsonAsync(GetUri(_relayUrl, SendPayloadPath), executionPayloadV1, cancellationToken); - private string GetUri(string relayUrl, string relativeUrl) => relayUrl + relativeUrl; + private static string GetUri(string relayUrl, string relativeUrl) => relayUrl + relativeUrl; } diff --git a/src/Nethermind/Nethermind.Merkleization/Merkleizer.cs b/src/Nethermind/Nethermind.Merkleization/Merkleizer.cs index 200391191cc..6fa128c9fbf 100644 --- a/src/Nethermind/Nethermind.Merkleization/Merkleizer.cs +++ b/src/Nethermind/Nethermind.Merkleization/Merkleizer.cs @@ -13,7 +13,7 @@ namespace Nethermind.Merkleization; public ref struct Merkleizer { - public bool IsKthBitSet(int k) + public readonly bool IsKthBitSet(int k) { return (_filled & ((ulong)1 << k)) != 0; } @@ -31,7 +31,7 @@ public void UnsetKthBit(int k) private readonly Span _chunks; private ulong _filled; - public UInt256 PartChunk + public readonly UInt256 PartChunk { get { diff --git a/src/Nethermind/Nethermind.Mev/Execution/CallTxBundleExecutor.cs b/src/Nethermind/Nethermind.Mev/Execution/CallTxBundleExecutor.cs index 422c91a0411..1c2d8074ecc 100644 --- a/src/Nethermind/Nethermind.Mev/Execution/CallTxBundleExecutor.cs +++ b/src/Nethermind/Nethermind.Mev/Execution/CallTxBundleExecutor.cs @@ -19,7 +19,7 @@ public CallTxBundleExecutor(ITracerFactory tracer, ISpecProvider specProvider, I protected override TxsResults BuildResult(MevBundle bundle, BlockCallOutputTracer tracer) { - TxResult ToTxResult(CallOutputTracer callOutputTracer) + static TxResult ToTxResult(CallOutputTracer callOutputTracer) { TxResult result = new(); if (callOutputTracer.StatusCode == StatusCode.Success) diff --git a/src/Nethermind/Nethermind.Mev/Source/BundlePool.cs b/src/Nethermind/Nethermind.Mev/Source/BundlePool.cs index a69e5b2831c..b5d95d1ccf1 100644 --- a/src/Nethermind/Nethermind.Mev/Source/BundlePool.cs +++ b/src/Nethermind/Nethermind.Mev/Source/BundlePool.cs @@ -188,7 +188,7 @@ public bool AddMegabundle(MevMegabundle megabundle) return false; } - private bool BundleInTimestampRange(MevBundle bundle, UInt256 minTimestamp, UInt256 maxTimestamp) + private static bool BundleInTimestampRange(MevBundle bundle, UInt256 minTimestamp, UInt256 maxTimestamp) { bool bundleIsInFuture = bundle.MinTimestamp != UInt256.Zero && minTimestamp < bundle.MinTimestamp; bool bundleIsTooOld = bundle.MaxTimestamp != UInt256.Zero && maxTimestamp > bundle.MaxTimestamp; @@ -348,7 +348,7 @@ private void OnNewBlock(object? sender, BlockEventArgs e) private void RemoveBundlesUpToBlock(long blockNumber) { - void StopSimulations(IEnumerable simulations) + static void StopSimulations(IEnumerable simulations) { foreach (SimulatedMevBundleContext simulation in simulations) { @@ -419,7 +419,7 @@ private void RemoveSimulation(MevBundle bundle) } } - private void StopSimulation(SimulatedMevBundleContext simulation) + private static void StopSimulation(SimulatedMevBundleContext simulation) { if (!simulation.Task.IsCompleted) { diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs index e0a7ac91725..ff17a82c6f9 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs @@ -151,7 +151,7 @@ protected static int GetLengthSerializeNode(IPEndPoint address, byte[] id) return length; } - protected void PrepareBufferForSerialization(IByteBuffer byteBuffer, int dataLength, byte msgType) + protected static void PrepareBufferForSerialization(IByteBuffer byteBuffer, int dataLength, byte msgType) { byteBuffer.EnsureWritable(MdcSigOffset + 1 + dataLength); byteBuffer.SetWriterIndex(byteBuffer.WriterIndex + MdcSigOffset); diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs index 1c79dd90e81..d388fb19063 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/NeighborsMsgSerializer.cs @@ -79,7 +79,7 @@ public NeighborsMsg Deserialize(IByteBuffer msgBytes) }); } - private int GetNodesLength(Node[] nodes, out int contentLength) + private static int GetNodesLength(Node[] nodes, out int contentLength) { contentLength = 0; for (int i = 0; i < nodes.Length; i++) @@ -96,7 +96,7 @@ public int GetLength(NeighborsMsg msg, out int contentLength) return totalLength; } - private (int totalLength, int contentLength, int nodesContentLength) GetLength(NeighborsMsg msg) + private static (int totalLength, int contentLength, int nodesContentLength) GetLength(NeighborsMsg msg) { int nodesContentLength = 0; int contentLength = 0; diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/PingMsgSerializer.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/PingMsgSerializer.cs index 093e8ca17cf..4b8162c61ef 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/PingMsgSerializer.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/PingMsgSerializer.cs @@ -91,7 +91,7 @@ public int GetLength(PingMsg msg, out int contentLength) } - private (int totalLength, int contentLength, int sourceAddressLength, int destinationAddressLength) GetLength(PingMsg msg) + private static (int totalLength, int contentLength, int sourceAddressLength, int destinationAddressLength) GetLength(PingMsg msg) { int sourceAddressLength = GetIPEndPointLength(msg.SourceAddress); int destinationAddressLength = GetIPEndPointLength(msg.DestinationAddress); diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/PongMsgSerializer.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/PongMsgSerializer.cs index dbe4ff97e28..adb43765e0d 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/PongMsgSerializer.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/PongMsgSerializer.cs @@ -63,7 +63,7 @@ public int GetLength(PongMsg message, out int contentLength) return totalLength; } - private (int totalLength, int contentLength, int farAddressLength) GetLength(PongMsg message) + private static (int totalLength, int contentLength, int farAddressLength) GetLength(PongMsg message) { if (message.FarAddress is null) { diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrDiscovery.cs b/src/Nethermind/Nethermind.Network.Dns/EnrDiscovery.cs index 15ffd4df564..7620dfaa8df 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrDiscovery.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrDiscovery.cs @@ -57,7 +57,7 @@ public async Task SearchTree(string domain) } } - private Node? CreateNode(NodeRecord nodeRecord) + private static Node? CreateNode(NodeRecord nodeRecord) { CompressedPublicKey? compressedPublicKey = nodeRecord.GetObj(EnrContentKey.Secp256K1); IPAddress? ipAddress = nodeRecord.GetObj(EnrContentKey.Ip); diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrRecordParser.cs b/src/Nethermind/Nethermind.Network.Dns/EnrRecordParser.cs index 7418c3a4517..e7123f86753 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrRecordParser.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrRecordParser.cs @@ -40,7 +40,7 @@ public NodeRecord ParseRecord(string nodeRecordText) public NodeRecord ParseRecord(string nodeRecordText, IByteBuffer buffer) { - void AddPadding(IByteBuffer byteBuffer, ICharSequence base64) + static void AddPadding(IByteBuffer byteBuffer, ICharSequence base64) { if (base64[^1] != '=') { diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs index aeac844f881..7a5385bc493 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs @@ -69,7 +69,7 @@ public static EnrTreeRoot ParseEnrRoot(string enrTreeRootText) enrTreeRoot.LinkRoot = enrTreeRootText.Substring(linkRootIndex + 2, HashLengthBase32); int seqIndex = enrTreeRootText.IndexOf("seq=", StringComparison.InvariantCulture); - int seqLength = enrTreeRootText.IndexOf(" ", seqIndex, StringComparison.InvariantCulture) - (seqIndex + 4); + int seqLength = enrTreeRootText.IndexOf(' ', seqIndex) - (seqIndex + 4); enrTreeRoot.Sequence = int.Parse(enrTreeRootText.AsSpan(seqIndex + 4, seqLength)); int sigIndex = enrTreeRootText.IndexOf("sig=", StringComparison.InvariantCulture); diff --git a/src/Nethermind/Nethermind.Network/ForkInfo.cs b/src/Nethermind/Nethermind.Network/ForkInfo.cs index 6f3c5e6c582..2dfd59abb75 100644 --- a/src/Nethermind/Nethermind.Network/ForkInfo.cs +++ b/src/Nethermind/Nethermind.Network/ForkInfo.cs @@ -86,7 +86,7 @@ public ValidationResult ValidateForkId(ForkId peerId, BlockHeader? head) // Potentially we can parametrize it based on Spec provider, but not worth it for now // We support block forks up to 1,4 bln blocks [MethodImpl(MethodImplOptions.AggressiveInlining)] - bool IsTimestamp(ulong next) => next >= MainnetSpecProvider.GenesisBlockTimestamp; + static bool IsTimestamp(ulong next) => next >= MainnetSpecProvider.GenesisBlockTimestamp; if (head == null) return ValidationResult.Valid; if (!DictForks.TryGetValue(peerId.ForkHash, out (ForkActivation Activation, ForkId Id) found)) diff --git a/src/Nethermind/Nethermind.Network/NetworkNodeDecoder.cs b/src/Nethermind/Nethermind.Network/NetworkNodeDecoder.cs index e714aaee37e..315b17e9791 100644 --- a/src/Nethermind/Nethermind.Network/NetworkNodeDecoder.cs +++ b/src/Nethermind/Nethermind.Network/NetworkNodeDecoder.cs @@ -73,7 +73,7 @@ public int GetLength(NetworkNode item, RlpBehaviors rlpBehaviors) return Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors)); } - private int GetContentLength(NetworkNode item, RlpBehaviors rlpBehaviors) + private static int GetContentLength(NetworkNode item, RlpBehaviors rlpBehaviors) { return Rlp.LengthOf(item.NodeId.Bytes) + Rlp.LengthOf(item.Host) diff --git a/src/Nethermind/Nethermind.Network/P2P/Messages/AddCapabilityMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Messages/AddCapabilityMessageSerializer.cs index cdde08192fc..6acc3f0c59a 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Messages/AddCapabilityMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Messages/AddCapabilityMessageSerializer.cs @@ -32,7 +32,7 @@ public AddCapabilityMessage Deserialize(IByteBuffer byteBuffer) return new AddCapabilityMessage(new Capability(protocolCode, version)); } - private int GetLength(AddCapabilityMessage msg, out int contentLength) + private static int GetLength(AddCapabilityMessage msg, out int contentLength) { contentLength = Rlp.LengthOf(msg.Capability.ProtocolCode.ToLowerInvariant()); contentLength += Rlp.LengthOf(msg.Capability.Version); diff --git a/src/Nethermind/Nethermind.Network/P2P/Messages/DisconnectMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Messages/DisconnectMessageSerializer.cs index d6693214589..8858ddb46e9 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Messages/DisconnectMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Messages/DisconnectMessageSerializer.cs @@ -20,7 +20,7 @@ public void Serialize(IByteBuffer byteBuffer, DisconnectMessage msg) rlpStream.Encode((byte)msg.Reason); } - private int GetLength(DisconnectMessage message, out int contentLength) + private static int GetLength(DisconnectMessage message, out int contentLength) { contentLength = Rlp.LengthOf((byte)message.Reason); diff --git a/src/Nethermind/Nethermind.Network/P2P/Messages/HelloMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Messages/HelloMessageSerializer.cs index dea213406df..64868d0f03d 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Messages/HelloMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Messages/HelloMessageSerializer.cs @@ -35,7 +35,7 @@ public void Serialize(IByteBuffer byteBuffer, HelloMessage msg) stream.Encode(msg.NodeId.Bytes); } - private (int, int) GetLength(HelloMessage msg) + private static (int, int) GetLength(HelloMessage msg) { int contentLength = 0; contentLength += Rlp.LengthOf(msg.P2PVersion); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/PooledTxsRequestor.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/PooledTxsRequestor.cs index 61ba67e486f..3aa898824dc 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/PooledTxsRequestor.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/PooledTxsRequestor.cs @@ -133,13 +133,13 @@ private void AddMarkUnknownHashesEth68(IReadOnlyList hashes, IReadOnlyL } } - private void RequestPooledTransactions(Action send, IReadOnlyList hashesToRequest) + private static void RequestPooledTransactions(Action send, IReadOnlyList hashesToRequest) { send(new GetPooledTransactionsMessage(hashesToRequest)); Metrics.Eth65GetPooledTransactionsRequested++; } - private void RequestPooledTransactionsEth66(Action send, IReadOnlyList hashesToRequest) + private static void RequestPooledTransactionsEth66(Action send, IReadOnlyList hashesToRequest) { GetPooledTransactionsMessage msg65 = new(hashesToRequest); send(new V66.Messages.GetPooledTransactionsMessage() { EthMessage = msg65 }); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/TransactionsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/TransactionsMessageSerializer.cs index a3c23bbfecb..7508e75aefb 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/TransactionsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/TransactionsMessageSerializer.cs @@ -42,7 +42,7 @@ public int GetLength(TransactionsMessage message, out int contentLength) return Rlp.LengthOfSequence(contentLength); } - public Transaction[] DeserializeTxs(RlpStream rlpStream) + public static Transaction[] DeserializeTxs(RlpStream rlpStream) { return Rlp.DecodeArray(rlpStream, RlpBehaviors.InMempoolForm); } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/GetReceiptsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/GetReceiptsMessageSerializer.cs index 25aef824ad9..adadd99357d 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/GetReceiptsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/GetReceiptsMessageSerializer.cs @@ -9,7 +9,7 @@ namespace Nethermind.Network.P2P.Subprotocols.Eth.V63.Messages { public class GetReceiptsMessageSerializer : HashesMessageSerializer { - public GetReceiptsMessage Deserialize(byte[] bytes) + public static GetReceiptsMessage Deserialize(byte[] bytes) { RlpStream rlpStream = bytes.AsRlpStream(); Hash256[] hashes = rlpStream.DecodeArray(itemContext => itemContext.DecodeKeccak()); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V65/Messages/PooledTransactionsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V65/Messages/PooledTransactionsMessageSerializer.cs index 1f5297cf0cf..838c26a1787 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V65/Messages/PooledTransactionsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V65/Messages/PooledTransactionsMessageSerializer.cs @@ -20,7 +20,7 @@ public void Serialize(IByteBuffer byteBuffer, PooledTransactionsMessage message) public PooledTransactionsMessage Deserialize(IByteBuffer byteBuffer) { NettyRlpStream rlpStream = new(byteBuffer); - Transaction[] txs = _txsMessageDeserializer.DeserializeTxs(rlpStream); + Transaction[] txs = TransactionsMessageSerializer.DeserializeTxs(rlpStream); return new PooledTransactionsMessage(txs); } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs index b054f268238..210af8ad776 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/LesProtocolHandler.cs @@ -263,7 +263,7 @@ public void GetCHTData(HelperTrieRequest request, List proofNodes, List< if (headerResult.Length != 1) throw new SubprotocolException($"Unable to find header for block {request.Key.WithoutLeadingZeros().ToArray().ToLongFromBigEndianByteArrayWithoutLeadingZeros()} for GetHelperProofs response."); auxData.Add(Rlp.Encode(headerResult[0]).Bytes); } - proofNodes.AddRange(cht.BuildProof(request.Key, request.SectionIndex, request.FromLevel)); + proofNodes.AddRange(Synchronization.LesSync.CanonicalHashTrie.BuildProof(request.Key, request.SectionIndex, request.FromLevel)); } private BlockHeader _lastSentBlock; diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/AnnounceMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/AnnounceMessageSerializer.cs index e805a3998f0..d91b2bf3905 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/AnnounceMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/AnnounceMessageSerializer.cs @@ -28,7 +28,7 @@ public AnnounceMessage Deserialize(IByteBuffer byteBuffer) return Deserialize(rlpStream); } - private int GetLength(AnnounceMessage message, out int contentLength) + private static int GetLength(AnnounceMessage message, out int contentLength) { contentLength = Rlp.LengthOf(message.HeadHash) + diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/GetHelperTrieProofsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/GetHelperTrieProofsMessageSerializer.cs index 07718fa7a6c..af4c3756c8d 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/GetHelperTrieProofsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/GetHelperTrieProofsMessageSerializer.cs @@ -37,7 +37,7 @@ public void Serialize(IByteBuffer byteBuffer, GetHelperTrieProofsMessage message } } - private int GetRequestLength(HelperTrieRequest request) + private static int GetRequestLength(HelperTrieRequest request) { return Rlp.LengthOf((int)request.SubType) + diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/HelperTrieProofsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/HelperTrieProofsMessageSerializer.cs index 7c56e645c3d..14a11ba6d70 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/HelperTrieProofsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/HelperTrieProofsMessageSerializer.cs @@ -57,7 +57,7 @@ public HelperTrieProofsMessage Deserialize(IByteBuffer byteBuffer) return Deserialize(rlpStream); } - public HelperTrieProofsMessage Deserialize(RlpStream rlpStream) + public static HelperTrieProofsMessage Deserialize(RlpStream rlpStream) { HelperTrieProofsMessage message = new(); rlpStream.ReadSequenceLength(); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/ByteCodesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/ByteCodesMessageSerializer.cs index 168bb3643f7..46f536d81e7 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/ByteCodesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/ByteCodesMessageSerializer.cs @@ -35,7 +35,7 @@ public ByteCodesMessage Deserialize(IByteBuffer byteBuffer) return new ByteCodesMessage(result) { RequestId = requestId }; } - public (int contentLength, int codesLength) GetLength(ByteCodesMessage message) + public static (int contentLength, int codesLength) GetLength(ByteCodesMessage message) { int codesLength = 0; for (int i = 0; i < message.Codes.Length; i++) 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 a99057f8dbc..1178d0c6c45 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/GetTrieNodesMessageSerializer.cs @@ -69,7 +69,7 @@ private PathGroup DecodeGroup(RlpStream stream) return group; } - private (int contentLength, int allPathsLength, int[] pathsLengths) CalculateLengths(GetTrieNodesMessage message) + private static (int contentLength, int allPathsLength, int[] pathsLengths) CalculateLengths(GetTrieNodesMessage message) { int contentLength = Rlp.LengthOf(message.RequestId); contentLength += Rlp.LengthOf(message.RootHash); 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 0ee71b9900d..ea7f1ddb7e8 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/StorageRangesMessageSerializer.cs @@ -88,7 +88,7 @@ private PathWithStorageSlot DecodeSlot(RlpStream stream) return data; } - private (int contentLength, int allSlotsLength, int[] accountSlotsLengths, int proofsLength) CalculateLengths(StorageRangeMessage message) + private static (int contentLength, int allSlotsLength, int[] accountSlotsLengths, int proofsLength) CalculateLengths(StorageRangeMessage message) { int contentLength = Rlp.LengthOf(message.RequestId); diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/TrieNodesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/TrieNodesMessageSerializer.cs index ba01806b10d..436bd1d1833 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/TrieNodesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/Messages/TrieNodesMessageSerializer.cs @@ -36,7 +36,7 @@ public TrieNodesMessage Deserialize(IByteBuffer byteBuffer) return new TrieNodesMessage(result) { RequestId = requestId }; } - public (int contentLength, int nodesLength) GetLength(TrieNodesMessage message) + public static (int contentLength, int nodesLength) GetLength(TrieNodesMessage message) { int nodesLength = 0; for (int i = 0; i < message.Nodes.Length; i++) diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/SnapProtocolHandler.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/SnapProtocolHandler.cs index d9f30bdb47b..7dc648bbf46 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/SnapProtocolHandler.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Snap/SnapProtocolHandler.cs @@ -250,7 +250,7 @@ private async Task GetTrieNodes(ValueHash256 rootHash, PathGroup[] gro return response.Nodes; } - private PathGroup[] GetPathGroups(AccountsToRefreshRequest request) + private static PathGroup[] GetPathGroups(AccountsToRefreshRequest request) { PathGroup[] groups = new PathGroup[request.Paths.Length]; diff --git a/src/Nethermind/Nethermind.Network/ProtocolValidator.cs b/src/Nethermind/Nethermind.Network/ProtocolValidator.cs index d34d8c71cdb..5b7865eb973 100644 --- a/src/Nethermind/Nethermind.Network/ProtocolValidator.cs +++ b/src/Nethermind/Nethermind.Network/ProtocolValidator.cs @@ -83,7 +83,7 @@ private bool Disconnect(ISession session, DisconnectReason reason, Compatibility return false; } - private bool ValidateP2PVersion(byte p2PVersion) => p2PVersion is 4 or 5; + private static bool ValidateP2PVersion(byte p2PVersion) => p2PVersion is 4 or 5; private bool ValidateNetworkId(ulong networkId) => networkId == _blockTree.NetworkId; } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/FrameMacProcessor.cs b/src/Nethermind/Nethermind.Network/Rlpx/FrameMacProcessor.cs index e13301f70e7..990637126e2 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/FrameMacProcessor.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/FrameMacProcessor.cs @@ -207,7 +207,7 @@ private void UpdateMac(KeccakHash mac, KeccakHash macCopy, byte[] seed, int offs } } - private void DoFinalNoReset(KeccakHash mac, KeccakHash macCopy, byte[] output) + private static void DoFinalNoReset(KeccakHash mac, KeccakHash macCopy, byte[] output) { macCopy.ResetTo(mac); macCopy.UpdateFinalTo(output); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthEip8MessageSerializer.cs b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthEip8MessageSerializer.cs index 2aacdc9cdd0..a51ae149752 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthEip8MessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthEip8MessageSerializer.cs @@ -32,7 +32,7 @@ public void Serialize(IByteBuffer byteBuffer, AuthEip8Message msg) _messagePad?.Pad(byteBuffer); } - public int GetLength(AuthEip8Message msg) + public static int GetLength(AuthEip8Message msg) { int contentLength = Rlp.LengthOf(Bytes.Concat(msg.Signature.Bytes, msg.Signature.RecoveryId)) + Rlp.LengthOf(msg.PublicKey.Bytes) diff --git a/src/Nethermind/Nethermind.Network/Rlpx/ZeroPacketSplitter.cs b/src/Nethermind/Nethermind.Network/Rlpx/ZeroPacketSplitter.cs index 2917b343eb0..03ed67d0c29 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/ZeroPacketSplitter.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/ZeroPacketSplitter.cs @@ -116,7 +116,7 @@ protected override void Encode(IChannelHandlerContext context, IByteBuffer input } } - private int WritePacketType(int packetType, IByteBuffer output) + private static int WritePacketType(int packetType, IByteBuffer output) { if (packetType == 0) { diff --git a/src/Nethermind/Nethermind.Network/StaticNodes/StaticNodesManager.cs b/src/Nethermind/Nethermind.Network/StaticNodes/StaticNodesManager.cs index b7c218cd438..e47e2f2dd18 100644 --- a/src/Nethermind/Nethermind.Network/StaticNodes/StaticNodesManager.cs +++ b/src/Nethermind/Nethermind.Network/StaticNodes/StaticNodesManager.cs @@ -33,6 +33,8 @@ public StaticNodesManager(string staticNodesPath, ILogManager logManager) public IEnumerable Nodes => _nodes.Values; + private static readonly char[] separator = new[] { '\r', '\n' }; + public async Task InitAsync() { if (!File.Exists(_staticNodesPath)) @@ -77,7 +79,7 @@ private static string[] GetNodes(string data) } catch (JsonException) { - nodes = data.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + nodes = data.Split(separator, StringSplitOptions.RemoveEmptyEntries); } return nodes.Distinct().ToArray(); diff --git a/src/Nethermind/Nethermind.Serialization.Json/BufferSegmentStack.cs b/src/Nethermind/Nethermind.Serialization.Json/BufferSegmentStack.cs index 09ca1148bbb..1ba71fe1372 100644 --- a/src/Nethermind/Nethermind.Serialization.Json/BufferSegmentStack.cs +++ b/src/Nethermind/Nethermind.Serialization.Json/BufferSegmentStack.cs @@ -20,7 +20,7 @@ public BufferSegmentStack(int size) _size = 0; } - public int Count => _size; + public readonly int Count => _size; public bool TryPop([NotNullWhen(true)] out BufferSegment? result) { diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs index fc1f0226567..ef76caa4744 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/BlockDecoder.cs @@ -261,7 +261,7 @@ public void Encode(RlpStream stream, Block? item, RlpBehaviors rlpBehaviors = Rl } } - public ReceiptRecoveryBlock? DecodeToReceiptRecoveryBlock(MemoryManager? memoryManager, Memory memory, RlpBehaviors rlpBehaviors) + public static ReceiptRecoveryBlock? DecodeToReceiptRecoveryBlock(MemoryManager? memoryManager, Memory memory, RlpBehaviors rlpBehaviors) { Rlp.ValueDecoderContext decoderContext = new Rlp.ValueDecoderContext(memory, true); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/BlockInfoDecoder.cs index 290d21a959b..7b8a97af5c6 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 } } - private int GetContentLength(BlockInfo item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) + private static int GetContentLength(BlockInfo item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { bool hasMetadata = item.Metadata != BlockMetadata.None; int contentLength = 0; diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs index c29daf71e00..0ba3fe93be4 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ChainLevelDecoder.cs @@ -109,7 +109,7 @@ public Rlp Encode(ChainLevelInfo? item, RlpBehaviors rlpBehaviors = RlpBehaviors throw new NotImplementedException(); } - private int GetContentLength(ChainLevelInfo item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) + private static int GetContentLength(ChainLevelInfo item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (item == null) { @@ -132,7 +132,7 @@ public int GetLength(ChainLevelInfo? item, RlpBehaviors rlpBehaviors) return Rlp.LengthOfSequence(contLength); } - private int GetBlockInfoLength(BlockInfo[] item) + private static int GetBlockInfoLength(BlockInfo[] item) { int contentLength = 0; foreach (BlockInfo? blockInfo in item) diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/CompactLogEntryDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/CompactLogEntryDecoder.cs index d603793465a..9d99a9ee474 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/CompactLogEntryDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/CompactLogEntryDecoder.cs @@ -15,7 +15,7 @@ public class CompactLogEntryDecoder : IRlpDecoder { public static CompactLogEntryDecoder Instance { get; } = new(); - public LogEntry? Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) + public static LogEntry? Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (rlpStream.IsNextItemNull()) { @@ -41,7 +41,7 @@ public class CompactLogEntryDecoder : IRlpDecoder return new LogEntry(address, data, topics.ToArray()); } - public LogEntry? Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) + public static LogEntry? Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (decoderContext.IsNextItemNull()) { @@ -67,7 +67,7 @@ public class CompactLogEntryDecoder : IRlpDecoder return new LogEntry(address, data, topics.ToArray()); } - public void DecodeLogEntryStructRef(scoped ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors behaviors, out LogEntryStructRef item) + public static void DecodeLogEntryStructRef(scoped ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors behaviors, out LogEntryStructRef item) { if (decoderContext.IsNextItemNull()) { @@ -91,7 +91,7 @@ public void DecodeLogEntryStructRef(scoped ref Rlp.ValueDecoderContext decoderCo item = new LogEntryStructRef(address, data, topics); } - public Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) + public static Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) { long sequenceLength = valueDecoderContext.ReadSequenceLength(); long untilPosition = valueDecoderContext.Position + sequenceLength; @@ -104,7 +104,7 @@ public Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) return topics.ToArray(); } - public void Encode(RlpStream rlpStream, LogEntry? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) + public static void Encode(RlpStream rlpStream, LogEntry? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) { if (item is null) { diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs index 42526386632..514ea3b8822 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs @@ -50,7 +50,7 @@ public CompactReceiptStorageDecoder() while (rlpStream.Position < lastCheck) { - logEntries.Add(CompactLogEntryDecoder.Instance.Decode(rlpStream, RlpBehaviors.AllowExtraBytes)); + logEntries.Add(CompactLogEntryDecoder.Decode(rlpStream, RlpBehaviors.AllowExtraBytes)); } txReceipt.Logs = logEntries.ToArray(); @@ -98,7 +98,7 @@ public CompactReceiptStorageDecoder() using ArrayPoolList logEntries = new(sequenceLength * 2 / Rlp.LengthOfAddressRlp); while (decoderContext.Position < lastCheck) { - logEntries.Add(CompactLogEntryDecoder.Instance.Decode(ref decoderContext, RlpBehaviors.AllowExtraBytes)); + logEntries.Add(CompactLogEntryDecoder.Decode(ref decoderContext, RlpBehaviors.AllowExtraBytes)); } txReceipt.Logs = logEntries.ToArray(); @@ -152,12 +152,12 @@ public void DecodeStructRef(scoped ref Rlp.ValueDecoderContext decoderContext, R public void DecodeLogEntryStructRef(scoped ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors none, out LogEntryStructRef current) { - CompactLogEntryDecoder.Instance.DecodeLogEntryStructRef(ref decoderContext, none, out current); + CompactLogEntryDecoder.DecodeLogEntryStructRef(ref decoderContext, none, out current); } public Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext) { - return CompactLogEntryDecoder.Instance.DecodeTopics(valueDecoderContext); + return CompactLogEntryDecoder.DecodeTopics(valueDecoderContext); } // Refstruct decode does not generate bloom @@ -201,11 +201,11 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio LogEntry[] logs = item.Logs ?? Array.Empty(); for (int i = 0; i < logs.Length; i++) { - CompactLogEntryDecoder.Instance.Encode(rlpStream, logs[i]); + CompactLogEntryDecoder.Encode(rlpStream, logs[i]); } } - private (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) + private static (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) { int contentLength = 0; if (item is null) @@ -232,7 +232,7 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio return (contentLength, logsLength); } - private int GetLogsLength(TxReceipt item) + private static int GetLogsLength(TxReceipt item) { int logsLength = 0; LogEntry[] logs = item.Logs ?? Array.Empty(); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/KeccakDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/KeccakDecoder.cs index f149f086ccf..89dd7e56486 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/KeccakDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/KeccakDecoder.cs @@ -11,7 +11,7 @@ public class KeccakDecoder : IRlpValueDecoder public Hash256? Decode(ref Rlp.ValueDecoderContext decoderContext, RlpBehaviors rlpBehaviors = RlpBehaviors.None) => decoderContext.DecodeKeccak(); - public Rlp Encode(Hash256 item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) => Rlp.Encode(item); + public static Rlp Encode(Hash256 item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) => Rlp.Encode(item); public int GetLength(Hash256 item, RlpBehaviors rlpBehaviors) => Rlp.LengthOf(item); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs index af1c6563ff2..731ed2c33a7 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs @@ -150,12 +150,12 @@ public TxReceipt DeserializeReceiptObsolete(Hash256 hash, Span receiptData } } - public bool IsCompactEncoding(Span receiptsData) + public static bool IsCompactEncoding(Span receiptsData) { return receiptsData.Length > 0 && receiptsData[0] == CompactEncoding; } - public IReceiptRefDecoder GetRefDecoder(Span receiptsData) + public static IReceiptRefDecoder GetRefDecoder(Span receiptsData) { if (IsCompactEncoding(receiptsData)) { diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptMessageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptMessageDecoder.cs index b7da5faaedb..052a6e766b1 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptMessageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptMessageDecoder.cs @@ -62,7 +62,7 @@ public TxReceipt Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBeha return txReceipt; } - private (int Total, int Logs) GetContentLength(TxReceipt item, RlpBehaviors rlpBehaviors) + private static (int Total, int Logs) GetContentLength(TxReceipt item, RlpBehaviors rlpBehaviors) { if (item is null) { @@ -88,7 +88,7 @@ public TxReceipt Decode(RlpStream rlpStream, RlpBehaviors rlpBehaviors = RlpBeha return (contentLength, logsLength); } - private int GetLogsLength(TxReceipt item) + private static int GetLogsLength(TxReceipt item) { int logsLength = 0; for (var i = 0; i < item.Logs.Length; i++) diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptRecoveryBlock.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptRecoveryBlock.cs index c41c6d4296c..a44d0b8d8b1 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptRecoveryBlock.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptRecoveryBlock.cs @@ -59,10 +59,10 @@ public Transaction GetNextTransaction() return _txBuffer; } - public Hash256? Hash => Header.Hash; // do not add setter here - public long Number => Header.Number; // do not add setter here + public readonly Hash256? Hash => Header.Hash; // do not add setter here + public readonly long Number => Header.Number; // do not add setter here - public void Dispose() + public readonly void Dispose() { ((IMemoryOwner?)_memoryOwner)?.Dispose(); } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs index 6cb512487ec..0aa910bcfdb 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs @@ -255,7 +255,7 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio } } - private (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) + private static (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) { int contentLength = 0; if (item is null) @@ -299,7 +299,7 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio return (contentLength, logsLength); } - private int GetLogsLength(TxReceipt item) + private static int GetLogsLength(TxReceipt item) { int logsLength = 0; for (int i = 0; i < item.Logs.Length; i++) diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs b/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs index dbbddf92d9c..d12de160200 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs @@ -565,15 +565,15 @@ public ValueDecoderContext(Memory memory, bool sliceMemory = false) public Span Data { get; } - public bool IsEmpty => Data.IsEmpty; + public readonly bool IsEmpty => Data.IsEmpty; public int Position { get; set; } - public int Length => Data.Length; + public readonly int Length => Data.Length; - public bool ShouldSliceMemory => _sliceMemory; + public readonly bool ShouldSliceMemory => _sliceMemory; - public bool IsSequenceNext() + public readonly bool IsSequenceNext() { return Data[Position] >= 192; } @@ -782,7 +782,7 @@ private Memory ReadSlicedMemory(int length) return data; } - public void Check(int nextCheck) + public readonly void Check(int nextCheck) { if (Position != nextCheck) { @@ -1065,7 +1065,7 @@ public Span PeekNextItem() return item; } - public bool IsNextItemNull() + public readonly bool IsNextItemNull() { return Data[Position] == 192; } @@ -1269,12 +1269,12 @@ public bool DecodeBool() private string Description => Data[..Math.Min(DebugMessageContentLength, Length)].ToHexString(); - public byte PeekByte() + public readonly byte PeekByte() { return Data[Position]; } - private byte PeekByte(int offset) + private readonly byte PeekByte(int offset) { return Data[Position + offset]; } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs index 1c408d3b6d0..8b8f8148da1 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/TxDecoder.cs @@ -80,7 +80,7 @@ protected virtual T NewTx() switch (transaction.Type) { case TxType.Legacy: - DecodeLegacyPayloadWithoutSig(transaction, rlpStream); + TxDecoder.DecodeLegacyPayloadWithoutSig(transaction, rlpStream); break; case TxType.AccessList: DecodeAccessListPayloadWithoutSig(transaction, rlpStream, rlpBehaviors); @@ -92,7 +92,7 @@ protected virtual T NewTx() DecodeShardBlobPayloadWithoutSig(transaction, rlpStream, rlpBehaviors); break; case TxType.DepositTx: - DecodeDepositPayloadWithoutSig(transaction, rlpStream, rlpBehaviors); + TxDecoder.DecodeDepositPayloadWithoutSig(transaction, rlpStream, rlpBehaviors); break; } @@ -111,7 +111,7 @@ protected virtual T NewTx() switch (transaction.Type) { case TxType.Blob: - DecodeShardBlobNetworkPayload(transaction, rlpStream, rlpBehaviors); + TxDecoder.DecodeShardBlobNetworkPayload(transaction, rlpStream, rlpBehaviors); break; } @@ -175,7 +175,7 @@ private static Hash256 CalculateHashForNetworkPayloadForm(TxType type, Span.DecodeLegacyPayloadWithoutSig(transaction, ref decoderContext, rlpBehaviors); break; case TxType.AccessList: DecodeAccessListPayloadWithoutSig(transaction, ref decoderContext, rlpBehaviors); @@ -457,7 +457,7 @@ public void Decode(ref Rlp.ValueDecoderContext decoderContext, ref T? transactio DecodeShardBlobPayloadWithoutSig(transaction, ref decoderContext, rlpBehaviors); break; case TxType.DepositTx: - DecodeDepositPayloadWithoutSig(transaction, ref decoderContext, rlpBehaviors); + TxDecoder.DecodeDepositPayloadWithoutSig(transaction, ref decoderContext, rlpBehaviors); break; } @@ -476,7 +476,7 @@ public void Decode(ref Rlp.ValueDecoderContext decoderContext, ref T? transactio switch (transaction.Type) { case TxType.Blob: - DecodeShardBlobNetworkPayload(transaction, ref decoderContext, rlpBehaviors); + TxDecoder.DecodeShardBlobNetworkPayload(transaction, ref decoderContext, rlpBehaviors); break; } @@ -642,7 +642,7 @@ private void EncodeTx(RlpStream stream, T? item, RlpBehaviors rlpBehaviors = Rlp switch (item.Type) { case TxType.Legacy: - EncodeLegacyWithoutPayload(item, stream); + TxDecoder.EncodeLegacyWithoutPayload(item, stream); break; case TxType.AccessList: EncodeAccessListPayloadWithoutPayload(item, stream, rlpBehaviors); @@ -654,7 +654,7 @@ private void EncodeTx(RlpStream stream, T? item, RlpBehaviors rlpBehaviors = Rlp EncodeShardBlobPayloadWithoutPayload(item, stream, rlpBehaviors); break; case TxType.DepositTx: - EncodeDepositTxPayloadWithoutPayload(item, stream); + TxDecoder.EncodeDepositTxPayloadWithoutPayload(item, stream); break; } @@ -665,7 +665,7 @@ private void EncodeTx(RlpStream stream, T? item, RlpBehaviors rlpBehaviors = Rlp switch (item.Type) { case TxType.Blob: - EncodeShardBlobNetworkPayload(item, stream, rlpBehaviors); + TxDecoder.EncodeShardBlobNetworkPayload(item, stream, rlpBehaviors); break; } } @@ -703,7 +703,7 @@ private static void EncodeSignature(RlpStream stream, T item, bool forSigning, u } } - private void EncodeShardBlobNetworkPayload(T transaction, RlpStream rlpStream, RlpBehaviors rlpBehaviors) + private static void EncodeShardBlobNetworkPayload(T transaction, RlpStream rlpStream, RlpBehaviors rlpBehaviors) { ShardBlobNetworkWrapper networkWrapper = transaction.NetworkWrapper as ShardBlobNetworkWrapper; rlpStream.Encode(networkWrapper.Blobs); @@ -711,7 +711,7 @@ private void EncodeShardBlobNetworkPayload(T transaction, RlpStream rlpStream, R rlpStream.Encode(networkWrapper.Proofs); } - private int GetLegacyContentLength(T item) + private static int GetLegacyContentLength(T item) { return Rlp.LengthOf(item.Nonce) + Rlp.LengthOf(item.GasPrice) @@ -761,7 +761,7 @@ private int GetShardBlobContentLength(T item) + Rlp.LengthOf(item.BlobVersionedHashes); } - private int GetShardBlobNetworkWrapperContentLength(T item, int txContentLength) + private static int GetShardBlobNetworkWrapperContentLength(T item, int txContentLength) { ShardBlobNetworkWrapper networkWrapper = item.NetworkWrapper as ShardBlobNetworkWrapper; return Rlp.LengthOfSequence(txContentLength) @@ -770,7 +770,7 @@ private int GetShardBlobNetworkWrapperContentLength(T item, int txContentLength) + Rlp.LengthOf(networkWrapper.Proofs); } - private int GetDepositTxContentLength(T item) + private static int GetDepositTxContentLength(T item) { return Rlp.LengthOf(item.SourceHash) + Rlp.LengthOf(item.SenderAddress) @@ -790,7 +790,7 @@ private int GetContentLength(T item, bool forSigning, bool isEip155Enabled = fal switch (item.Type) { case TxType.Legacy: - contentLength = GetLegacyContentLength(item); + contentLength = TxDecoder.GetLegacyContentLength(item); break; case TxType.AccessList: contentLength = GetAccessListContentLength(item); @@ -802,7 +802,7 @@ private int GetContentLength(T item, bool forSigning, bool isEip155Enabled = fal contentLength = GetShardBlobContentLength(item); break; case TxType.DepositTx: - contentLength = GetDepositTxContentLength(item); + contentLength = TxDecoder.GetDepositTxContentLength(item); break; } @@ -812,7 +812,7 @@ private int GetContentLength(T item, bool forSigning, bool isEip155Enabled = fal { if (item.Type == TxType.Blob) { - contentLength = GetShardBlobNetworkWrapperContentLength(item, contentLength); + contentLength = TxDecoder.GetShardBlobNetworkWrapperContentLength(item, contentLength); } } return contentLength; diff --git a/src/Nethermind/Nethermind.Specs/FrontierSpecProvider.cs b/src/Nethermind/Nethermind.Specs/FrontierSpecProvider.cs index ef1ea94c1b7..7d48cdb6292 100644 --- a/src/Nethermind/Nethermind.Specs/FrontierSpecProvider.cs +++ b/src/Nethermind/Nethermind.Specs/FrontierSpecProvider.cs @@ -31,7 +31,7 @@ public void UpdateMergeTransitionInfo(long? blockNumber, UInt256? terminalTotalD public ulong NetworkId => Core.BlockchainIds.Mainnet; public ulong ChainId => NetworkId; - public Hash256 GenesisHash => KnownHashes.MainnetGenesis; + public static Hash256 GenesisHash => KnownHashes.MainnetGenesis; public ForkActivation[] TransitionActivations { get; } = { (ForkActivation)0 }; private FrontierSpecProvider() diff --git a/src/Nethermind/Nethermind.State/StateProvider.cs b/src/Nethermind/Nethermind.State/StateProvider.cs index 588865e6eff..1d0cfa2ac28 100644 --- a/src/Nethermind/Nethermind.State/StateProvider.cs +++ b/src/Nethermind/Nethermind.State/StateProvider.cs @@ -824,7 +824,7 @@ public void CommitTree(long blockNumber) _tree.Commit(blockNumber); } - public void CommitBranch() + public static void CommitBranch() { // placeholder for the three level Commit->CommitBlock->CommitBranch } diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs index c26f226f6a0..bd1c64359a1 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlockDownloader.cs @@ -778,10 +778,10 @@ public AllocationWithCancellation(SyncPeerAllocation allocation, CancellationTok } private CancellationTokenSource Cancellation { get; } - public bool IsCancellationRequested => Cancellation.IsCancellationRequested; + public readonly bool IsCancellationRequested => Cancellation.IsCancellationRequested; public SyncPeerAllocation Allocation { get; } - public void Cancel() + public readonly void Cancel() { lock (Cancellation) { diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs index 3e90d954f43..278a11a0867 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategy.cs @@ -26,7 +26,7 @@ public BlocksSyncPeerAllocationStrategy(long? minBlocksAhead) public bool CanBeReplaced => true; - private long? GetSpeed(INodeStatsManager nodeStatsManager, PeerInfo peerInfo) + private static long? GetSpeed(INodeStatsManager nodeStatsManager, PeerInfo peerInfo) { long? headersSpeed = nodeStatsManager.GetOrAdd(peerInfo.SyncPeer.Node).GetAverageTransferSpeed(TransferSpeedType.Headers); long? bodiesSpeed = nodeStatsManager.GetOrAdd(peerInfo.SyncPeer.Node).GetAverageTransferSpeed(TransferSpeedType.Bodies); diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/SyncBatchSize.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/SyncBatchSize.cs index 113a0d32396..795424cc5d3 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/SyncBatchSize.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/SyncBatchSize.cs @@ -22,9 +22,9 @@ public struct SyncBatchSize public int Current { get; private set; } - public bool IsMin => Current == Min; + public readonly bool IsMin => Current == Min; - public bool IsMax => Current == Max; + public readonly bool IsMax => Current == Max; public SyncBatchSize(ILogManager logManager) { diff --git a/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs b/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs index d852ad5f21e..d6fc854566c 100644 --- a/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs +++ b/src/Nethermind/Nethermind.Synchronization/LesSync/CanonicalHashTrie.cs @@ -37,7 +37,7 @@ public void CommitSectionIndex(long sectionIndex) StoreRootHash(sectionIndex); } - public long GetMaxSectionIndex() + public static long GetMaxSectionIndex() { //return GetMaxSectionIndex(_keyValueStore); return -1; @@ -45,12 +45,12 @@ public long GetMaxSectionIndex() public static long GetSectionFromBlockNo(long blockNo) => (blockNo / SectionSize) - 1L; - public byte[][] BuildProof(long blockNo, long sectionIndex, long fromLevel) + public static byte[][] BuildProof(long blockNo, long sectionIndex, long fromLevel) { return BuildProof(GetKey(blockNo), sectionIndex, fromLevel); } - public byte[][] BuildProof(byte[] key, long sectionIndex, long fromLevel) + public static byte[][] BuildProof(byte[] key, long sectionIndex, long fromLevel) { ChtProofCollector proofCollector = new(key, fromLevel); //Accept(proofCollector, GetRootHash(sectionIndex), false); @@ -126,7 +126,7 @@ private static byte[] GetRootHashKey(long key) return Bytes.Concat(Encoding.ASCII.GetBytes("RootHash"), GetKey(key)); } - private Rlp GetValue(BlockHeader header) + private static Rlp GetValue(BlockHeader header) { if (!header.TotalDifficulty.HasValue) { diff --git a/src/Nethermind/Nethermind.Synchronization/LesSync/ChtDecoder.cs b/src/Nethermind/Nethermind.Synchronization/LesSync/ChtDecoder.cs index ac73de88542..50ca5e4277c 100644 --- a/src/Nethermind/Nethermind.Synchronization/LesSync/ChtDecoder.cs +++ b/src/Nethermind/Nethermind.Synchronization/LesSync/ChtDecoder.cs @@ -48,7 +48,7 @@ public int GetLength((Hash256?, UInt256) item, RlpBehaviors rlpBehaviors) return Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors)); } - private int GetContentLength((Hash256?, UInt256) item, RlpBehaviors rlpBehaviors) + private static int GetContentLength((Hash256?, UInt256) item, RlpBehaviors rlpBehaviors) { (Hash256? hash, UInt256 totalDifficulty) = item; return Rlp.LengthOf(hash) + Rlp.LengthOf(totalDifficulty); diff --git a/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs b/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs index 60530ebeb27..f7f7c40fcd0 100644 --- a/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs +++ b/src/Nethermind/Nethermind.Synchronization/ParallelSync/MultiSyncModeSelector.cs @@ -246,7 +246,7 @@ public void Update() UpdateSyncModes(newModes, reason); } - private void CheckAddFlag(in bool flag, SyncMode mode, ref SyncMode resultMode) + private static void CheckAddFlag(in bool flag, SyncMode mode, ref SyncMode resultMode) { if (flag) { @@ -567,7 +567,7 @@ private bool ShouldBeInFastReceiptsMode(Snapshot best) return result; } - private bool ShouldBeInDisconnectedMode(Snapshot best) + private static bool ShouldBeInDisconnectedMode(Snapshot best) { return !best.IsInUpdatingPivot && !best.IsInFastBodies && @@ -743,7 +743,7 @@ private Snapshot TakeSnapshot(in UInt256 peerDifficulty, long peerBlock, bool in return new(processed, state, block, header, chainDifficulty, Math.Max(peerBlock, 0), peerDifficulty, inBeaconControl, targetBlock); } - private bool IsSnapshotInvalid(Snapshot best) + private static bool IsSnapshotInvalid(Snapshot best) { return // none of these values should ever be negative best.Block < 0 @@ -824,7 +824,7 @@ long targetBlock public bool IsInWaitingForBlock { get; set; } public bool IsInBeaconHeaders { get; set; } public bool IsInBeaconControl { get; } - public bool IsInAnyBeaconMode => IsInBeaconHeaders || IsInBeaconControl; + public readonly bool IsInAnyBeaconMode => IsInBeaconHeaders || IsInBeaconControl; /// /// Best block that has been processed diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/PeerInfo.cs b/src/Nethermind/Nethermind.Synchronization/Peers/PeerInfo.cs index 72de806b171..ca0f4b1cf34 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/PeerInfo.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/PeerInfo.cs @@ -144,7 +144,7 @@ public AllocationContexts IncreaseWeakness(AllocationContexts allocationContexts return sleeps; } - private void ResolveWeaknessChecks(ref int weakness, AllocationContexts singleContext, ref AllocationContexts sleeps) + private static void ResolveWeaknessChecks(ref int weakness, AllocationContexts singleContext, ref AllocationContexts sleeps) { int level = Interlocked.Increment(ref weakness); if (level >= SleepThreshold) diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs index b3e4d4f3ba1..f28a377442c 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeersReport.cs @@ -189,7 +189,7 @@ private void AddPeerInfo(PeerInfo peerInfo) _stringBuilder.Append('[').Append(peerInfo.SyncPeer.ClientId).Append(']'); } - private string GetPaddedAverageTransferSpeed(INodeStats nodeStats, TransferSpeedType transferSpeedType) + private static string GetPaddedAverageTransferSpeed(INodeStats nodeStats, TransferSpeedType transferSpeedType) { long? speed = nodeStats.GetAverageTransferSpeed(transferSpeedType); if (speed is null) @@ -230,7 +230,7 @@ private struct PeersContextCounts public int Snap { get; set; } public int Total { get; set; } - public void AppendTo(StringBuilder sb, string allText) + public readonly void AppendTo(StringBuilder sb, string allText) { if (Total == None) { @@ -248,7 +248,7 @@ public void AppendTo(StringBuilder sb, string allText) if (Witness > 0) AddComma(sb, ref added).Append(Witness).Append(" Witness"); if (Snap > 0) AddComma(sb, ref added).Append(Snap).Append(" Snap"); - StringBuilder AddComma(StringBuilder sb, ref bool itemAdded) + static StringBuilder AddComma(StringBuilder sb, ref bool itemAdded) { if (itemAdded) { diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs index fbdcc51d133..3acdcae49b6 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs @@ -188,7 +188,7 @@ private static (AddRangeResult result, List sortedBoundaryList, bool m else { Span pathSpan = CollectionsMarshal.AsSpan(path); - if (Bytes.Comparer.Compare(pathSpan, leftBoundary[0..path.Count]) >= 0 + if (Bytes.BytesComparer.Compare(pathSpan, leftBoundary[0..path.Count]) >= 0 && parent is not null && parent.IsBranch) { @@ -210,9 +210,9 @@ private static (AddRangeResult result, List sortedBoundaryList, bool m pathIndex++; Span pathSpan = CollectionsMarshal.AsSpan(path); - int left = Bytes.Comparer.Compare(pathSpan, leftBoundary[0..path.Count]) == 0 ? leftBoundary[pathIndex] : 0; - int right = Bytes.Comparer.Compare(pathSpan, rightBoundary[0..path.Count]) == 0 ? rightBoundary[pathIndex] : 15; - int limit = Bytes.Comparer.Compare(pathSpan, rightLimit[0..path.Count]) == 0 ? rightLimit[pathIndex] : 15; + int left = Bytes.BytesComparer.Compare(pathSpan, leftBoundary[0..path.Count]) == 0 ? leftBoundary[pathIndex] : 0; + int right = Bytes.BytesComparer.Compare(pathSpan, rightBoundary[0..path.Count]) == 0 ? rightBoundary[pathIndex] : 15; + int limit = Bytes.BytesComparer.Compare(pathSpan, rightLimit[0..path.Count]) == 0 ? rightLimit[pathIndex] : 15; int maxIndex = moreChildrenToRight ? right : 15; diff --git a/src/Nethermind/Nethermind.Synchronization/SyncServer.cs b/src/Nethermind/Nethermind.Synchronization/SyncServer.cs index 0f23b6f0337..ddbb7a5f153 100644 --- a/src/Nethermind/Nethermind.Synchronization/SyncServer.cs +++ b/src/Nethermind/Nethermind.Synchronization/SyncServer.cs @@ -277,7 +277,7 @@ private void BroadcastBlock(Block block, bool allowHashes, ISyncPeer? nodeWhoSen Task.Run(() => { - double CalculateBroadcastRatio(int minPeers, int peerCount) => peerCount == 0 ? 0 : minPeers / (double)peerCount; + static double CalculateBroadcastRatio(int minPeers, int peerCount) => peerCount == 0 ? 0 : minPeers / (double)peerCount; int peerCount = _pool.PeerCount - (nodeWhoSentTheBlock is null ? 0 : 1); int minPeers = (int)Math.Ceiling(Math.Sqrt(peerCount)); @@ -495,7 +495,7 @@ public Task BuildCHT() long maxSection = CanonicalHashTrie.GetSectionFromBlockNo(_blockTree.FindLatestHeader().Number - Sync.MaxReorgLength); - long maxKnownSection = _cht.GetMaxSectionIndex(); + long maxKnownSection = CanonicalHashTrie.GetMaxSectionIndex(); for (long section = (maxKnownSection + 1); section <= maxSection; section++) { diff --git a/src/Nethermind/Nethermind.Synchronization/Synchronizer.cs b/src/Nethermind/Nethermind.Synchronization/Synchronizer.cs index 3fa163e643f..9f28b227950 100644 --- a/src/Nethermind/Nethermind.Synchronization/Synchronizer.cs +++ b/src/Nethermind/Nethermind.Synchronization/Synchronizer.cs @@ -391,7 +391,7 @@ protected SyncDispatcher CreateDispatcher(ISyncFeed feed, ISyncDownload _logManager); } - private NodeStatsEventType Convert(SyncEvent syncEvent) + private static NodeStatsEventType Convert(SyncEvent syncEvent) { return syncEvent switch { diff --git a/src/Nethermind/Nethermind.Trie/Nibbles.cs b/src/Nethermind/Nethermind.Trie/Nibbles.cs index d5470e2f735..e42cd8afb18 100644 --- a/src/Nethermind/Nethermind.Trie/Nibbles.cs +++ b/src/Nethermind/Nethermind.Trie/Nibbles.cs @@ -7,7 +7,7 @@ namespace Nethermind.Trie { [DebuggerDisplay("{_nibble}")] [DebuggerStepThrough] - public struct Nibble + public readonly struct Nibble { // ReSharper disable once FieldCanBeMadeReadOnly.Local private readonly byte _nibble; diff --git a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs index 537f7dcd311..cdcc6361753 100644 --- a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs +++ b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs @@ -339,7 +339,7 @@ private void SetRootHash(Hash256? value, bool resetObjects) private static void EnhanceException(ReadOnlySpan rawKey, ValueHash256 rootHash, TrieException baseException) { - TrieNodeException? GetTrieNodeException(TrieException? exception) => + static TrieNodeException? GetTrieNodeException(TrieException? exception) => exception switch { null => null, diff --git a/src/Nethermind/Nethermind.Trie/Pruning/NullTrieStore.cs b/src/Nethermind/Nethermind.Trie/Pruning/NullTrieStore.cs index 0c4c6b761de..a1a327dda3d 100644 --- a/src/Nethermind/Nethermind.Trie/Pruning/NullTrieStore.cs +++ b/src/Nethermind/Nethermind.Trie/Pruning/NullTrieStore.cs @@ -17,7 +17,7 @@ public void CommitNode(long blockNumber, NodeCommitInfo nodeCommitInfo, WriteFla public void FinishBlockCommit(TrieType trieType, long blockNumber, TrieNode? root, WriteFlags flags = WriteFlags.None) { } - public void HackPersistOnShutdown() { } + public static void HackPersistOnShutdown() { } public IReadOnlyTrieStore AsReadOnly(IKeyValueStore keyValueStore) => this; @@ -37,6 +37,6 @@ public event EventHandler ReorgBoundaryReached public void Dispose() { } - public byte[]? Get(ReadOnlySpan key, ReadFlags flags = ReadFlags.None) => null; + public static byte[]? Get(ReadOnlySpan key, ReadFlags flags = ReadFlags.None) => null; } } diff --git a/src/Nethermind/Nethermind.Trie/Pruning/ReadOnlyTrieStore.cs b/src/Nethermind/Nethermind.Trie/Pruning/ReadOnlyTrieStore.cs index 943fd8d4453..460cd403a19 100644 --- a/src/Nethermind/Nethermind.Trie/Pruning/ReadOnlyTrieStore.cs +++ b/src/Nethermind/Nethermind.Trie/Pruning/ReadOnlyTrieStore.cs @@ -49,7 +49,7 @@ public event EventHandler ReorgBoundaryReached public void Dispose() { } - public void Set(ReadOnlySpan key, byte[]? value, WriteFlags flags = WriteFlags.None) { } + public static void Set(ReadOnlySpan key, byte[]? value, WriteFlags flags = WriteFlags.None) { } private class ReadOnlyValueStore : IKeyValueStore { diff --git a/src/Nethermind/Nethermind.Trie/TreeDumper.cs b/src/Nethermind/Nethermind.Trie/TreeDumper.cs index a879ea85207..d0e3d061cd7 100644 --- a/src/Nethermind/Nethermind.Trie/TreeDumper.cs +++ b/src/Nethermind/Nethermind.Trie/TreeDumper.cs @@ -37,10 +37,10 @@ public void VisitTree(Hash256 rootHash, TrieVisitContext trieVisitContext) } } - private string GetPrefix(TrieVisitContext context) => string.Concat($"{GetIndent(context.Level)}", context.IsStorage ? "STORAGE " : string.Empty, $"{GetChildIndex(context)}"); + private static 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 is null ? string.Empty : $"{context.BranchChildIndex:x2} "; + private static string GetIndent(int level) => new('+', level * 2); + private static string GetChildIndex(TrieVisitContext context) => context.BranchChildIndex is null ? string.Empty : $"{context.BranchChildIndex:x2} "; public void VisitMissingNode(Hash256 nodeHash, TrieVisitContext trieVisitContext) { @@ -86,7 +86,7 @@ public override string ToString() return _builder.ToString(); } - private string? KeccakOrRlpStringOfNode(TrieNode node) + private static string? KeccakOrRlpStringOfNode(TrieNode node) { return node.Keccak != null ? node.Keccak!.Bytes.ToHexString() : node.FullRlp.AsSpan().ToHexString(); } diff --git a/src/Nethermind/Nethermind.Trie/TrieNode.Decoder.cs b/src/Nethermind/Nethermind.Trie/TrieNode.Decoder.cs index 0d1a420cfc1..a8bf54f78ba 100644 --- a/src/Nethermind/Nethermind.Trie/TrieNode.Decoder.cs +++ b/src/Nethermind/Nethermind.Trie/TrieNode.Decoder.cs @@ -23,7 +23,7 @@ public partial class TrieNode private class TrieNodeDecoder { - public CappedArray Encode(ITrieNodeResolver tree, TrieNode? item, ICappedArrayPool? bufferPool) + public static CappedArray Encode(ITrieNodeResolver tree, TrieNode? item, ICappedArrayPool? bufferPool) { Metrics.TreeNodeRlpEncodings++; diff --git a/src/Nethermind/Nethermind.Trie/TrieNode.cs b/src/Nethermind/Nethermind.Trie/TrieNode.cs index 3c7bc48b6d0..f65a5decc5a 100644 --- a/src/Nethermind/Nethermind.Trie/TrieNode.cs +++ b/src/Nethermind/Nethermind.Trie/TrieNode.cs @@ -420,7 +420,7 @@ public bool TryResolveStorageRootHash(ITrieNodeResolver resolver, out Hash256? s internal CappedArray RlpEncode(ITrieNodeResolver tree, ICappedArrayPool? bufferPool = null) { - CappedArray rlp = _nodeDecoder.Encode(tree, this, bufferPool); + CappedArray rlp = TrieNodeDecoder.Encode(tree, this, bufferPool); // just included here to improve the class reading // after some analysis I believe that any non-test Ethereum cases of a trie ever have nodes with RLP shorter than 32 bytes // if (rlp.Bytes.Length < 32) diff --git a/src/Nethermind/Nethermind.Trie/VisitContext.cs b/src/Nethermind/Nethermind.Trie/VisitContext.cs index cfe6655398d..00308e2a5ce 100644 --- a/src/Nethermind/Nethermind.Trie/VisitContext.cs +++ b/src/Nethermind/Nethermind.Trie/VisitContext.cs @@ -79,7 +79,7 @@ public SmallTrieVisitContext(TrieVisitContext trieVisitContext) public bool IsStorage { - get => (_flags & StorageFlag) == StorageFlag; + readonly get => (_flags & StorageFlag) == StorageFlag; internal set { if (value) @@ -95,7 +95,7 @@ internal set public bool ExpectAccounts { - get => (_flags & ExpectAccountsFlag) == ExpectAccountsFlag; + readonly get => (_flags & ExpectAccountsFlag) == ExpectAccountsFlag; internal set { if (value) @@ -111,7 +111,7 @@ internal set public byte? BranchChildIndex { - get => _branchChildIndex == 255 ? null : _branchChildIndex; + readonly get => _branchChildIndex == 255 ? null : _branchChildIndex; internal set { if (value == null) diff --git a/src/Nethermind/Nethermind.TxPool/BlobTxStorage.cs b/src/Nethermind/Nethermind.TxPool/BlobTxStorage.cs index 732221942e2..68f399b7fd2 100644 --- a/src/Nethermind/Nethermind.TxPool/BlobTxStorage.cs +++ b/src/Nethermind/Nethermind.TxPool/BlobTxStorage.cs @@ -69,7 +69,7 @@ public void Add(Transaction transaction) rlpStream.Encode(transaction, RlpBehaviors.InMempoolForm); _fullBlobTxsDb.PutSpan(txHashPrefixed, byteBuffer.AsSpan()); - _lightBlobTxsDb.Set(transaction.Hash, _lightTxDecoder.Encode(transaction)); + _lightBlobTxsDb.Set(transaction.Hash, LightTxDecoder.Encode(transaction)); } public void Delete(in ValueHash256 hash, in UInt256 timestamp) @@ -99,7 +99,7 @@ private static bool TryDecodeLightTx(byte[]? txBytes, out LightTransaction? ligh { if (txBytes is not null) { - lightTx = _lightTxDecoder.Decode(txBytes); + lightTx = LightTxDecoder.Decode(txBytes); return true; } @@ -107,7 +107,7 @@ private static bool TryDecodeLightTx(byte[]? txBytes, out LightTransaction? ligh return false; } - private void GetHashPrefixedByTimestamp(UInt256 timestamp, ValueHash256 hash, Span txHashPrefixed) + private static void GetHashPrefixedByTimestamp(UInt256 timestamp, ValueHash256 hash, Span txHashPrefixed) { timestamp.WriteBigEndian(txHashPrefixed); hash.Bytes.CopyTo(txHashPrefixed[32..]); diff --git a/src/Nethermind/Nethermind.TxPool/LightTxDecoder.cs b/src/Nethermind/Nethermind.TxPool/LightTxDecoder.cs index aa5680d7427..a6fc5916fa5 100644 --- a/src/Nethermind/Nethermind.TxPool/LightTxDecoder.cs +++ b/src/Nethermind/Nethermind.TxPool/LightTxDecoder.cs @@ -8,7 +8,7 @@ namespace Nethermind.TxPool; public class LightTxDecoder : TxDecoder { - private int GetLength(Transaction tx) + private static int GetLength(Transaction tx) { return Rlp.LengthOf(tx.Timestamp) + Rlp.LengthOf(tx.SenderAddress) @@ -25,7 +25,7 @@ private int GetLength(Transaction tx) } - public byte[] Encode(Transaction tx) + public static byte[] Encode(Transaction tx) { RlpStream rlpStream = new(GetLength(tx)); @@ -45,7 +45,7 @@ public byte[] Encode(Transaction tx) return rlpStream.Data!; } - public LightTransaction Decode(byte[] data) + public static LightTransaction Decode(byte[] data) { RlpStream rlpStream = new(data); return new LightTransaction( diff --git a/src/Nethermind/Nethermind.TxPool/NonceLocker.cs b/src/Nethermind/Nethermind.TxPool/NonceLocker.cs index 391c8f81f81..adb66af21e9 100644 --- a/src/Nethermind/Nethermind.TxPool/NonceLocker.cs +++ b/src/Nethermind/Nethermind.TxPool/NonceLocker.cs @@ -29,7 +29,7 @@ public void Dispose() } } - public void Accept() + public readonly void Accept() { _acceptAction(); } diff --git a/src/Nethermind/Nethermind.TxPool/NullTxPool.cs b/src/Nethermind/Nethermind.TxPool/NullTxPool.cs index d495b09cbbd..cc1a85322ca 100644 --- a/src/Nethermind/Nethermind.TxPool/NullTxPool.cs +++ b/src/Nethermind/Nethermind.TxPool/NullTxPool.cs @@ -28,7 +28,7 @@ public IDictionary GetPendingTransactionsBySender() public IDictionary GetPendingLightBlobTransactionsBySender() => new Dictionary(); - public IEnumerable GetPendingBlobTransactions() => Array.Empty(); + public static IEnumerable GetPendingBlobTransactions() => Array.Empty(); public void AddPeer(ITxPoolPeer peer) { } From 60b9fac414084ca16454ae28270eef4131324b1f Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:31:30 +0000 Subject: [PATCH 2/9] Hashtable Contains+Add -> Add --- .../InvalidChainTracker/InvalidChainTracker.cs | 3 +-- src/Nethermind/Nethermind.Network.Dns/EnrTreeCrawler.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs index 94dc8abafbf..d766bf188ff 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/InvalidChainTracker/InvalidChainTracker.cs @@ -98,9 +98,8 @@ private void PropagateLastValidHash(Node node) if (childNode.LastValidHash != current.LastValidHash) { childNode.LastValidHash = current.LastValidHash; - if (!visited.Contains(childNode)) + if (visited.Add(childNode)) { - visited.Add(childNode); bfsQue.Enqueue(childNode); } } diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrTreeCrawler.cs b/src/Nethermind/Nethermind.Network.Dns/EnrTreeCrawler.cs index ecd894df694..2951a691bf9 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrTreeCrawler.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrTreeCrawler.cs @@ -50,9 +50,8 @@ private async IAsyncEnumerable SearchTree(DnsClient client, SearchContex private async IAsyncEnumerable SearchNode(IDnsClient client, string query, SearchContext searchContext) { - if (!searchContext.VisitedRefs.Contains(query)) + if (searchContext.VisitedRefs.Add(query)) { - searchContext.VisitedRefs.Add(query); IEnumerable lookupResult = await client.Lookup(query); foreach (string node in lookupResult) { From 38f5d82e163bb83348ebe87bebc62985e4956b4c Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:31:48 +0000 Subject: [PATCH 3/9] Hashtable Contains+Remove -> Remove --- src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs | 3 +-- .../Nethermind.Network.Discovery/RoutingTable/NodeBucket.cs | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs b/src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs index 513ace3ff10..239f76c1600 100644 --- a/src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs +++ b/src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs @@ -34,9 +34,8 @@ public bool ShouldVisit(Hash256 nextNode) _logger.Warn($"Ignore count leak -> {_ignoreThisOne.Count}"); } - if (_ignoreThisOne.Contains(nextNode)) + if (_ignoreThisOne.Remove(nextNode)) { - _ignoreThisOne.Remove(nextNode); return false; } diff --git a/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeBucket.cs b/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeBucket.cs index 9fb1f8c8e85..80953c79a57 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeBucket.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/RoutingTable/NodeBucket.cs @@ -112,9 +112,8 @@ public void ReplaceNode(Node nodeToRemove, Node nodeToAdd) lock (_nodeBucketLock) { NodeBucketItem item = new(nodeToRemove, DateTime.Now); - if (_items.Contains(item)) + if (_items.Remove(item)) { - _items.Remove(item); AddNode(nodeToAdd); } } From 6e4f81222ad2a5a82e73f34ce86b3a4533893634 Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:32:10 +0000 Subject: [PATCH 4/9] Span Fill(0) -> Clear() --- src/Nethermind/Nethermind.Trie/TrackingCappedArrayPool.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.Trie/TrackingCappedArrayPool.cs b/src/Nethermind/Nethermind.Trie/TrackingCappedArrayPool.cs index 73c8c41d525..13aeb87fbdc 100644 --- a/src/Nethermind/Nethermind.Trie/TrackingCappedArrayPool.cs +++ b/src/Nethermind/Nethermind.Trie/TrackingCappedArrayPool.cs @@ -35,7 +35,7 @@ public CappedArray Rent(int size) } CappedArray rented = new CappedArray(_arrayPool.Rent(size), size); - rented.AsSpan().Fill(0); + rented.AsSpan().Clear(); _rentedBuffers.Add(rented); return rented; } From 3eb4381507a42af6b6ea2d9f27908b0b3f6dfacc Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:48:25 +0000 Subject: [PATCH 5/9] Fix Ethereum tests --- src/Nethermind/Ethereum.PoW.Test/EthashTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nethermind/Ethereum.PoW.Test/EthashTests.cs b/src/Nethermind/Ethereum.PoW.Test/EthashTests.cs index 065ec1da9a1..9540b8788e7 100644 --- a/src/Nethermind/Ethereum.PoW.Test/EthashTests.cs +++ b/src/Nethermind/Ethereum.PoW.Test/EthashTests.cs @@ -85,7 +85,7 @@ public void Test(EthashTest test) Assert.That(Bytes.AreEqual(test.Result.Bytes, resultHalfTest), Is.True, "half test"); // here we confirm that the whole mix hash calculation is fine - (byte[] mixHash, ValueHash256 result, bool success) = ethash.Hashimoto((ulong)test.FullSize, cache, headerHash, blockHeader.MixHash, test.Nonce); + (byte[] mixHash, ValueHash256 result, bool success) = Ethash.Hashimoto((ulong)test.FullSize, cache, headerHash, blockHeader.MixHash, test.Nonce); Assert.That(Bytes.AreEqual(mixHash, test.MixHash.Bytes), Is.True, "mix hash"); Assert.That(Bytes.AreEqual(result.Bytes, test.Result.Bytes), Is.True, "result"); From ef748033fb9e109247ea4ea26690ba8f451bce9b Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 02:51:26 +0000 Subject: [PATCH 6/9] Whitespace --- src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs b/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs index 19c9be22f84..c6c71525a5d 100644 --- a/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs +++ b/src/Nethermind/Nethermind.Core/Buffers/CappedArray.cs @@ -45,7 +45,8 @@ public static implicit operator CappedArray(T[]? array) } public int Length - { readonly get => _length; + { + readonly get => _length; set => _length = value; } From b2ab4596c1f7fb8a5addcc223b3832fc5366490d Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 03:08:45 +0000 Subject: [PATCH 7/9] Fix --- .../Modules/Subscribe/JsonRpcSubscriptionResponse.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs index 54694343907..5c791e392a0 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Subscribe/JsonRpcSubscriptionResponse.cs @@ -12,7 +12,7 @@ public class JsonRpcSubscriptionResponse : JsonRpcResponse [JsonPropertyName("method")] [JsonPropertyOrder(1)] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public new static string MethodName => "eth_subscription"; + public new string MethodName => "eth_subscription"; [JsonPropertyName("params")] [JsonPropertyOrder(2)] From 612dbc8ced7454e50f4906ab9b617267c6280830 Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 03:27:10 +0000 Subject: [PATCH 8/9] Fix benchmarks --- .../Nethermind.Network.Benchmark/KdfDerivationBenchmarks.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/Nethermind/Nethermind.Network.Benchmark/KdfDerivationBenchmarks.cs b/src/Nethermind/Nethermind.Network.Benchmark/KdfDerivationBenchmarks.cs index ef27c04d262..94fa19ff537 100644 --- a/src/Nethermind/Nethermind.Network.Benchmark/KdfDerivationBenchmarks.cs +++ b/src/Nethermind/Nethermind.Network.Benchmark/KdfDerivationBenchmarks.cs @@ -11,12 +11,10 @@ public class KdfDerivationBenchmarks { private static byte[] _z = Bytes.FromHexString("22ca1111ca383ef9d090ca567245eb72f80d8730fd4e1507e9a23bcdb3bb5a87"); - private OptimizedKdf _current = new OptimizedKdf(); - [Benchmark] public byte[] Current() { - var result = _current.Derive(_z); + var result = OptimizedKdf.Derive(_z); return result; } } From 0812020a28063960a5ba0db6d5ec8e8a1f5ad352 Mon Sep 17 00:00:00 2001 From: benaadams Date: Fri, 15 Dec 2023 11:06:46 +0000 Subject: [PATCH 9/9] Remove unneeded methods --- src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs | 1 - .../Nethermind.Blockchain/Receipts/NullReceiptStorage.cs | 6 ------ src/Nethermind/Nethermind.Hive/HiveRunner.cs | 5 ----- 3 files changed, 12 deletions(-) diff --git a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs index ddec2fca480..8fdeb68242a 100644 --- a/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs +++ b/src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs @@ -57,7 +57,6 @@ public BlockHeader? LowestInsertedBeaconHeader public Block Head => _wrapped.Head; public void MarkChainAsProcessed(IReadOnlyList blocks) => throw new InvalidOperationException($"{nameof(ReadOnlyBlockTree)} does not expect {nameof(MarkChainAsProcessed)} calls"); public (BlockInfo Info, ChainLevelInfo Level) GetInfo(long number, Hash256 blockHash) => _wrapped.GetInfo(number, blockHash); - public static UInt256? UpdateTotalDifficulty(Block block, UInt256 totalDifficulty) => throw new InvalidOperationException(); public bool CanAcceptNewBlocks { get; } = false; public async Task Accept(IBlockTreeVisitor blockTreeVisitor, CancellationToken cancellationToken) diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs index bc50321c05e..22f6b7fdc21 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/NullReceiptStorage.cs @@ -37,12 +37,6 @@ public long? LowestInsertedReceiptBlockNumber public long MigratedBlockNumber { get; set; } = 0; - public static event EventHandler ReceiptsInserted - { - add { } - remove { } - } - public bool HasBlock(long blockNumber, Hash256 hash) { return false; diff --git a/src/Nethermind/Nethermind.Hive/HiveRunner.cs b/src/Nethermind/Nethermind.Hive/HiveRunner.cs index 2f0ad1e2aba..40ffbb0d5a0 100644 --- a/src/Nethermind/Nethermind.Hive/HiveRunner.cs +++ b/src/Nethermind/Nethermind.Hive/HiveRunner.cs @@ -112,11 +112,6 @@ private void ListEnvironmentVariables() } } - public static async Task StopAsync() - { - await Task.CompletedTask; - } - private async Task InitializeBlocks(string blocksDir, CancellationToken cancellationToken) { if (!Directory.Exists(blocksDir))