From 276bfaaccaff8729ca006ca74dbb5a1eb02271a4 Mon Sep 17 00:00:00 2001 From: benaadams Date: Sun, 23 Apr 2023 01:12:05 +0100 Subject: [PATCH] Modernise C# --- .../Nethermind.Abi/AbiDefinition.cs | 2 +- src/Nethermind/Nethermind.Abi/AbiUInt.cs | 2 +- .../UserOperationSubscribeTests.cs | 4 +-- .../AccountAbstractionPlugin.cs | 10 ++---- .../Executor/UserOperationSimulator.cs | 5 +-- .../Network/AccountAbstractionPeerManager.cs | 2 +- .../NewPendingUserOpsSubscription.cs | 4 +-- .../NewReceivedUserOpsSubscription.cs | 4 +-- .../Receipts/InMemoryReceiptStorage.cs | 2 +- .../Console/AutoCompletionHandler.cs | 4 +-- .../Nethermind.Cli/Modules/NodeCliModule.cs | 4 +-- .../Nethermind.Config/ConfigProvider.cs | 2 +- .../Nethermind.Config/ConfigSourceHelper.cs | 2 +- .../Nethermind.Config/JsonConfigSource.cs | 8 ++--- .../Nethermind.Config/StringExtensions.cs | 4 +-- .../AuRaBlockProcessor.cs | 3 +- ...afeContractDataStoreCollectionDecorator.cs | 2 +- .../StartBlockProducerAuRa.cs | 2 +- .../Transactions/RandomContractTxSource.cs | 4 +-- .../Transactions/TxPermissionFilter.cs | 2 +- .../BlockHeaderExtensions.cs | 3 +- .../CliqueSealer.cs | 2 +- .../SnapshotManager.cs | 4 +-- .../EthashDifficultyCalculator.cs | 2 +- .../HintBasedCache.cs | 3 +- .../NethDevPlugin.cs | 3 +- .../Nethermind.Consensus/MiningConfig.cs | 5 +-- .../Nethermind.Consensus/Tracing/Tracer.cs | 2 +- src/Nethermind/Nethermind.Core/Bytes32.cs | 2 +- .../Collections/CompactStack.cs | 5 +-- .../Collections/SpanConcurrentDictionary.cs | 6 ++-- .../Collections/SpanDictionary.cs | 13 +++---- .../Nethermind.Core/Crypto/Keccak.cs | 12 +++---- .../Nethermind.Core/Crypto/PublicKey.cs | 6 ++-- src/Nethermind/Nethermind.Core/Crypto/Root.cs | 2 +- .../Nethermind.Core/Crypto/Signature.cs | 2 +- .../Nethermind.Core/Extensions/Bytes.cs | 12 +++---- .../Extensions/HexConverter.cs | 2 +- src/Nethermind/Nethermind.Core/Platform.cs | 2 +- .../Nethermind.Crypto/EciesCipher.cs | 2 +- .../Nethermind.Crypto/EthereumEcdsa.cs | 2 +- src/Nethermind/Nethermind.Crypto/Keccak512.cs | 2 +- src/Nethermind/Nethermind.Db/DbProvider.cs | 2 +- .../Nethermind.Db/RocksDbInitializer.cs | 2 +- .../Clients/EthStatsClient.cs | 3 +- src/Nethermind/Nethermind.Evm/EvmStack.cs | 4 +-- .../Precompiles/Blake2FPrecompile.cs | 2 +- .../Precompiles/EcRecoverPrecompile.cs | 8 ++--- .../Nethermind.Evm/Precompiles/Extensions.cs | 4 +-- .../Precompiles/ModExpPrecompile.cs | 12 +++---- .../Precompiles/ModExpPrecompilePreEip2565.cs | 6 ++-- .../Snarks/Shamatar/Bn256PairingPrecompile.cs | 4 +-- .../Tracing/ParityStyle/ParityLikeTxTracer.cs | 4 +-- .../Nethermind.Evm/VirtualMachine.cs | 4 +-- .../Nethermind.Facade/BlockchainBridge.cs | 5 +-- .../Nethermind.Facade/Filters/FilterStore.cs | 3 +- .../Nethermind.Facade/Filters/LogFinder.cs | 5 +-- .../Proxy/JsonRpcClientProxy.cs | 2 +- .../Nethermind.Init/Cpu/Frequency.cs | 3 +- .../Nethermind.Init/Cpu/ProcCpuInfoParser.cs | 19 +++++----- .../Cpu/ProcCpuInfoProvider.cs | 2 +- .../Nethermind.Init/Cpu/SectionsHelper.cs | 7 ++-- .../Nethermind.Init/Cpu/TimeInterval.cs | 8 ++--- .../Nethermind.Init/MemoryHintMan.cs | 1 - .../Nethermind.Init/Steps/FilterBootnodes.cs | 3 +- .../Client/BasicJsonRpcClient.cs | 2 +- .../Modules/Admin/NodeInfo.cs | 6 ++-- .../Modules/Parity/PeerInfo.cs | 6 ++-- .../Nethermind.KeyStore/FileKeyStore.cs | 2 +- .../StackTraceUtils.cs | 8 ++--- .../Nethermind.Logging/ConsoleAsyncLogger.cs | 2 +- .../Nethermind.Merge.Plugin/MergePlugin.cs | 2 +- .../MemMerkleTreeStore.cs | 2 +- .../Nethermind.Merkleization/Merkle.cs | 36 +++++++++---------- .../Nethermind.Merkleization/ShaMerkleTree.cs | 2 +- .../MonitoringService.cs | 2 +- .../Serializers/DiscoveryMsgSerializerBase.cs | 6 ++-- .../SyncPeerProtocolHandlerBase.cs | 5 +-- .../Eth/V62/Messages/BlockBodiesMessage.cs | 2 +- .../Eth/V63/Messages/ReceiptsMessage.cs | 3 +- .../V63/Messages/ReceiptsMessageSerializer.cs | 2 +- .../Messages/BlockBodiesMessageSerializer.cs | 2 +- .../Nethermind.Network/PeerManager.cs | 2 +- .../Handshake/AuthEip8MessageSerializer.cs | 4 +-- .../Rlpx/Handshake/AuthMessageSerializer.cs | 2 +- .../Rlpx/Handshake/HandshakeService.cs | 2 +- .../Rlpx/ZeroFrameEncoder.cs | 2 +- .../Logging/NLogConfigurator.cs | 5 +-- src/Nethermind/Nethermind.Secp256k1/Proxy.cs | 2 +- .../AccountDecoder.cs | 9 ++--- .../CompactReceiptStorageDecoder.cs | 3 +- .../ReceiptArrayStorageDecoder.cs | 2 +- .../ReceiptStorageDecoder.cs | 3 +- .../Nethermind.Serialization.Rlp/Rlp.cs | 22 ++++++------ .../Nethermind.Serialization.Rlp/RlpStream.cs | 14 ++++---- .../HashUtility.cs | 2 +- .../Ssz.BasicTypes.cs | 4 +-- .../Ssz.BitArray.cs | 4 +-- .../Nethermind.Sockets/Extensions.cs | 2 +- .../ChainSpecLoaderExtensions.cs | 6 ++-- .../BlockDownloaderTests.cs | 2 +- .../FastBlocks/FastHeadersSyncFeed.cs | 3 +- .../FastSync/TreeSync.cs | 10 +++--- .../Peers/SyncPeerExtensions.cs | 2 +- .../SnapSync/SnapProviderHelper.cs | 7 ++-- src/Nethermind/Nethermind.Trie/HexPrefix.cs | 2 +- .../Nethermind.Trie/PatriciaTree.cs | 11 +++--- .../Nethermind.TxPool.Test/TxPoolTests.cs | 5 +-- .../Collections/SortedPool.cs | 5 +-- src/Nethermind/Nethermind.TxPool/TxPool.cs | 5 +-- 110 files changed, 234 insertions(+), 277 deletions(-) diff --git a/src/Nethermind/Nethermind.Abi/AbiDefinition.cs b/src/Nethermind/Nethermind.Abi/AbiDefinition.cs index 28af0bb0157..1adcccdfc8b 100644 --- a/src/Nethermind/Nethermind.Abi/AbiDefinition.cs +++ b/src/Nethermind/Nethermind.Abi/AbiDefinition.cs @@ -62,6 +62,6 @@ public void Add(AbiErrorDescription @error) public AbiEventDescription GetEvent(string name, bool camelCase = false) => _events[camelCase ? GetName(name) : name]; public AbiErrorDescription GetError(string name, bool camelCase = false) => _errors[camelCase ? GetName(name) : name]; - public static string GetName(string name) => char.IsUpper(name[0]) ? char.ToLowerInvariant(name[0]) + name.Substring(1) : name; + public static string GetName(string name) => char.IsUpper(name[0]) ? char.ToLowerInvariant(name[0]) + name[1..] : name; } } diff --git a/src/Nethermind/Nethermind.Abi/AbiUInt.cs b/src/Nethermind/Nethermind.Abi/AbiUInt.cs index 479416ebf32..0a40a9a9d2c 100644 --- a/src/Nethermind/Nethermind.Abi/AbiUInt.cs +++ b/src/Nethermind/Nethermind.Abi/AbiUInt.cs @@ -89,7 +89,7 @@ public override (object, int) Decode(byte[] data, int position, bool packed) public override byte[] Encode(object? arg, bool packed) { - Span bytes = null; + Span bytes; if (arg is UInt256 uint256) { bytes = ((BigInteger)uint256).ToBigEndianByteArray(); diff --git a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationSubscribeTests.cs b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationSubscribeTests.cs index 2c77e6d1cc6..b285aeaea91 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationSubscribeTests.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction.Test/UserOperationSubscribeTests.cs @@ -182,7 +182,7 @@ public void NewPendingUserOperationsSubscription_creating_result_with_wrong_entr "newPendingUserOperations", "{\"entryPoints\":[\"" + _entryPointAddress + "\", \"" + "0x123" + "\"]}"); string beginningOfExpectedResult = "{\"jsonrpc\":\"2.0\",\"error\":"; - beginningOfExpectedResult.Should().Be(serialized.Substring(0, beginningOfExpectedResult.Length)); + beginningOfExpectedResult.Should().Be(serialized[..beginningOfExpectedResult.Length]); } [Test] @@ -243,7 +243,7 @@ public void NewReceivedUserOperationsSubscription_creating_result_with_wrong_ent "eth_subscribe", "newPendingUserOperations", "{\"entryPoints\":[\"" + _entryPointAddress + "\", \"" + "0x123" + "\"]}"); string beginningOfExpectedResult = "{\"jsonrpc\":\"2.0\",\"error\":"; - beginningOfExpectedResult.Should().Be(serialized.Substring(0, beginningOfExpectedResult.Length)); + beginningOfExpectedResult.Should().Be(serialized[..beginningOfExpectedResult.Length]); } [Test] diff --git a/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs b/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs index 3a83cbf6855..cb545205169 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/AccountAbstractionPlugin.cs @@ -147,9 +147,7 @@ private UserOperationTxSource UserOperationTxSource { get { - if (_userOperationTxSource is null) - { - _userOperationTxSource = new UserOperationTxSource + _userOperationTxSource ??= new UserOperationTxSource ( _userOperationTxBuilders, _userOperationPools, @@ -159,7 +157,6 @@ private UserOperationTxSource UserOperationTxSource _nethermindApi.EngineSigner!, _logger ); - } return _userOperationTxSource; } @@ -169,10 +166,7 @@ private IUserOperationBroadcaster UserOperationBroadcaster { get { - if (_userOperationBroadcaster is null) - { - _userOperationBroadcaster = new UserOperationBroadcaster(_logger); - } + _userOperationBroadcaster ??= new UserOperationBroadcaster(_logger); return _userOperationBroadcaster; } diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs b/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs index af1dc856027..60ce68bfcea 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Executor/UserOperationSimulator.cs @@ -242,10 +242,7 @@ private void CallAndRestore( bool treatBlockHeaderAsParentBlock, ITxTracer tracer) { - if (transaction.SenderAddress is null) - { - transaction.SenderAddress = Address.SystemUser; - } + transaction.SenderAddress ??= Address.SystemUser; if (transaction.Nonce == 0) { diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Network/AccountAbstractionPeerManager.cs b/src/Nethermind/Nethermind.AccountAbstraction/Network/AccountAbstractionPeerManager.cs index 32d115aa1af..833b53dab31 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Network/AccountAbstractionPeerManager.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Network/AccountAbstractionPeerManager.cs @@ -53,7 +53,7 @@ public void AddPeer(IUserOperationPoolPeer peer) { entryPoints[counter] = kv.Key; userOperations[counter] = kv.Value.GetUserOperations().ToArray(); - totalLength = totalLength + userOperations[counter].Length; + totalLength += userOperations[counter].Length; counter++; } UserOperationWithEntryPoint[] userOperationsWithEntryPoints = new UserOperationWithEntryPoint[totalLength]; diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs index 14ae4b96957..7d58ff24692 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs @@ -65,11 +65,11 @@ private void OnNewPending(object? sender, UserOperationEventArgs e) JsonRpcResult result; if (_includeUserOperations) { - result = CreateSubscriptionMessage(new { UserOperation = new UserOperationRpc(e.UserOperation), EntryPoint = e.EntryPoint }); + result = CreateSubscriptionMessage(new { UserOperation = new UserOperationRpc(e.UserOperation), e.EntryPoint }); } else { - result = CreateSubscriptionMessage(new { UserOperation = e.UserOperation.RequestId, EntryPoint = e.EntryPoint }); + result = CreateSubscriptionMessage(new { UserOperation = e.UserOperation.RequestId, e.EntryPoint }); } JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) _logger.Trace($"newPendingUserOperations subscription {Id} printed hash of newPendingUserOperations."); diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs index f59839bfb8d..b72b9952615 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs @@ -66,11 +66,11 @@ private void OnNewReceived(object? sender, UserOperationEventArgs e) JsonRpcResult result; if (_includeUserOperations) { - result = CreateSubscriptionMessage(new { UserOperation = new UserOperationRpc(e.UserOperation), EntryPoint = e.EntryPoint }); + result = CreateSubscriptionMessage(new { UserOperation = new UserOperationRpc(e.UserOperation), e.EntryPoint }); } else { - result = CreateSubscriptionMessage(new { UserOperation = e.UserOperation.RequestId, EntryPoint = e.EntryPoint }); + result = CreateSubscriptionMessage(new { UserOperation = e.UserOperation.RequestId, e.EntryPoint }); } JsonRpcDuplexClient.SendJsonRpcResult(result); if (_logger.IsTrace) _logger.Trace($"newReceivedUserOperations subscription {Id} printed hash of newReceivedUserOperations."); diff --git a/src/Nethermind/Nethermind.Blockchain/Receipts/InMemoryReceiptStorage.cs b/src/Nethermind/Nethermind.Blockchain/Receipts/InMemoryReceiptStorage.cs index aaa7ef618a6..680c0354861 100644 --- a/src/Nethermind/Nethermind.Blockchain/Receipts/InMemoryReceiptStorage.cs +++ b/src/Nethermind/Nethermind.Blockchain/Receipts/InMemoryReceiptStorage.cs @@ -39,7 +39,7 @@ public TxReceipt[] Get(Keccak blockHash) return receipts; } - return new TxReceipt[] { }; + return Array.Empty(); } public bool CanGetReceiptsByHash(long blockNumber) => true; diff --git a/src/Nethermind/Nethermind.Cli/Console/AutoCompletionHandler.cs b/src/Nethermind/Nethermind.Cli/Console/AutoCompletionHandler.cs index f8817d657ad..722a1d43a13 100644 --- a/src/Nethermind/Nethermind.Cli/Console/AutoCompletionHandler.cs +++ b/src/Nethermind/Nethermind.Cli/Console/AutoCompletionHandler.cs @@ -24,7 +24,7 @@ public AutoCompletionHandler(CliModuleLoader cliModuleLoader) public string[] GetSuggestions(string text, int index) { string[] suggestions = Array.Empty(); - if (text.IndexOf('.') == -1) + if (!text.Contains('.')) { suggestions = _cliModuleLoader.ModuleNames.OrderBy(x => x).Where(x => x.StartsWith(text)).ToArray(); } @@ -33,7 +33,7 @@ public string[] GetSuggestions(string text, int index) { if (text.StartsWith($"{moduleName}.")) { - string methodPart = text.Substring(text.IndexOf('.') + 1); + string methodPart = text[(text.IndexOf('.') + 1)..]; suggestions = _cliModuleLoader.MethodsByModules[moduleName].Where(x => x.StartsWith(methodPart)).OrderBy(x => x).ToArray(); break; } diff --git a/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs b/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs index 18197e159b0..17aab3c5727 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs @@ -24,9 +24,9 @@ public string SetNodeKey(string key) [CliFunction("node", "switch")] public string Switch(string uri) { - if (!uri.Contains(":")) + if (!uri.Contains(':')) { - uri = uri + ":8545"; + uri += ":8545"; } if (!uri.StartsWith("http://") && !uri.StartsWith("https://")) diff --git a/src/Nethermind/Nethermind.Config/ConfigProvider.cs b/src/Nethermind/Nethermind.Config/ConfigProvider.cs index f7d780a1a62..035c92e4fa6 100644 --- a/src/Nethermind/Nethermind.Config/ConfigProvider.cs +++ b/src/Nethermind/Nethermind.Config/ConfigProvider.cs @@ -73,7 +73,7 @@ public void Initialize() if (directImplementation is not null) { - Categories.Add(@interface.Name.Substring(1), + Categories.Add(@interface.Name[1..], Activator.CreateInstance(directImplementation)); _implementations[@interface] = directImplementation; diff --git a/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs b/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs index 1f4c957909b..7f402e56f30 100644 --- a/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs +++ b/src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs @@ -43,7 +43,7 @@ public static object ParseValue(Type valueType, string valueString, string categ string item = valueItem; if (valueItem.StartsWith('"') && valueItem.EndsWith('"')) { - item = valueItem.Substring(1, valueItem.Length - 2); + item = valueItem[1..^1]; } var itemValue = GetValue(itemType, item); diff --git a/src/Nethermind/Nethermind.Config/JsonConfigSource.cs b/src/Nethermind/Nethermind.Config/JsonConfigSource.cs index 8b6ccbdf4f3..ee5110c3ee5 100644 --- a/src/Nethermind/Nethermind.Config/JsonConfigSource.cs +++ b/src/Nethermind/Nethermind.Config/JsonConfigSource.cs @@ -61,10 +61,8 @@ private void LoadJsonConfig(string configFilePath) { // do nothing - the lines above just give extra info and config is loaded at the beginning so unlikely we have any catastrophic errors here } - finally - { - throw new IOException(missingConfigFileMessage.ToString()); - } + + throw new IOException(missingConfigFileMessage.ToString()); } ApplyJsonConfig(File.ReadAllText(configFilePath)); @@ -98,7 +96,7 @@ private void ApplyConfigValues(string configModule, Dictionary i { if (!configModule.EndsWith("Config")) { - configModule = configModule + "Config"; + configModule += "Config"; } _values[configModule] = items; diff --git a/src/Nethermind/Nethermind.Config/StringExtensions.cs b/src/Nethermind/Nethermind.Config/StringExtensions.cs index bd27e0a38d9..6aa6fcb2ddb 100644 --- a/src/Nethermind/Nethermind.Config/StringExtensions.cs +++ b/src/Nethermind/Nethermind.Config/StringExtensions.cs @@ -6,9 +6,9 @@ namespace Nethermind.Config public static class StringExtensions { public static string RemoveStart(this string thisString, char removeChar) => - thisString.StartsWith(removeChar) ? thisString.Substring(1, thisString.Length - 1) : thisString; + thisString.StartsWith(removeChar) ? thisString[1..] : thisString; public static string RemoveEnd(this string thisString, char removeChar) => - thisString.EndsWith(removeChar) ? thisString.Substring(0, thisString.Length - 1) : thisString; + thisString.EndsWith(removeChar) ? thisString[..^1] : thisString; } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs index c7647a6d065..e269a6e030e 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/AuRaBlockProcessor.cs @@ -110,8 +110,7 @@ private BlockHeader GetParentHeader(Block block) => private void ValidateGasLimit(Block block) { BlockHeader parentHeader = GetParentHeader(block); - long? expectedGasLimit = null; - if (_gasLimitOverride?.IsGasLimitValid(parentHeader, block.GasLimit, out expectedGasLimit) == false) + if (_gasLimitOverride?.IsGasLimitValid(parentHeader, block.GasLimit, out long? expectedGasLimit) == false) { if (_logger.IsWarn) _logger.Warn($"Invalid gas limit for block {block.Number}, hash {block.Hash}, expected value from contract {expectedGasLimit}, but found {block.GasLimit}."); throw new InvalidBlockException(block); diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ThreadSafeContractDataStoreCollectionDecorator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ThreadSafeContractDataStoreCollectionDecorator.cs index 71d5c7056fd..e6b3758ab99 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ThreadSafeContractDataStoreCollectionDecorator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Contracts/DataStore/ThreadSafeContractDataStoreCollectionDecorator.cs @@ -51,7 +51,7 @@ public void Remove(IEnumerable items) public bool TryGetValue(T key, out T value) { // ReSharper disable once InconsistentlySynchronizedField - if (!(_inner is IDictionaryContractDataStoreCollection dictionaryContractDataStoreCollection)) + if (_inner is not IDictionaryContractDataStoreCollection dictionaryContractDataStoreCollection) { throw new InvalidOperationException("Inner collection is not dictionary based."); } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs index 1f4c445f172..b88d1504194 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/InitializationSteps/StartBlockProducerAuRa.cs @@ -55,7 +55,7 @@ private IAuRaStepCalculator StepCalculator { get { - return _stepCalculator ?? (_stepCalculator = new AuRaStepCalculator(_api.ChainSpec.AuRa.StepDuration, _api.Timestamper, _api.LogManager)); + return _stepCalculator ??= new AuRaStepCalculator(_api.ChainSpec.AuRa.StepDuration, _api.Timestamper, _api.LogManager); } } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/RandomContractTxSource.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/RandomContractTxSource.cs index a5a53836335..a578cd96ccd 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/RandomContractTxSource.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/RandomContractTxSource.cs @@ -94,7 +94,7 @@ public IEnumerable GetTransactions(BlockHeader parent, long gasLimi { using (privateKey) { - bytes = _eciesCipher.Decrypt(privateKey, cipher).Item2; + bytes = _eciesCipher.Decrypt(privateKey, cipher).PlainText; } } else @@ -108,7 +108,7 @@ public IEnumerable GetTransactions(BlockHeader parent, long gasLimi // But we need to fallback to node key here when we upgrade version. // This is temporary code after all validators are upgraded we can remove it. using PrivateKey privateKey = _previousCryptoKey.Unprotect(); - bytes = _eciesCipher.Decrypt(privateKey, cipher).Item2; + bytes = _eciesCipher.Decrypt(privateKey, cipher).PlainText; } if (bytes?.Length != 32) diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs index d0f7daa66a3..fcd9b2bfc7f 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Transactions/TxPermissionFilter.cs @@ -47,7 +47,7 @@ public AcceptTxResult IsAllowed(Transaction tx, BlockHeader parentHeader) private (ITransactionPermissionContract.TxPermissions Permissions, bool ContractExists) GetPermissions(Transaction tx, BlockHeader parentHeader) { - var key = (parentHeader.Hash, SenderAddress: tx.SenderAddress); + var key = (parentHeader.Hash, tx.SenderAddress); return _cache.Permissions.TryGet(key, out var txCachedPermissions) ? txCachedPermissions : GetPermissionsFromContract(tx, parentHeader, key); diff --git a/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs b/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs index 3608f8b00d4..4921948d9e6 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/BlockHeaderExtensions.cs @@ -20,8 +20,7 @@ internal static Address[] ExtractSigners(BlockHeader blockHeader) throw new Exception(string.Empty); } - Span signersData = blockHeader.ExtraData.AsSpan() - .Slice(Clique.ExtraVanityLength, blockHeader.ExtraData.Length - Clique.ExtraSealLength - Clique.ExtraVanityLength); + Span signersData = blockHeader.ExtraData.AsSpan(Clique.ExtraVanityLength, (blockHeader.ExtraData.Length - Clique.ExtraSealLength)); Address[] signers = new Address[signersData.Length / Address.ByteLength]; for (int i = 0; i < signers.Length; i++) { diff --git a/src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs b/src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs index 31f956a626f..8cd7f3d8024 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs @@ -71,7 +71,7 @@ public CliqueSealer(ISigner signer, ICliqueConfig config, ISnapshotManager snaps Array.Copy(signatureBytes, 0, header.ExtraData, header.ExtraData.Length - Clique.ExtraSealLength, signatureBytes.Length); // Copy signature's recovery id (V) byte recoveryId = signature.RecoveryId; - header.ExtraData[header.ExtraData.Length - 1] = recoveryId; + header.ExtraData[^1] = recoveryId; return block; } diff --git a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs index 7524098ac7f..d3d6d16d09b 100644 --- a/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs +++ b/src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs @@ -91,7 +91,7 @@ public static Keccak CalculateCliqueHeaderHash(BlockHeader blockHeader) public Snapshot GetOrCreateSnapshot(long number, Keccak hash) { Snapshot? snapshot = GetSnapshot(number, hash); - if (!(snapshot is null)) + if (snapshot is not null) { return snapshot; } @@ -138,7 +138,7 @@ public Snapshot GetOrCreateSnapshot(long number, Keccak hash) // No snapshot for this header, gather the header and move backward headers.Add(header); - number = number - 1; + number--; hash = header.ParentHash; } diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs b/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs index 963eed34c42..d996c365e6a 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/EthashDifficultyCalculator.cs @@ -82,7 +82,7 @@ private BigInteger TimeAdjustment( private BigInteger TimeBomb(IReleaseSpec spec, long blockNumber) { - blockNumber = blockNumber - spec.DifficultyBombDelay; + blockNumber -= spec.DifficultyBombDelay; return blockNumber < InitialDifficultyBombBlock ? BigInteger.Zero : BigInteger.Pow(2, (int)(BigInteger.Divide(blockNumber, 100000) - 2)); } diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/HintBasedCache.cs b/src/Nethermind/Nethermind.Consensus.Ethash/HintBasedCache.cs index 871ec1bd4fb..bf9f0a42f21 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/HintBasedCache.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/HintBasedCache.cs @@ -111,9 +111,8 @@ public void Hint(Guid guid, long start, long end) if (_epochRefs[epoch] == 1) { // _logger.Warn($"Building data set for epoch {epoch}"); - if (_recent.ContainsKey(epoch)) + if (_recent.Remove(epoch, out DataSetWithTime reused)) { - _recent.Remove(epoch, out DataSetWithTime reused); _cachedSets[epoch] = reused.DataSet; } else diff --git a/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs b/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs index 024cc39fb35..6d2b0f0ead6 100644 --- a/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs +++ b/src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs @@ -43,7 +43,8 @@ public Task InitBlockProducer(IBlockProductionTrigger? blockProd { return Task.FromResult((IBlockProducer)null); } - var (getFromApi, setInApi) = _nethermindApi!.ForProducer; + + var (getFromApi, _) = _nethermindApi!.ForProducer; ReadOnlyDbProvider readOnlyDbProvider = getFromApi.DbProvider.AsReadOnly(false); ReadOnlyBlockTree readOnlyBlockTree = getFromApi.BlockTree.AsReadOnly(); diff --git a/src/Nethermind/Nethermind.Consensus/MiningConfig.cs b/src/Nethermind/Nethermind.Consensus/MiningConfig.cs index db9e5ae9aca..b3abd0b054e 100644 --- a/src/Nethermind/Nethermind.Consensus/MiningConfig.cs +++ b/src/Nethermind/Nethermind.Consensus/MiningConfig.cs @@ -65,10 +65,7 @@ public IBlocksConfig? BlocksConfig get { // Lazt initalisation due to the awaiting of interface defaults application on assembly - if (_blocksConfig is null) - { - _blocksConfig = new BlocksConfig(); - } + _blocksConfig ??= new BlocksConfig(); return _blocksConfig; } diff --git a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs index 89232edff0f..118c0bf40eb 100644 --- a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs +++ b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs @@ -31,7 +31,7 @@ We also want to make it read only so the state is not modified persistently in a blockTracer.StartNewBlockTrace(block); - Block? processedBlock = null; + Block? processedBlock; try { processedBlock = _blockProcessor.Process(block, _processingOptions, blockTracer); diff --git a/src/Nethermind/Nethermind.Core/Bytes32.cs b/src/Nethermind/Nethermind.Core/Bytes32.cs index 4d9da084f8d..0d21fa5372b 100644 --- a/src/Nethermind/Nethermind.Core/Bytes32.cs +++ b/src/Nethermind/Nethermind.Core/Bytes32.cs @@ -99,6 +99,6 @@ public override bool Equals(object? obj) public override int GetHashCode() { - return BinaryPrimitives.ReadInt32LittleEndian(AsSpan().Slice(0, 4)); + return BinaryPrimitives.ReadInt32LittleEndian(AsSpan()[..4]); } } diff --git a/src/Nethermind/Nethermind.Core/Collections/CompactStack.cs b/src/Nethermind/Nethermind.Core/Collections/CompactStack.cs index 53573829505..bcade1d9fde 100644 --- a/src/Nethermind/Nethermind.Core/Collections/CompactStack.cs +++ b/src/Nethermind/Nethermind.Core/Collections/CompactStack.cs @@ -60,10 +60,7 @@ public CompactStack(ObjectPool? nodePool = null) public void Push(T item) { - if (_head == null) - { - _head = _nodePool.Get(); - } + _head ??= _nodePool.Get(); if (_head._count == _head._array.Length) { diff --git a/src/Nethermind/Nethermind.Core/Collections/SpanConcurrentDictionary.cs b/src/Nethermind/Nethermind.Core/Collections/SpanConcurrentDictionary.cs index 7af48a2beef..37db95f22ab 100644 --- a/src/Nethermind/Nethermind.Core/Collections/SpanConcurrentDictionary.cs +++ b/src/Nethermind/Nethermind.Core/Collections/SpanConcurrentDictionary.cs @@ -1543,7 +1543,7 @@ void IDictionary.Add(object key, object? value) { ArgumentNullException.ThrowIfNull(key); - if (!(key is TKey)) + if (key is not TKey) { throw new ArgumentException("The key was of an incorrect type for this dictionary."); } @@ -1664,7 +1664,7 @@ void IDictionary.Remove(object key) { ArgumentNullException.ThrowIfNull(key); - if (!(key is TKey)) + if (key is not TKey) { throw new ArgumentException("The key was of an incorrect type for this dictionary."); } @@ -1680,7 +1680,7 @@ private static void ThrowIfInvalidObjectValue(object? value) { if (value != null) { - if (!(value is TValue)) + if (value is not TValue) { throw new ArgumentException("The value was of an incorrect type for this dictionary."); } diff --git a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs index a968d93831e..d5a59349018 100644 --- a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs +++ b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs @@ -654,14 +654,14 @@ public virtual void OnDeserialization(object? sender) KeyValuePair[]? array = (KeyValuePair[]?) siInfo.GetValue(KeyValuePairsName, typeof(KeyValuePair[])); - if (array == null) + if (array is null) { throw new SerializationException("The Keys for this Hashtable are missing."); } for (int i = 0; i < array.Length; i++) { - if (array[i].Key == null) + if (array[i].Key is null) { throw new SerializationException("One of the serialized keys is null."); } @@ -915,8 +915,7 @@ void ICollection.CopyTo(Array array, int index) } else { - object[]? objects = array as object[]; - if (objects == null) + if (array is not object[] objects) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection."); } @@ -1365,8 +1364,7 @@ void ICollection.CopyTo(Array array, int index) } else { - object[]? objects = array as object[]; - if (objects == null) + if (array is not object[] objects) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection."); } @@ -1543,8 +1541,7 @@ void ICollection.CopyTo(Array array, int index) } else { - object[]? objects = array as object[]; - if (objects == null) + if (array is not object[] objects) { throw new ArgumentException("Target array type is not compatible with the type of items in the collection."); } diff --git a/src/Nethermind/Nethermind.Core/Crypto/Keccak.cs b/src/Nethermind/Nethermind.Core/Crypto/Keccak.cs index edbf59ba741..7b36a782a3f 100644 --- a/src/Nethermind/Nethermind.Core/Crypto/Keccak.cs +++ b/src/Nethermind/Nethermind.Core/Crypto/Keccak.cs @@ -26,7 +26,7 @@ namespace Nethermind.Core.Crypto /// /// 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 /// - public static readonly ValueKeccak OfAnEmptyString = InternalCompute(new byte[] { }); + public static readonly ValueKeccak OfAnEmptyString = InternalCompute(Array.Empty()); /// /// 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 @@ -145,7 +145,7 @@ public override string ToString() public string ToShortString(bool withZeroX = true) { string hash = BytesAsSpan.ToHexString(withZeroX); - return $"{hash.Substring(0, withZeroX ? 8 : 6)}...{hash.Substring(hash.Length - 6)}"; + return $"{hash[..(withZeroX ? 8 : 6)]}...{hash[^6..]}"; } public string ToString(bool withZeroX) @@ -209,7 +209,7 @@ public bool Equals(KeccakKey other) public override bool Equals(object? obj) { - return obj is KeccakKey && Equals((KeccakKey)obj); + return obj is KeccakKey key && Equals(key); } public override int GetHashCode() @@ -244,7 +244,7 @@ public class Keccak : IEquatable, IComparable /// /// 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 /// - public static readonly Keccak OfAnEmptyString = InternalCompute(new byte[] { }); + public static readonly Keccak OfAnEmptyString = InternalCompute(Array.Empty()); /// /// 0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347 @@ -289,7 +289,7 @@ public override string ToString() public string ToShortString(bool withZeroX = true) { string hash = Bytes.ToHexString(withZeroX); - return $"{hash.Substring(0, withZeroX ? 8 : 6)}...{hash.Substring(hash.Length - 6)}"; + return $"{hash[..(withZeroX ? 8 : 6)]}...{hash[^6..]}"; } public string ToString(bool withZeroX) @@ -437,7 +437,7 @@ public override string ToString() public string ToShortString(bool withZeroX = true) { string hash = Bytes.ToHexString(withZeroX); - return $"{hash.Substring(0, withZeroX ? 8 : 6)}...{hash.Substring(hash.Length - 6)}"; + return $"{hash[..(withZeroX ? 8 : 6)]}...{hash[^6..]}"; } public string ToString(bool withZeroX) diff --git a/src/Nethermind/Nethermind.Core/Crypto/PublicKey.cs b/src/Nethermind/Nethermind.Core/Crypto/PublicKey.cs index 9ef4f04313c..ca2f3ef87e2 100644 --- a/src/Nethermind/Nethermind.Core/Crypto/PublicKey.cs +++ b/src/Nethermind/Nethermind.Core/Crypto/PublicKey.cs @@ -80,13 +80,13 @@ public bool Equals(PublicKey? other) private Address ComputeAddress() { Span hash = ValueKeccak.Compute(Bytes).BytesAsSpan; - return new Address(hash.Slice(12).ToArray()); + return new Address(hash[12..].ToArray()); } public static Address ComputeAddress(ReadOnlySpan publicKeyBytes) { Span hash = ValueKeccak.Compute(publicKeyBytes).BytesAsSpan; - return new Address(hash.Slice(12).ToArray()); + return new Address(hash[12..].ToArray()); } public override bool Equals(object? obj) @@ -112,7 +112,7 @@ public string ToString(bool with0X) public string ToShortString() { string value = Bytes.ToHexString(false); - return $"{value.Substring(0, 6)}...{value.Substring(value.Length - 6)}"; + return $"{value[..6]}...{value[^6..]}"; } public static bool operator ==(PublicKey? a, PublicKey? b) diff --git a/src/Nethermind/Nethermind.Core/Crypto/Root.cs b/src/Nethermind/Nethermind.Core/Crypto/Root.cs index 3a9b576f572..f92636af3a7 100644 --- a/src/Nethermind/Nethermind.Core/Crypto/Root.cs +++ b/src/Nethermind/Nethermind.Core/Crypto/Root.cs @@ -72,7 +72,7 @@ public ReadOnlySpan AsSpan() public override int GetHashCode() { - return BinaryPrimitives.ReadInt32LittleEndian(AsSpan().Slice(0, 4)); + return BinaryPrimitives.ReadInt32LittleEndian(AsSpan()[..4]); } public static bool operator ==(Root left, Root right) diff --git a/src/Nethermind/Nethermind.Core/Crypto/Signature.cs b/src/Nethermind/Nethermind.Core/Crypto/Signature.cs index 33b2c652aa9..abe035dfff0 100644 --- a/src/Nethermind/Nethermind.Core/Crypto/Signature.cs +++ b/src/Nethermind/Nethermind.Core/Crypto/Signature.cs @@ -31,7 +31,7 @@ public Signature(ReadOnlySpan bytes) throw new ArgumentException(); } - bytes.Slice(0, 64).CopyTo(Bytes.AsSpan()); + bytes[..64].CopyTo(Bytes.AsSpan()); V = bytes[64]; } diff --git a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs index 5b3cd06b275..20ccabbd2aa 100644 --- a/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs +++ b/src/Nethermind/Nethermind.Core/Extensions/Bytes.cs @@ -118,7 +118,7 @@ public int Compare(Span x, Span y) public static readonly byte[] Zero32 = new byte[32]; - public static readonly byte[] Empty = new byte[0]; + public static readonly byte[] Empty = Array.Empty(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool GetBit(this byte b, int bitNumber) @@ -224,7 +224,7 @@ public static byte[] PadLeft(this Span bytes, int length, byte padding = 0 if (bytes.Length > length) { - return bytes.Slice(0, length).ToArray(); + return bytes[..length].ToArray(); } byte[] result = new byte[length]; @@ -337,7 +337,7 @@ public static uint ReadEthUInt32(this ReadOnlySpan bytes) } Span fourBytes = stackalloc byte[4]; - bytes.CopyTo(fourBytes.Slice(4 - bytes.Length)); + bytes.CopyTo(fourBytes[(4 - bytes.Length)..]); return BinaryPrimitives.ReadUInt32BigEndian(fourBytes); } @@ -354,7 +354,7 @@ public static uint ReadEthUInt32LittleEndian(this Span bytes) } Span fourBytes = stackalloc byte[4]; - bytes.CopyTo(fourBytes.Slice(4 - bytes.Length)); + bytes.CopyTo(fourBytes[(4 - bytes.Length)..]); return BinaryPrimitives.ReadUInt32LittleEndian(fourBytes); } @@ -376,7 +376,7 @@ public static int ReadEthInt32(this ReadOnlySpan bytes) } Span fourBytes = stackalloc byte[4]; - bytes.CopyTo(fourBytes.Slice(4 - bytes.Length)); + bytes.CopyTo(fourBytes[(4 - bytes.Length)..]); return BinaryPrimitives.ReadInt32BigEndian(fourBytes); } @@ -398,7 +398,7 @@ public static ulong ReadEthUInt64(this ReadOnlySpan bytes) } Span eightBytes = stackalloc byte[8]; - bytes.CopyTo(eightBytes.Slice(8 - bytes.Length)); + bytes.CopyTo(eightBytes[(8 - bytes.Length)..]); return BinaryPrimitives.ReadUInt64BigEndian(eightBytes); } diff --git a/src/Nethermind/Nethermind.Core/Extensions/HexConverter.cs b/src/Nethermind/Nethermind.Core/Extensions/HexConverter.cs index 8a219c18274..fd072cdf98d 100644 --- a/src/Nethermind/Nethermind.Core/Extensions/HexConverter.cs +++ b/src/Nethermind/Nethermind.Core/Extensions/HexConverter.cs @@ -339,7 +339,7 @@ public static bool TryDecodeFromUtf16_Vector128(ReadOnlySpan chars, Span diff --git a/src/Nethermind/Nethermind.Core/Platform.cs b/src/Nethermind/Nethermind.Core/Platform.cs index aeccb8e9e6e..0a1edc4a532 100644 --- a/src/Nethermind/Nethermind.Core/Platform.cs +++ b/src/Nethermind/Nethermind.Core/Platform.cs @@ -37,7 +37,7 @@ private static OSPlatform GetPlatform() public class Platform { - public static String GetPlatformName() + public static string GetPlatformName() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { diff --git a/src/Nethermind/Nethermind.Crypto/EciesCipher.cs b/src/Nethermind/Nethermind.Crypto/EciesCipher.cs index 8c6a1314377..e26ec7ca1ea 100644 --- a/src/Nethermind/Nethermind.Crypto/EciesCipher.cs +++ b/src/Nethermind/Nethermind.Crypto/EciesCipher.cs @@ -78,7 +78,7 @@ private byte[] Decrypt(PublicKey ephemeralPublicKey, PrivateKey privateKey, byte return iesEngine.ProcessBlock(ciphertextBody, 0, ciphertextBody.Length, macData); } - private static IesParameters _iesParameters = new IesWithCipherParameters(new byte[] { }, new byte[] { }, KeySize, KeySize); + private static IesParameters _iesParameters = new IesWithCipherParameters(Array.Empty(), Array.Empty(), KeySize, KeySize); private IIesEngine MakeIesEngine(bool isEncrypt, PublicKey publicKey, PrivateKey privateKey, byte[] iv) { diff --git a/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs b/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs index 1b18176518d..5964145d82b 100644 --- a/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs +++ b/src/Nethermind/Nethermind.Crypto/EthereumEcdsa.cs @@ -123,7 +123,7 @@ public bool Verify(Address sender, Transaction tx) bool success = Proxy.RecoverKeyFromCompact( publicKey, message.Bytes, - signatureBytes.Slice(0, 64), + signatureBytes[..64], signatureBytes[64], false); diff --git a/src/Nethermind/Nethermind.Crypto/Keccak512.cs b/src/Nethermind/Nethermind.Crypto/Keccak512.cs index 18306a7c6dd..4530b8b2f5a 100644 --- a/src/Nethermind/Nethermind.Crypto/Keccak512.cs +++ b/src/Nethermind/Nethermind.Crypto/Keccak512.cs @@ -23,7 +23,7 @@ public Keccak512(byte[] bytes) Bytes = bytes; } - public static Keccak512 OfAnEmptyString = InternalCompute(new byte[] { }); + public static Keccak512 OfAnEmptyString = InternalCompute(Array.Empty()); /// /// 0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 diff --git a/src/Nethermind/Nethermind.Db/DbProvider.cs b/src/Nethermind/Nethermind.Db/DbProvider.cs index b03067f0bf4..14c03ad77eb 100644 --- a/src/Nethermind/Nethermind.Db/DbProvider.cs +++ b/src/Nethermind/Nethermind.Db/DbProvider.cs @@ -37,7 +37,7 @@ public T GetDb(string dbName) where T : class, IDb throw new ArgumentException($"{dbName} database has not been registered in {nameof(DbProvider)}."); } - if (!(found is T result)) + if (found is not T result) { throw new IOException( $"An attempt was made to resolve DB {dbName} as {typeof(T)} while its type is {found.GetType()}."); diff --git a/src/Nethermind/Nethermind.Db/RocksDbInitializer.cs b/src/Nethermind/Nethermind.Db/RocksDbInitializer.cs index e9a659c7a4d..f4c422cf36f 100644 --- a/src/Nethermind/Nethermind.Db/RocksDbInitializer.cs +++ b/src/Nethermind/Nethermind.Db/RocksDbInitializer.cs @@ -68,6 +68,6 @@ protected async Task InitAllAsync() await Task.WhenAll(allInitializers); } - protected static string GetTitleDbName(string dbName) => char.ToUpper(dbName[0]) + dbName.Substring(1); + protected static string GetTitleDbName(string dbName) => char.ToUpper(dbName[0]) + dbName[1..]; } } diff --git a/src/Nethermind/Nethermind.EthStats/Clients/EthStatsClient.cs b/src/Nethermind/Nethermind.EthStats/Clients/EthStatsClient.cs index 8c5acb80a11..e6d47686a70 100644 --- a/src/Nethermind/Nethermind.EthStats/Clients/EthStatsClient.cs +++ b/src/Nethermind/Nethermind.EthStats/Clients/EthStatsClient.cs @@ -38,8 +38,7 @@ public EthStatsClient( internal string BuildUrl() { string websocketUrl = _urlFromConfig; - Uri? websocketUri; - if (!Uri.TryCreate(_urlFromConfig, UriKind.Absolute, out websocketUri)) + if (!Uri.TryCreate(_urlFromConfig, UriKind.Absolute, out Uri? websocketUri)) { ThrowIncorrectUrl(); } diff --git a/src/Nethermind/Nethermind.Evm/EvmStack.cs b/src/Nethermind/Nethermind.Evm/EvmStack.cs index 781efd10e4d..76d8dc89429 100644 --- a/src/Nethermind/Nethermind.Evm/EvmStack.cs +++ b/src/Nethermind/Nethermind.Evm/EvmStack.cs @@ -71,7 +71,7 @@ public void PushBytes(scoped in ZeroPaddedSpan value) if (value.Span.Length != 32) { word.Clear(); - value.Span.CopyTo(word.Slice(0, value.Span.Length)); + value.Span.CopyTo(word[..value.Span.Length]); } else { @@ -93,7 +93,7 @@ public void PushBytes(scoped in ZeroPaddedMemory value) if (value.Memory.Length != 32) { word.Clear(); - value.Memory.Span.CopyTo(word.Slice(0, value.Memory.Length)); + value.Memory.Span.CopyTo(word[..value.Memory.Length]); } else { diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/Blake2FPrecompile.cs b/src/Nethermind/Nethermind.Evm/Precompiles/Blake2FPrecompile.cs index 6808abb0987..985eeafd6b3 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/Blake2FPrecompile.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/Blake2FPrecompile.cs @@ -34,7 +34,7 @@ public long DataGasCost(in ReadOnlyMemory inputData, IReleaseSpec releaseS return 0; } - uint rounds = inputData.Slice(0, 4).Span.ReadEthUInt32(); + uint rounds = inputData[..4].Span.ReadEthUInt32(); return rounds; } diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs b/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs index 77cc6f96b14..ad7be99ba4e 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/EcRecoverPrecompile.cs @@ -40,17 +40,17 @@ public long BaseGasCost(IReleaseSpec releaseSpec) Metrics.EcRecoverPrecompile++; Span inputDataSpan = stackalloc byte[128]; - inputData.Span.Slice(0, Math.Min(128, inputData.Length)) - .CopyTo(inputDataSpan.Slice(0, Math.Min(128, inputData.Length))); + inputData.Span[..Math.Min(128, inputData.Length)] + .CopyTo(inputDataSpan[..Math.Min(128, inputData.Length)]); - Keccak hash = new(inputDataSpan.Slice(0, 32).ToArray()); + Keccak hash = new(inputDataSpan[..32].ToArray()); Span vBytes = inputDataSpan.Slice(32, 32); Span r = inputDataSpan.Slice(64, 32); Span s = inputDataSpan.Slice(96, 32); // TEST: CALLCODEEcrecoverV_prefixedf0_d0g0v0 // TEST: CALLCODEEcrecoverV_prefixedf0_d1g0v0 - if (!Bytes.AreEqual(_zero31, vBytes.Slice(0, 31))) + if (!Bytes.AreEqual(_zero31, vBytes[..31])) { return (Array.Empty(), true); } diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/Extensions.cs b/src/Nethermind/Nethermind.Evm/Precompiles/Extensions.cs index a8ef7f7b7bf..43ba06acdea 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/Extensions.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/Extensions.cs @@ -9,8 +9,8 @@ public static class Extensions { public static void PrepareEthInput(this ReadOnlyMemory inputData, Span inputDataSpan) { - inputData.Span.Slice(0, Math.Min(inputDataSpan.Length, inputData.Length)) - .CopyTo(inputDataSpan.Slice(0, Math.Min(inputDataSpan.Length, inputData.Length))); + inputData.Span[..Math.Min(inputDataSpan.Length, inputData.Length)] + .CopyTo(inputDataSpan[..Math.Min(inputDataSpan.Length, inputData.Length)]); } } } diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompile.cs b/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompile.cs index edf393dab60..b6372c15e57 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompile.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompile.cs @@ -52,10 +52,10 @@ public long DataGasCost(in ReadOnlyMemory inputData, IReleaseSpec releaseS try { Span extendedInput = stackalloc byte[96]; - inputData.Slice(0, Math.Min(96, inputData.Length)).Span - .CopyTo(extendedInput.Slice(0, Math.Min(96, inputData.Length))); + inputData[..Math.Min(96, inputData.Length)].Span + .CopyTo(extendedInput[..Math.Min(96, inputData.Length)]); - UInt256 baseLength = new(extendedInput.Slice(0, 32), true); + UInt256 baseLength = new(extendedInput[..32], true); UInt256 expLength = new(extendedInput.Slice(32, 32), true); UInt256 modulusLength = new(extendedInput.Slice(64, 32), true); @@ -91,10 +91,10 @@ private static mpz_t ImportDataToGmp(byte[] data) private static (int, int, int) GetInputLengths(in ReadOnlyMemory inputData) { Span extendedInput = stackalloc byte[96]; - inputData.Slice(0, Math.Min(96, inputData.Length)).Span - .CopyTo(extendedInput.Slice(0, Math.Min(96, inputData.Length))); + inputData[..Math.Min(96, inputData.Length)].Span + .CopyTo(extendedInput[..Math.Min(96, inputData.Length)]); - int baseLength = (int)new UInt256(extendedInput.Slice(0, 32), true); + int baseLength = (int)new UInt256(extendedInput[..32], true); UInt256 expLengthUint256 = new(extendedInput.Slice(32, 32), true); int expLength = expLengthUint256 > Array.MaxLength ? Array.MaxLength : (int)expLengthUint256; int modulusLength = (int)new UInt256(extendedInput.Slice(64, 32), true); diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompilePreEip2565.cs b/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompilePreEip2565.cs index 3eae0cf95e9..1f5c23d3e36 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompilePreEip2565.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/ModExpPrecompilePreEip2565.cs @@ -34,10 +34,10 @@ public long DataGasCost(in ReadOnlyMemory inputData, IReleaseSpec releaseS try { Span extendedInput = stackalloc byte[96]; - inputData.Slice(0, Math.Min(96, inputData.Length)).Span - .CopyTo(extendedInput.Slice(0, Math.Min(96, inputData.Length))); + inputData[..Math.Min(96, inputData.Length)].Span + .CopyTo(extendedInput[..Math.Min(96, inputData.Length)]); - UInt256 baseLength = new(extendedInput.Slice(0, 32), true); + UInt256 baseLength = new(extendedInput[..32], true); UInt256 expLength = new(extendedInput.Slice(32, 32), true); UInt256 modulusLength = new(extendedInput.Slice(64, 32), true); diff --git a/src/Nethermind/Nethermind.Evm/Precompiles/Snarks/Shamatar/Bn256PairingPrecompile.cs b/src/Nethermind/Nethermind.Evm/Precompiles/Snarks/Shamatar/Bn256PairingPrecompile.cs index 623576b0efc..68431893648 100644 --- a/src/Nethermind/Nethermind.Evm/Precompiles/Snarks/Shamatar/Bn256PairingPrecompile.cs +++ b/src/Nethermind/Nethermind.Evm/Precompiles/Snarks/Shamatar/Bn256PairingPrecompile.cs @@ -48,7 +48,7 @@ safe in benchmarks so we need to remember to clone */ Span inputReshuffled = stackalloc byte[PairSize]; for (int i = 0; i < inputData.Length / PairSize; i++) { - inputDataSpan.Slice(i * PairSize + 0, 64).CopyTo(inputReshuffled.Slice(0, 64)); + inputDataSpan.Slice(i * PairSize + 0, 64).CopyTo(inputReshuffled[..64]); inputDataSpan.Slice(i * PairSize + 64, 32).CopyTo(inputReshuffled.Slice(96, 32)); inputDataSpan.Slice(i * PairSize + 96, 32).CopyTo(inputReshuffled.Slice(64, 32)); inputDataSpan.Slice(i * PairSize + 128, 32).CopyTo(inputReshuffled.Slice(160, 32)); @@ -60,7 +60,7 @@ safe in benchmarks so we need to remember to clone */ if (success) { - result = (output.Slice(0, 32).ToArray(), true); + result = (output[..32].ToArray(), true); } else { diff --git a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs index 9c2d9eb5a8b..b5300031b50 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/ParityStyle/ParityLikeTxTracer.cs @@ -288,7 +288,7 @@ public void ReportOperationRemainingGas(long gas) { _gasAlreadySetForCurrentOp = true; - _currentOperation.Cost = _currentOperation.Cost - (_treatGasParityStyle ? 0 : gas); + _currentOperation.Cost -= (_treatGasParityStyle ? 0 : gas); // based on Parity behaviour - adding stipend to the gas cost if (_currentOperation.Cost == 7400) @@ -389,7 +389,7 @@ public void ReportAccountRead(Address address) public void ReportStorageChange(in StorageCell storageCell, byte[] before, byte[] after) { - Dictionary> storage = null; + Dictionary> storage; if (!_trace.StateChanges.ContainsKey(storageCell.Address)) { _trace.StateChanges[storageCell.Address] = new ParityAccountStateChange(); diff --git a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs index 33170a4338a..e0a3dc897a1 100644 --- a/src/Nethermind/Nethermind.Evm/VirtualMachine.cs +++ b/src/Nethermind/Nethermind.Evm/VirtualMachine.cs @@ -867,11 +867,11 @@ static void UpdateCurrentState(EvmState state, int pc, long gas, int stackHead) if (sign >= 0) { - BytesZero32.AsSpan(0, position).CopyTo(b.Slice(0, position)); + BytesZero32.AsSpan(0, position).CopyTo(b[..position]); } else { - BytesMax32.AsSpan(0, position).CopyTo(b.Slice(0, position)); + BytesMax32.AsSpan(0, position).CopyTo(b[..position]); } stack.PushBytes(b); diff --git a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs index af48907c000..7bc9ddb5399 100644 --- a/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs +++ b/src/Nethermind/Nethermind.Facade/BlockchainBridge.cs @@ -234,10 +234,7 @@ private void CallAndRestore( bool treatBlockHeaderAsParentBlock, ITxTracer tracer) { - if (transaction.SenderAddress is null) - { - transaction.SenderAddress = Address.SystemUser; - } + transaction.SenderAddress ??= Address.SystemUser; Keccak stateRoot = blockHeader.StateRoot!; using IReadOnlyTransactionProcessor transactionProcessor = _processingEnv.Build(stateRoot); diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs index ea1a1578bb5..4a7c32480d4 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterStore.cs @@ -200,8 +200,7 @@ private static FilterTopic GetTopic(object obj) }; } - var topics = obj as IEnumerable; - if (topics is null) + if (obj is not IEnumerable topics) { return null; } diff --git a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs index 3551671e88a..5412afdcf80 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/LogFinder.cs @@ -236,10 +236,7 @@ private static IEnumerable FilterLogsInBlockLowMemoryAllocation(LogFi logList ??= new List(); Keccak[] topics = log.Topics; - if (topics is null) - { - topics = iterator.DecodeTopics(new Rlp.ValueDecoderContext(log.TopicsRlp)); - } + topics ??= iterator.DecodeTopics(new Rlp.ValueDecoderContext(log.TopicsRlp)); logList.Add(new FilterLog( logIndexInBlock, diff --git a/src/Nethermind/Nethermind.Facade/Proxy/JsonRpcClientProxy.cs b/src/Nethermind/Nethermind.Facade/Proxy/JsonRpcClientProxy.cs index e933748823a..19cec2b1bcb 100644 --- a/src/Nethermind/Nethermind.Facade/Proxy/JsonRpcClientProxy.cs +++ b/src/Nethermind/Nethermind.Facade/Proxy/JsonRpcClientProxy.cs @@ -43,7 +43,7 @@ public Task> SendAsync(string method, long id, params object[] @ jsonrpc = 2.0, id, method, - @params = (@params ?? Array.Empty()).Where(x => !(x is null)) + @params = (@params ?? Array.Empty()).Where(x => x is not null) }); } diff --git a/src/Nethermind/Nethermind.Init/Cpu/Frequency.cs b/src/Nethermind/Nethermind.Init/Cpu/Frequency.cs index 26a4a391ece..2a860a948f4 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/Frequency.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/Frequency.cs @@ -124,8 +124,7 @@ public static implicit operator double(Frequency property) public static bool TryParse(string s, FrequencyUnit unit, out Frequency freq) { - double result; - bool result2 = double.TryParse(s, NumberStyles.Any, DefaultCultureInfo.Instance, out result); + bool result2 = double.TryParse(s, NumberStyles.Any, DefaultCultureInfo.Instance, out double result); freq = new Frequency(result, unit); return result2; } diff --git a/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoParser.cs b/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoParser.cs index 27b4d842e21..8db1a4c52f4 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoParser.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoParser.cs @@ -10,7 +10,7 @@ namespace Nethermind.Init.Cpu; -internal static class ProcCpuInfoParser +internal static partial class ProcCpuInfoParser { internal static CpuInfo ParseOutput(string? content) { @@ -53,18 +53,18 @@ internal static CpuInfo ParseOutput(string? content) return new CpuInfo( processorModelNames.Count > 0 ? string.Join(", ", processorModelNames) : "", - processorsToPhysicalCoreCount.Count > 0 ? processorsToPhysicalCoreCount.Count : (int?)null, - processorsToPhysicalCoreCount.Count > 0 ? processorsToPhysicalCoreCount.Values.Sum() : (int?)null, - logicalCoreCount > 0 ? logicalCoreCount : (int?)null, - nominalFrequency > 0 ? nominalFrequency : (Frequency?)null, - minFrequency > 0 ? minFrequency : (Frequency?)null, - maxFrequency > 0 ? maxFrequency : (Frequency?)null); + processorsToPhysicalCoreCount.Count > 0 ? processorsToPhysicalCoreCount.Count : null, + processorsToPhysicalCoreCount.Count > 0 ? processorsToPhysicalCoreCount.Values.Sum() : null, + logicalCoreCount > 0 ? logicalCoreCount : null, + nominalFrequency > 0 ? nominalFrequency : null, + minFrequency > 0 ? minFrequency : null, + maxFrequency > 0 ? maxFrequency : null); } internal static Frequency ParseFrequencyFromBrandString(string brandString) { const string pattern = "(\\d.\\d+)GHz"; - var matches = Regex.Matches(brandString, pattern, RegexOptions.IgnoreCase); + var matches = MatchRegex().Matches(brandString); if (matches.Count > 0 && matches[0].Groups.Count > 1) { string match = Regex.Matches(brandString, pattern, RegexOptions.IgnoreCase)[0].Groups[1].ToString(); @@ -73,4 +73,7 @@ internal static Frequency ParseFrequencyFromBrandString(string brandString) return 0d; } + + [GeneratedRegex("(\\d.\\d+)GHz", RegexOptions.IgnoreCase, "en-US")] + private static partial Regex MatchRegex(); } diff --git a/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoProvider.cs b/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoProvider.cs index 852c395a309..fd62747fdf4 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoProvider.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/ProcCpuInfoProvider.cs @@ -23,7 +23,7 @@ internal static class ProcCpuInfoProvider { string? content = ProcessHelper.RunAndReadOutput("cat", "/proc/cpuinfo"); string output = GetCpuSpeed(); - content = content + output; + content += output; return ProcCpuInfoParser.ParseOutput(content); } return null; diff --git a/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs b/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs index cc9bff11f71..6d305b5c8e0 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/SectionsHelper.cs @@ -11,7 +11,7 @@ namespace Nethermind.Init.Cpu; -internal static class SectionsHelper +internal static partial class SectionsHelper { public static Dictionary ParseSection(string? content, char separator) { @@ -33,9 +33,12 @@ public static List> ParseSections(string? content, ch // wmic doubles the carriage return character due to a bug. // Therefore, the * quantifier should be used to workaround it. return - Regex.Split(content ?? "", "(\r*\n){2,}") + ParseRegex().Split(content ?? "") .Select(s => ParseSection(s, separator)) .Where(s => s.Count > 0) .ToList(); } + + [GeneratedRegex("(\r*\n){2,}")] + private static partial Regex ParseRegex(); } diff --git a/src/Nethermind/Nethermind.Init/Cpu/TimeInterval.cs b/src/Nethermind/Nethermind.Init/Cpu/TimeInterval.cs index 68f3fbdd339..da44e32dc7c 100644 --- a/src/Nethermind/Nethermind.Init/Cpu/TimeInterval.cs +++ b/src/Nethermind/Nethermind.Init/Cpu/TimeInterval.cs @@ -173,10 +173,10 @@ public string ToString(CultureInfo cultureInfo, string format = "N4", UnitPresen public string ToString(TimeUnit? timeUnit, CultureInfo cultureInfo, string format = "N4", UnitPresentation? unitPresentation = null) { - timeUnit = timeUnit ?? TimeUnit.GetBestTimeUnit(Nanoseconds); - cultureInfo = cultureInfo ?? DefaultCultureInfo.Instance; - format = format ?? "N4"; - unitPresentation = unitPresentation ?? UnitPresentation.Default; + timeUnit ??= TimeUnit.GetBestTimeUnit(Nanoseconds); + cultureInfo ??= DefaultCultureInfo.Instance; + format ??= "N4"; + unitPresentation ??= UnitPresentation.Default; double num = TimeUnit.Convert(Nanoseconds, TimeUnit.Nanosecond, timeUnit); if (unitPresentation.IsVisible) { diff --git a/src/Nethermind/Nethermind.Init/MemoryHintMan.cs b/src/Nethermind/Nethermind.Init/MemoryHintMan.cs index c19171abc43..002ca4d8878 100644 --- a/src/Nethermind/Nethermind.Init/MemoryHintMan.cs +++ b/src/Nethermind/Nethermind.Init/MemoryHintMan.cs @@ -189,7 +189,6 @@ private void UpdateDbConfig(uint cpuCount, ISyncConfig syncConfig, IDbConfig dbC dbNeeds = GetStateNeeds(cpuCount, syncConfig); dbGets = GiveItWhatYouCan(dbNeeds, DbMemory, remaining); - remaining -= dbGets.CacheMem + dbGets.Buffers * dbGets.SingleBufferMem; dbConfig.WriteBufferNumber = dbGets.Buffers; dbConfig.WriteBufferSize = (ulong)dbGets.SingleBufferMem; dbConfig.BlockCacheSize = (ulong)dbGets.CacheMem; diff --git a/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs b/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs index ab75b8e1bd4..309025ffb54 100644 --- a/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs +++ b/src/Nethermind/Nethermind.Init/Steps/FilterBootnodes.cs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -31,7 +32,7 @@ public Task Execute(CancellationToken _) return Task.CompletedTask; } - _api.ChainSpec.Bootnodes = _api.ChainSpec.Bootnodes?.Where(n => !n.NodeId?.Equals(_api.NodeKey.PublicKey) ?? false).ToArray() ?? new NetworkNode[0]; + _api.ChainSpec.Bootnodes = _api.ChainSpec.Bootnodes?.Where(n => !n.NodeId?.Equals(_api.NodeKey.PublicKey) ?? false).ToArray() ?? Array.Empty(); return Task.CompletedTask; } } diff --git a/src/Nethermind/Nethermind.JsonRpc/Client/BasicJsonRpcClient.cs b/src/Nethermind/Nethermind.JsonRpc/Client/BasicJsonRpcClient.cs index f1390307881..9570d9a4e2d 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Client/BasicJsonRpcClient.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Client/BasicJsonRpcClient.cs @@ -92,7 +92,7 @@ private string GetJsonRequest(string method, IEnumerable parameters) private void AddAuthorizationHeader() { var url = _client.BaseAddress.ToString(); - if (!url.Contains("@")) + if (!url.Contains('@')) { return; } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/NodeInfo.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/NodeInfo.cs index 443199775cd..766fdc064b3 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/NodeInfo.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Admin/NodeInfo.cs @@ -32,8 +32,10 @@ public class NodeInfo { public NodeInfo() { - Protocols = new Dictionary(); - Protocols.Add("eth", new EthProtocolInfo()); + Protocols = new Dictionary + { + { "eth", new EthProtocolInfo() } + }; Ports = new PortsInfo(); } diff --git a/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/PeerInfo.cs b/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/PeerInfo.cs index a0f76e7858b..9095c0ca77a 100644 --- a/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/PeerInfo.cs +++ b/src/Nethermind/Nethermind.JsonRpc/Modules/Parity/PeerInfo.cs @@ -71,8 +71,10 @@ public PeerInfo(Peer peer) Network = peerNetworkInfo; - Protocols = new Dictionary(); - Protocols.Add("eth", ethProtocolInfo); + Protocols = new Dictionary + { + { "eth", ethProtocolInfo } + }; } } } diff --git a/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs b/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs index 9d761ce5441..69127ba3883 100644 --- a/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs +++ b/src/Nethermind/Nethermind.KeyStore/FileKeyStore.cs @@ -140,7 +140,7 @@ public FileKeyStore( break; case "pbkdf2": int c = kdfParams.C.Value; - var deriveBytes = new Rfc2898DeriveBytes(passBytes, salt, kdfParams.C.Value, HashAlgorithmName.SHA256); + var deriveBytes = new Rfc2898DeriveBytes(passBytes, salt, c, HashAlgorithmName.SHA256); derivedKey = deriveBytes.GetBytes(256); break; default: diff --git a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs index 76460a16948..888865df81b 100644 --- a/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs +++ b/src/Nethermind/Nethermind.Logging.NLog/StackTraceUtils.cs @@ -30,14 +30,14 @@ private static string GetStackFrameMethodClassName(MethodBase method, bool inclu } Type declaringType = method.DeclaringType; - if (cleanAsyncMoveNext && method.Name == "MoveNext" && ((object)declaringType is not null ? declaringType.DeclaringType : null) 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) { int length = str.IndexOf("+<>", StringComparison.Ordinal); if (length >= 0) - str = str.Substring(0, length); + str = str[..length]; } return str; @@ -91,11 +91,11 @@ private static Assembly LookupAssemblyFromStackFrame(StackFrame stackFrame) if (method is null) return null; Type declaringType = method.DeclaringType; - Assembly assembly1 = (object)declaringType is not null ? declaringType.Assembly : null; + Assembly assembly1 = declaringType?.Assembly; if ((object)assembly1 is null) { Module module = method.Module; - assembly1 = (object)module is not null ? module.Assembly : null; + assembly1 = module?.Assembly; } Assembly assembly2 = assembly1; diff --git a/src/Nethermind/Nethermind.Logging/ConsoleAsyncLogger.cs b/src/Nethermind/Nethermind.Logging/ConsoleAsyncLogger.cs index fcfe13e28c7..4323c6829ee 100644 --- a/src/Nethermind/Nethermind.Logging/ConsoleAsyncLogger.cs +++ b/src/Nethermind/Nethermind.Logging/ConsoleAsyncLogger.cs @@ -54,7 +54,7 @@ public ConsoleAsyncLogger(LogLevel logLevel, string prefix = null) private void Log(string text) { - _queuedEntries.Add($"{DateTime.Now:HH:mm:ss.fff} [{Thread.CurrentThread.ManagedThreadId}] {_prefix}{text}"); + _queuedEntries.Add($"{DateTime.Now:HH:mm:ss.fff} [{Environment.CurrentManagedThreadId}] {_prefix}{text}"); } public void Info(string text) diff --git a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs index 20de02b731f..159af0d2942 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/MergePlugin.cs @@ -174,7 +174,7 @@ private void EnsureJsonRpcUrl() if (!jsonRpcConfig.EnabledModules.Contains("engine")) { // Disable it - jsonRpcConfig.EnabledModules = new string[] { }; + jsonRpcConfig.EnabledModules = Array.Empty(); } jsonRpcConfig.AdditionalRpcUrls = jsonRpcConfig.AdditionalRpcUrls diff --git a/src/Nethermind/Nethermind.Merkleization/MemMerkleTreeStore.cs b/src/Nethermind/Nethermind.Merkleization/MemMerkleTreeStore.cs index dcc068ba6c3..416bb5ffb97 100644 --- a/src/Nethermind/Nethermind.Merkleization/MemMerkleTreeStore.cs +++ b/src/Nethermind/Nethermind.Merkleization/MemMerkleTreeStore.cs @@ -12,7 +12,7 @@ public class MemMerkleTreeStore : IKeyValueStore public byte[]? this[ulong key] { - get => _dictionary.ContainsKey(key) ? _dictionary[key] : null; + get => _dictionary.TryGetValue(key, out byte[]? value) ? value : null; set => _dictionary[key] = value; } } diff --git a/src/Nethermind/Nethermind.Merkleization/Merkle.cs b/src/Nethermind/Nethermind.Merkleization/Merkle.cs index e8cacd5ff81..c0494f3eeb1 100644 --- a/src/Nethermind/Nethermind.Merkleization/Merkle.cs +++ b/src/Nethermind/Nethermind.Merkleization/Merkle.cs @@ -22,7 +22,7 @@ private static void BuildZeroHashes() for (int i = 1; i < 64; i++) { var previous = ZeroHashes[i - 1]; - MemoryMarshal.CreateSpan(ref previous, 1).CopyTo(concatenation.Slice(0, 1)); + MemoryMarshal.CreateSpan(ref previous, 1).CopyTo(concatenation[..1]); MemoryMarshal.CreateSpan(ref previous, 1).CopyTo(concatenation.Slice(1, 1)); ZeroHashes[i] = new UInt256(SHA256.HashData(MemoryMarshal.Cast(concatenation))); } @@ -163,9 +163,9 @@ public static void Ize(out UInt256 root, Span value) int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc bool[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk)); } else @@ -180,9 +180,9 @@ public static void Ize(out UInt256 root, Span value) int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc byte[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk)); } else @@ -197,9 +197,9 @@ public static void Ize(out UInt256 root, ReadOnlySpan value, ulong chunkCo int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - ReadOnlySpan fullChunks = value.Slice(0, value.Length - partialChunkLength); + ReadOnlySpan fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc byte[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk), chunkCount); } else @@ -215,16 +215,16 @@ public static void IzeBits(out UInt256 root, Span value, uint limit) int length = value.Length * 8 - (8 - lastBitPosition); if (value[^1] == 0) { - value = value.Slice(0, value.Length - 1); + value = value[..^1]; } const int typeSize = 1; int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc byte[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk), limit); } else @@ -294,9 +294,9 @@ public static void Ize(out UInt256 root, Span value) int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc ushort[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk)); } else @@ -311,9 +311,9 @@ public static void Ize(out UInt256 root, Span value) int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc uint[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk)); } else @@ -329,9 +329,9 @@ public static void Ize(out UInt256 root, Span value, ulong maxLength = 0U int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc ulong[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk), limit); } else @@ -346,9 +346,9 @@ public static void Ize(out UInt256 root, Span value) int partialChunkLength = value.Length % (32 / typeSize); if (partialChunkLength > 0) { - Span fullChunks = value.Slice(0, value.Length - partialChunkLength); + Span fullChunks = value[..^partialChunkLength]; Span lastChunk = stackalloc UInt128[32 / typeSize]; - value.Slice(value.Length - partialChunkLength).CopyTo(lastChunk); + value[^partialChunkLength..].CopyTo(lastChunk); Ize(out root, MemoryMarshal.Cast(fullChunks), MemoryMarshal.Cast(lastChunk)); } else diff --git a/src/Nethermind/Nethermind.Merkleization/ShaMerkleTree.cs b/src/Nethermind/Nethermind.Merkleization/ShaMerkleTree.cs index 3520df95edc..cf0b3bd1231 100644 --- a/src/Nethermind/Nethermind.Merkleization/ShaMerkleTree.cs +++ b/src/Nethermind/Nethermind.Merkleization/ShaMerkleTree.cs @@ -39,7 +39,7 @@ private static void HashStatic(ReadOnlySpan a, ReadOnlySpan b, Span< { Span combined = stackalloc byte[a.Length + b.Length]; a.CopyTo(combined); - b.CopyTo(combined.Slice(a.Length)); + b.CopyTo(combined[a.Length..]); _hashAlgorithm.TryComputeHash(combined, target, out int bytesWritten); } diff --git a/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs b/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs index 1ee0e4fc586..e30d40e1ff0 100644 --- a/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs +++ b/src/Nethermind/Nethermind.Monitoring/MonitoringService.cs @@ -106,7 +106,7 @@ private string GetGroup() { string group = GetValueFromVariableOrDefault("GROUP", "nethermind"); string endpoint = _pushGatewayUrl.Split("/").LastOrDefault(); - if (!string.IsNullOrWhiteSpace(endpoint) && endpoint.Contains("-")) + if (!string.IsNullOrWhiteSpace(endpoint) && endpoint.Contains('-')) { group = endpoint.Split("-")[0] ?? group; } diff --git a/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs b/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs index bc96cd47d5e..d75395ed122 100644 --- a/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs +++ b/src/Nethermind/Nethermind.Network.Discovery/Serializers/DiscoveryMsgSerializerBase.cs @@ -100,8 +100,8 @@ protected void AddSignatureAndMdc(IByteBuffer byteBuffer, int dataLength) } IByteBuffer data = msg.Slice(98, msg.ReadableBytes - 98); Memory msgBytes = msg.ReadAllBytesAsMemory(); - Memory mdc = msgBytes.Slice(0, 32); - Span sigAndData = msgBytes.Span.Slice(32); + Memory mdc = msgBytes[..32]; + Span sigAndData = msgBytes.Span[32..]; Span computedMdc = ValueKeccak.Compute(sigAndData).BytesAsSpan; if (!Bytes.AreEqual(mdc.Span, computedMdc)) @@ -109,7 +109,7 @@ protected void AddSignatureAndMdc(IByteBuffer byteBuffer, int dataLength) throw new NetworkingException("Invalid MDC", NetworkExceptionType.Validation); } - PublicKey nodeId = _nodeIdResolver.GetNodeId(sigAndData.Slice(0, 64), sigAndData[64], sigAndData.Slice(65, sigAndData.Length - 65)); + PublicKey nodeId = _nodeIdResolver.GetNodeId(sigAndData[..64], sigAndData[64], sigAndData[65..]); return (nodeId, mdc, data); } diff --git a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs index 62d9eb27527..4dd2fe6fac2 100644 --- a/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs +++ b/src/Nethermind/Nethermind.Network/P2P/ProtocolHandlers/SyncPeerProtocolHandlerBase.cs @@ -279,10 +279,7 @@ protected BlockHeadersMessage FulfillBlockHeadersRequest(GetBlockHeadersMessage } Keccak startingHash = msg.StartBlockHash; - if (startingHash is null) - { - startingHash = SyncServer.FindHash(msg.StartBlockNumber); - } + startingHash ??= SyncServer.FindHash(msg.StartBlockNumber); BlockHeader[] headers = startingHash is null diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs index 6353d93465a..66b78ddf3ad 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V62/Messages/BlockBodiesMessage.cs @@ -20,7 +20,7 @@ public BlockBodiesMessage(Block[] blocks) Bodies = new BlockBody[blocks.Length]; for (int i = 0; i < blocks.Length; i++) { - Bodies[i] = blocks[i] is null ? null : blocks[i].Body; + Bodies[i] = blocks[i]?.Body; } } diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessage.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessage.cs index 0ba1972267d..a3e75dd67c6 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessage.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessage.cs @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2022 Demerzel Solutions Limited // SPDX-License-Identifier: LGPL-3.0-only +using System; using Nethermind.Core; using Nethermind.Network.P2P.Messages; @@ -17,7 +18,7 @@ public class ReceiptsMessage : P2PMessage public ReceiptsMessage(TxReceipt[][] txReceipts) { - TxReceipts = txReceipts ?? new TxReceipt[0][]; + TxReceipts = txReceipts ?? Array.Empty(); } public override string ToString() => $"{nameof(ReceiptsMessage)}({TxReceipts?.Length ?? 0})"; diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs index 6a1fcd0bea6..4c3453116a3 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Eth/V63/Messages/ReceiptsMessageSerializer.cs @@ -76,7 +76,7 @@ public ReceiptsMessage Deserialize(IByteBuffer byteBuffer) public ReceiptsMessage Deserialize(RlpStream rlpStream) { TxReceipt[][] data = rlpStream.DecodeArray(itemContext => - itemContext.DecodeArray(nestedContext => _decoder.Decode(nestedContext)) ?? new TxReceipt[0], true); + itemContext.DecodeArray(nestedContext => _decoder.Decode(nestedContext)) ?? Array.Empty(), true); ReceiptsMessage message = new(data); return message; diff --git a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/BlockBodiesMessageSerializer.cs b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/BlockBodiesMessageSerializer.cs index 0a236abf1a1..37d66043b05 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/BlockBodiesMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Subprotocols/Les/Messages/BlockBodiesMessageSerializer.cs @@ -11,7 +11,7 @@ public class BlockBodiesMessageSerializer : IZeroMessageSerializer sigAllBytes = rlpStream.DecodeByteArraySpan(); - Signature signature = new(sigAllBytes.Slice(0, 64), sigAllBytes[64]); // since Signature class is Ethereum style it expects V as the 65th byte, hence we use RecoveryID constructor + Signature signature = new(sigAllBytes[..64], sigAllBytes[64]); // since Signature class is Ethereum style it expects V as the 65th byte, hence we use RecoveryID constructor authMessage.Signature = signature; authMessage.PublicKey = new PublicKey(rlpStream.DecodeByteArraySpan()); authMessage.Nonce = rlpStream.DecodeByteArray(); - int version = rlpStream.DecodeInt(); + _ = rlpStream.DecodeInt(); return authMessage; } } diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthMessageSerializer.cs b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthMessageSerializer.cs index beb4ae1666e..eeebf2fe774 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthMessageSerializer.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/AuthMessageSerializer.cs @@ -55,7 +55,7 @@ public AuthMessage Deserialize(IByteBuffer msgBytes) AuthMessage authMessage = new AuthMessage(); Span msg = msgBytes.ReadAllBytesAsSpan(); - authMessage.Signature = new Signature(msg.Slice(SigOffset, SigLength - 1), msg[64]); + authMessage.Signature = new Signature(msg[..(SigLength - 1)], msg[64]); authMessage.EphemeralPublicHash = new Keccak(msg.Slice(EphemeralHashOffset, EphemeralHashLength).ToArray()); authMessage.PublicKey = new PublicKey(msg.Slice(PublicKeyOffset, PublicKeyLength)); authMessage.Nonce = msg.Slice(NonceOffset, NonceLength).ToArray(); diff --git a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/HandshakeService.cs b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/HandshakeService.cs index 9ab773ed59d..b59e6f2881c 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/Handshake/HandshakeService.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/Handshake/HandshakeService.cs @@ -251,7 +251,7 @@ public static void SetSecrets(EncryptionHandshake handshake, HandshakeRole hands Span tempConcat = stackalloc byte[64]; Span ephemeralSharedSecret = Proxy.EcdhSerialized(handshake.RemoteEphemeralPublicKey.Bytes, handshake.EphemeralPrivateKey.KeyBytes); Span nonceHash = ValueKeccak.Compute(Bytes.Concat(handshake.RecipientNonce, handshake.InitiatorNonce)).BytesAsSpan; - ephemeralSharedSecret.CopyTo(tempConcat.Slice(0, 32)); + ephemeralSharedSecret.CopyTo(tempConcat[..32]); nonceHash.CopyTo(tempConcat.Slice(32, 32)); Span sharedSecret = ValueKeccak.Compute(tempConcat).BytesAsSpan; // byte[] token = Keccak.Compute(sharedSecret).Bytes; diff --git a/src/Nethermind/Nethermind.Network/Rlpx/ZeroFrameEncoder.cs b/src/Nethermind/Nethermind.Network/Rlpx/ZeroFrameEncoder.cs index 8041c8cac2b..2dccd6af28d 100644 --- a/src/Nethermind/Nethermind.Network/Rlpx/ZeroFrameEncoder.cs +++ b/src/Nethermind/Nethermind.Network/Rlpx/ZeroFrameEncoder.cs @@ -42,7 +42,7 @@ protected override void Encode(IChannelHandlerContext context, IByteBuffer input // 1 if the buffer does not have enough bytes, and its capacity is unchanged. // 2 if the buffer has enough writable bytes, and its capacity has been increased. // 3 if the buffer does not have enough bytes, but its capacity has been increased to its maximum. - int code = output.EnsureWritable(Frame.HeaderSize + Frame.MacSize + frame.PayloadSize + Frame.MacSize, true); + _ = output.EnsureWritable(Frame.HeaderSize + Frame.MacSize + frame.PayloadSize + Frame.MacSize, true); WriteHeader(output); WriteHeaderMac(output); diff --git a/src/Nethermind/Nethermind.Runner/Logging/NLogConfigurator.cs b/src/Nethermind/Nethermind.Runner/Logging/NLogConfigurator.cs index 2ee394a482e..4c82688d5f6 100644 --- a/src/Nethermind/Nethermind.Runner/Logging/NLogConfigurator.cs +++ b/src/Nethermind/Nethermind.Runner/Logging/NLogConfigurator.cs @@ -50,10 +50,7 @@ public static void ConfigureSeqBufferTarget( public static void ClearSeqTarget() { LoggingConfiguration loggingConfiguration = LogManager.Configuration; - if (loggingConfiguration is not null) - { - loggingConfiguration.RemoveTarget("seq"); - } + loggingConfiguration?.RemoveTarget("seq"); } public static void ConfigureLogLevels(CommandOption logLevelOverride) diff --git a/src/Nethermind/Nethermind.Secp256k1/Proxy.cs b/src/Nethermind/Nethermind.Secp256k1/Proxy.cs index f258aef212b..a78e315a62a 100644 --- a/src/Nethermind/Nethermind.Secp256k1/Proxy.cs +++ b/src/Nethermind/Nethermind.Secp256k1/Proxy.cs @@ -357,7 +357,7 @@ private static void ToPublicKeyArray(Span serializedKey, byte[] unmanaged) // Add our uncompressed prefix to our key. Span uncompressedPrefixedPublicKey = stackalloc byte[65]; uncompressedPrefixedPublicKey[0] = 4; - unmanaged.AsSpan().CopyTo(uncompressedPrefixedPublicKey.Slice(1)); + unmanaged.AsSpan().CopyTo(uncompressedPrefixedPublicKey[1..]); // Parse our public key from the serialized data. if (!PublicKeyParse(publicKey, uncompressedPrefixedPublicKey)) diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs index f33cb338fec..4b8fd60c395 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/AccountDecoder.cs @@ -85,10 +85,7 @@ public Rlp Encode(Account? item, RlpBehaviors rlpBehaviors = RlpBehaviors.None) public void Encode(Account account, RlpStream rlpStream, int? contentLength = null) { - if (contentLength is null) - { - contentLength = GetContentLength(account); - } + contentLength ??= GetContentLength(account); rlpStream.StartSequence(contentLength.Value); rlpStream.Encode(account.Nonce); @@ -173,7 +170,7 @@ public int GetContentLength(Account? item) private Keccak DecodeStorageRoot(RlpStream rlpStream) { - Keccak storageRoot = null; + Keccak storageRoot; if (_slimFormat && rlpStream.IsNextItemEmptyArray()) { rlpStream.ReadByte(); @@ -189,7 +186,7 @@ private Keccak DecodeStorageRoot(RlpStream rlpStream) private Keccak DecodeCodeHash(RlpStream rlpStream) { - Keccak codeHash = null; + Keccak codeHash; if (_slimFormat && rlpStream.IsNextItemEmptyArray()) { rlpStream.ReadByte(); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs index 06794053ffe..eac6044e886 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/CompactReceiptStorageDecoder.cs @@ -208,7 +208,6 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio private (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) { int contentLength = 0; - int logsLength = 0; if (item is null) { return (contentLength, 0); @@ -227,7 +226,7 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio contentLength += Rlp.LengthOf(item.Sender); contentLength += Rlp.LengthOf(item.GasUsedTotal); - logsLength = GetLogsLength(item); + int logsLength = GetLogsLength(item); contentLength += Rlp.LengthOfSequence(logsLength); return (contentLength, logsLength); diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs index fac827bdb09..bf355ff7921 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptArrayStorageDecoder.cs @@ -114,7 +114,7 @@ public TxReceipt[] Decode(in Span receiptsData) if (receiptsData.Length > 0 && receiptsData[0] == CompactEncoding) { - var decoderContext = new Rlp.ValueDecoderContext(receiptsData.Slice(1)); + var decoderContext = new Rlp.ValueDecoderContext(receiptsData[1..]); return CompactReceiptStorageDecoder.DecodeArray(ref decoderContext, RlpBehaviors.Storage); } else diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs index a21b97f82dc..d9259a715fb 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/ReceiptStorageDecoder.cs @@ -258,7 +258,6 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio private (int Total, int Logs) GetContentLength(TxReceipt? item, RlpBehaviors rlpBehaviors) { int contentLength = 0; - int logsLength = 0; if (item is null) { return (contentLength, 0); @@ -281,7 +280,7 @@ public void Encode(RlpStream rlpStream, TxReceipt? item, RlpBehaviors rlpBehavio contentLength += Rlp.LengthOf(item.GasUsedTotal); contentLength += Rlp.LengthOf(item.Bloom); - logsLength = GetLogsLength(item); + int logsLength = GetLogsLength(item); contentLength += Rlp.LengthOfSequence(logsLength); bool isEip658Receipts = (rlpBehaviors & RlpBehaviors.Eip658Receipts) == RlpBehaviors.Eip658Receipts; diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs b/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs index 383a509d7ca..2f4fec645e0 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/Rlp.cs @@ -668,7 +668,7 @@ public int ReadSequenceLength() int prefix = ReadByte(); if (prefix < 192) { - throw new RlpException($"Expected a sequence prefix to be in the range of <192, 255> and got {prefix} at position {Position} in the message of length {Data.Length} starting with {Data.Slice(0, Math.Min(DebugMessageContentLength, Data.Length)).ToHexString()}"); + throw new RlpException($"Expected a sequence prefix to be in the range of <192, 255> and got {prefix} at position {Position} in the message of length {Data.Length} starting with {Data[..Math.Min(DebugMessageContentLength, Data.Length)].ToHexString()}"); } if (prefix <= 247) @@ -874,7 +874,7 @@ public void DecodeZeroPrefixedKeccakStructRef(out KeccakStructRef keccak, Span theSpan = DecodeByteArraySpan(); - theSpan.CopyTo(buffer.Slice(32 - theSpan.Length)); + theSpan.CopyTo(buffer[(32 - theSpan.Length)..]); keccak = new KeccakStructRef(buffer); } } @@ -889,7 +889,7 @@ public void DecodeZeroPrefixedKeccakStructRef(out KeccakStructRef keccak, Span 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | Data[Position + length - i]; + result |= Data[Position + length - i]; } } @@ -1141,7 +1141,7 @@ public bool DecodeBool() throw new RlpException($"Unexpected prefix of {prefix} when decoding a byte array at position {Position} in the message of length {Length} starting with {Description}"); } - private string Description => Data.Slice(0, Math.Min(DebugMessageContentLength, Length)).ToHexString(); + private string Description => Data[..Math.Min(DebugMessageContentLength, Length)].ToHexString(); public byte PeekByte() { @@ -1186,10 +1186,10 @@ public long DecodeLong() long result = 0; for (int i = 8; i > 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | PeekByte(length - i); + result |= PeekByte(length - i); } } @@ -1220,10 +1220,10 @@ public ulong DecodeULong() ulong result = 0ul; for (int i = 8; i > 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | PeekByte(length - i); + result |= PeekByte(length - i); } } diff --git a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs index 78c43cd42a2..f0c03445bc7 100644 --- a/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs +++ b/src/Nethermind/Nethermind.Serialization.Rlp/RlpStream.cs @@ -979,7 +979,7 @@ public bool DecodeBool() } public T[] DecodeArray(Func decodeItem, bool checkPositions = true, - T defaultElement = default(T)) + T defaultElement = default) { int positionCheck = ReadSequenceLength() + Position; int count = PeekNumberOfItemsRemaining(checkPositions ? positionCheck : (int?)null); @@ -1045,10 +1045,10 @@ public int DecodeInt() int result = 0; for (int i = 4; i > 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | PeekByte(length - i); + result |= PeekByte(length - i); } } @@ -1085,10 +1085,10 @@ public long DecodeLong() long result = 0; for (int i = 8; i > 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | PeekByte(length - i); + result |= PeekByte(length - i); } } @@ -1119,10 +1119,10 @@ public ulong DecodeULong() ulong result = 0; for (int i = 8; i > 0; i--) { - result = result << 8; + result <<= 8; if (i <= length) { - result = result | PeekByte(length - i); + result |= PeekByte(length - i); } } diff --git a/src/Nethermind/Nethermind.Serialization.Ssz.Test/HashUtility.cs b/src/Nethermind/Nethermind.Serialization.Ssz.Test/HashUtility.cs index 042c5b9981e..7f29fe72b80 100644 --- a/src/Nethermind/Nethermind.Serialization.Ssz.Test/HashUtility.cs +++ b/src/Nethermind/Nethermind.Serialization.Ssz.Test/HashUtility.cs @@ -33,7 +33,7 @@ public static byte[] Hash(ReadOnlySpan a, ReadOnlySpan b) { var combined = new Span(new byte[64]); a.CopyTo(combined); - b.CopyTo(combined.Slice(32)); + b.CopyTo(combined[32..]); return _hashAlgorithm.ComputeHash(combined.ToArray()); } diff --git a/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BasicTypes.cs b/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BasicTypes.cs index b279fc13485..258ffe75864 100644 --- a/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BasicTypes.cs +++ b/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BasicTypes.cs @@ -86,7 +86,7 @@ public static void Encode(Span span, ulong value) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void Encode(Span span, UInt128 value) { - BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(0, 8), (ulong)(value & ulong.MaxValue)); + BinaryPrimitives.WriteUInt64LittleEndian(span[..8], (ulong)(value & ulong.MaxValue)); BinaryPrimitives.WriteUInt64LittleEndian(span.Slice(8, 8), (ulong)(value >> 64)); } @@ -270,7 +270,7 @@ public static UInt128 DecodeUInt128(Span span) throw new InvalidDataException($"{nameof(DecodeUInt128)} expects input of length {expectedLength} and received {span.Length}"); } - ulong s0 = BinaryPrimitives.ReadUInt64LittleEndian(span.Slice(0, 8)); + ulong s0 = BinaryPrimitives.ReadUInt64LittleEndian(span[..8]); ulong s1 = BinaryPrimitives.ReadUInt64LittleEndian(span.Slice(8, 8)); return new UInt128(s0, s1); diff --git a/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BitArray.cs b/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BitArray.cs index e256f951834..5b865ba45ef 100644 --- a/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BitArray.cs +++ b/src/Nethermind/Nethermind.Serialization.Ssz/Ssz.BitArray.cs @@ -56,12 +56,12 @@ public static BitArray DecodeBitlist(ReadOnlySpan span) { BitArray value = new BitArray(span.ToArray()); int length = value.Length - 1; - int lastByte = span[span.Length - 1]; + int lastByte = span[^1]; int mask = 0x80; while ((lastByte & mask) == 0 && mask > 0) { length--; - mask = mask >> 1; + mask >>= 1; } value.Length = length; return value; diff --git a/src/Nethermind/Nethermind.Sockets/Extensions.cs b/src/Nethermind/Nethermind.Sockets/Extensions.cs index 7f4295ffec6..b4d066cb652 100644 --- a/src/Nethermind/Nethermind.Sockets/Extensions.cs +++ b/src/Nethermind/Nethermind.Sockets/Extensions.cs @@ -66,7 +66,7 @@ public static void UseWebSocketsModules(this IApplicationBuilder app) } finally { - if (!(module is null) && !string.IsNullOrWhiteSpace(id)) + if (module is not null && !string.IsNullOrWhiteSpace(id)) { module.RemoveClient(id); if (logger?.IsDebug == true) logger.Info($"Closing WebSockets for client: '{clientName}'."); diff --git a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoaderExtensions.cs b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoaderExtensions.cs index 65bed715981..97dbc200da2 100644 --- a/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoaderExtensions.cs +++ b/src/Nethermind/Nethermind.Specs/ChainSpecStyle/ChainSpecLoaderExtensions.cs @@ -82,10 +82,8 @@ public static ChainSpec LoadFromFile(this IChainSpecLoader chainSpecLoader, stri { // do nothing - the lines above just give extra info and config is loaded at the beginning so unlikely we have any catastrophic errors here } - finally - { - throw new FileNotFoundException(missingChainspecFileMessage.ToString()); - } + + throw new FileNotFoundException(missingChainspecFileMessage.ToString()); } if (logger.IsInfo) logger.Info($"Loading chainspec from file: {filePath}"); return chainSpecLoader.Load(File.ReadAllText(filePath)); diff --git a/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs b/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs index e7902956853..8f26b048bcb 100644 --- a/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs +++ b/src/Nethermind/Nethermind.Synchronization.Test/BlockDownloaderTests.cs @@ -1272,7 +1272,7 @@ public async Task BuildBlocksResponse(IList blockHashes, Re } BlockHeader startHeader = _blockTree.FindHeader(blockHashes[0], BlockTreeLookupOptions.None); - if (startHeader is null) startHeader = _headers[blockHashes[0]]; + startHeader ??= _headers[blockHashes[0]]; BlockHeader[] blockHeaders = new BlockHeader[blockHashes.Count]; BlockBody[] blockBodies = new BlockBody[blockHashes.Count]; diff --git a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs index 277d1fc5a50..2ab6379b3a2 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastBlocks/FastHeadersSyncFeed.cs @@ -715,9 +715,8 @@ protected virtual AddBlockResult InsertToBlockTree(BlockHeader header) protected void SetExpectedNextHeaderToParent(BlockHeader header) { - ulong nextHeaderDiff = 0; _nextHeaderHash = header.ParentHash!; - if (_expectedDifficultyOverride?.TryGetValue(header.Number, out nextHeaderDiff) == true) + if (_expectedDifficultyOverride?.TryGetValue(header.Number, out ulong nextHeaderDiff) == true) { _nextHeaderDiff = nextHeaderDiff; } diff --git a/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs b/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs index 5cd54367bf4..6c83c15a173 100644 --- a/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs +++ b/src/Nethermind/Nethermind.Synchronization/FastSync/TreeSync.cs @@ -781,7 +781,7 @@ private void HandleTrieNode(StateSyncItem currentStateSyncItem, byte[] currentRe HashSet alreadyProcessedChildHashes = new(); Span branchChildPath = stackalloc byte[currentStateSyncItem.PathNibbles.Length + 1]; - currentStateSyncItem.PathNibbles.CopyTo(branchChildPath.Slice(0, currentStateSyncItem.PathNibbles.Length)); + currentStateSyncItem.PathNibbles.CopyTo(branchChildPath[..currentStateSyncItem.PathNibbles.Length]); for (int childIndex = 15; childIndex >= 0; childIndex--) { @@ -838,8 +838,8 @@ private void HandleTrieNode(StateSyncItem currentStateSyncItem, byte[] currentRe // Add nibbles to StateSyncItem.PathNibbles Span childPath = stackalloc byte[currentStateSyncItem.PathNibbles.Length + trieNode.Key!.Length]; - currentStateSyncItem.PathNibbles.CopyTo(childPath.Slice(0, currentStateSyncItem.PathNibbles.Length)); - trieNode.Key!.CopyTo(childPath.Slice(currentStateSyncItem.PathNibbles.Length)); + currentStateSyncItem.PathNibbles.CopyTo(childPath[..currentStateSyncItem.PathNibbles.Length]); + trieNode.Key!.CopyTo(childPath[currentStateSyncItem.PathNibbles.Length..]); AddNodeResult addResult = AddNodeToPending( new StateSyncItem( @@ -901,8 +901,8 @@ private void HandleTrieNode(StateSyncItem currentStateSyncItem, byte[] currentRe // it's a leaf with a storage, so we need to copy the current path (full 64 nibbles) to StateSyncItem.AccountPathNibbles // and StateSyncItem.PathNibbles will start from null (storage root) Span childPath = stackalloc byte[currentStateSyncItem.PathNibbles.Length + trieNode.Key!.Length]; - currentStateSyncItem.PathNibbles.CopyTo(childPath.Slice(0, currentStateSyncItem.PathNibbles.Length)); - trieNode.Key!.CopyTo(childPath.Slice(currentStateSyncItem.PathNibbles.Length)); + currentStateSyncItem.PathNibbles.CopyTo(childPath[..currentStateSyncItem.PathNibbles.Length]); + trieNode.Key!.CopyTo(childPath[currentStateSyncItem.PathNibbles.Length..]); AddNodeResult addStorageNodeResult = AddNodeToPending(new StateSyncItem(storageRoot, childPath.ToArray(), null, NodeDataType.Storage, 0, currentStateSyncItem.Rightness), dependentItem, "storage"); if (addStorageNodeResult != AddNodeResult.AlreadySaved) diff --git a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerExtensions.cs b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerExtensions.cs index cf47ec860dd..c65dc1f8118 100644 --- a/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerExtensions.cs +++ b/src/Nethermind/Nethermind.Synchronization/Peers/SyncPeerExtensions.cs @@ -21,7 +21,7 @@ public static bool SupportsAllocation(this PeerInfo peerInfo, AllocationContexts && peerInfo.SyncPeer.ClientType == NodeClientType.OpenEthereum) // only for OE { // try get OpenEthereum version - Version? openEthereumVersion = peerInfo.SyncPeer.GetOpenEthereumVersion(out int releaseCandidate); + Version? openEthereumVersion = peerInfo.SyncPeer.GetOpenEthereumVersion(out _); if (openEthereumVersion is not null) { int versionComparision = openEthereumVersion.CompareTo(_openEthereumSecondRemoveGetNodeDataVersion); diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs index 7555ed5059d..ba072b0b85d 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs @@ -238,9 +238,10 @@ private static (AddRangeResult result, IList sortedBoundaryList, bool node.SetChild(ci, child); // TODO: we should optimize it - copy only if there are two boundary children - List newPath = new(path); - - newPath.Add((byte)ci); + List newPath = new(path) + { + (byte)ci + }; proofNodesToProcess.Push((node, child, pathIndex, newPath)); sortedBoundaryList.Add(child); diff --git a/src/Nethermind/Nethermind.Trie/HexPrefix.cs b/src/Nethermind/Nethermind.Trie/HexPrefix.cs index f9e782a097c..7b7af249182 100644 --- a/src/Nethermind/Nethermind.Trie/HexPrefix.cs +++ b/src/Nethermind/Nethermind.Trie/HexPrefix.cs @@ -19,7 +19,7 @@ public static void CopyToSpan(byte[] path, bool isLeaf, Span output) output[0] += (byte)(0x10 + path[0]); } - for (int i = 0; i < path.Length - 1; i = i + 2) + for (int i = 0; i < path.Length - 1; i += 2) { output[i / 2 + 1] = path.Length % 2 == 0 diff --git a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs index 334ac00c864..2735cbf81fb 100644 --- a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs +++ b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs @@ -362,7 +362,7 @@ public void Set(Span rawKey, Rlp? value) #endif TraverseContext traverseContext = - new(updatePath.Slice(0, nibblesCount), updateValue, isUpdate, ignoreMissingDelete); + new(updatePath[..nibblesCount], updateValue, isUpdate, ignoreMissingDelete); // lazy stack cleaning after the previous update if (traverseContext.IsUpdate) @@ -386,7 +386,7 @@ public void Set(Span rawKey, Rlp? value) if (traverseContext.UpdateValue is not null) { if (_logger.IsTrace) _logger.Trace($"Setting new leaf node with value {traverseContext.UpdateValue}"); - byte[] key = updatePath.Slice(0, nibblesCount).ToArray(); + byte[] key = updatePath[..nibblesCount].ToArray(); RootRef = TrieNodeFactory.CreateLeaf(key, traverseContext.UpdateValue); } @@ -701,9 +701,8 @@ which is not possible within the Ethereum protocol which has keys of the same le } int currentIndex = traverseContext.CurrentIndex + 1; - byte[] leafPath = traverseContext.UpdatePath.Slice( - currentIndex, - traverseContext.UpdatePath.Length - currentIndex).ToArray(); + byte[] leafPath = traverseContext.UpdatePath[ + currentIndex..].ToArray(); TrieNode leaf = TrieNodeFactory.CreateLeaf(leafPath, traverseContext.UpdateValue); ConnectNodes(leaf); @@ -792,7 +791,7 @@ which is not possible within the Ethereum protocol which has keys of the same le if (extensionLength != 0) { - ReadOnlySpan extensionPath = longerPath.Slice(0, extensionLength); + ReadOnlySpan extensionPath = longerPath[..extensionLength]; TrieNode extension = TrieNodeFactory.CreateExtension(extensionPath.ToArray()); _nodeStack.Push(new StackedNode(extension, 0)); } diff --git a/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs b/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs index 8504adda5ad..6af2bc29ef3 100644 --- a/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs +++ b/src/Nethermind/Nethermind.TxPool.Test/TxPoolTests.cs @@ -1505,10 +1505,7 @@ private TxPool CreatePool( new TransactionComparerProvider(specProvider, _blockTree); _headInfo = chainHeadInfoProvider; - if (_headInfo is null) - { - _headInfo = new ChainHeadInfoProvider(specProvider, _blockTree, _stateProvider); - } + _headInfo ??= new ChainHeadInfoProvider(specProvider, _blockTree, _stateProvider); return new TxPool( _ethereumEcdsa, diff --git a/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs b/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs index a09d5ba8f73..19f17ac2add 100644 --- a/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs +++ b/src/Nethermind/Nethermind.TxPool/Collections/SortedPool.cs @@ -86,10 +86,7 @@ protected SortedPool(int capacity, IComparer comparer) public TValue[] GetSnapshot() { TValue[]? snapshot = _snapshot; - if (snapshot is null) - { - snapshot = _snapshot = _buckets.SelectMany(b => b.Value).ToArray(); - } + snapshot ??= _snapshot = _buckets.SelectMany(b => b.Value).ToArray(); return snapshot; } diff --git a/src/Nethermind/Nethermind.TxPool/TxPool.cs b/src/Nethermind/Nethermind.TxPool/TxPool.cs index ebe6fa28218..30c9aa3d9f5 100644 --- a/src/Nethermind/Nethermind.TxPool/TxPool.cs +++ b/src/Nethermind/Nethermind.TxPool/TxPool.cs @@ -412,11 +412,8 @@ private AcceptTxResult AddCore(Transaction tx, TxFilteringState state, bool isPe } else { - if (previousTxBottleneck is null) - { - previousTxBottleneck = tx.CalculateAffordableGasPrice(_specProvider.GetCurrentHeadSpec().IsEip1559Enabled, + previousTxBottleneck ??= tx.CalculateAffordableGasPrice(_specProvider.GetCurrentHeadSpec().IsEip1559Enabled, _headInfo.CurrentBaseFee, balance); - } if (tx.Nonce == currentNonce + i) {