From 6744d21a6cda51b0d1829739b6cddbe72e125d39 Mon Sep 17 00:00:00 2001 From: Ben Adams Date: Tue, 12 Dec 2023 03:04:55 +0000 Subject: [PATCH] Use runtime throw helpers (#6348) --- .../NewPendingUserOpsSubscription.cs | 2 +- .../NewReceivedUserOpsSubscription.cs | 2 +- .../Nethermind.Blockchain/BlockTree.cs | 2 +- .../Nethermind.Cli/Modules/CliModuleLoader.cs | 5 +- .../Rewards/AuRaRewardCalculator.cs | 8 +-- .../Validators/ListBasedValidator.cs | 2 +- .../Validators/MultiValidator.cs | 2 +- .../Processing/CompositeDataRecoveryStep.cs | 2 +- .../Processing/ReadOnlyTxProcessingEnv.cs | 4 +- .../IBlockProductionTriggerExtensions.cs | 10 +-- .../Nethermind.Consensus/Tracing/Tracer.cs | 4 +- .../Transactions/TxFilterPipelineBuilder.cs | 2 +- src/Nethermind/Nethermind.Core/Address.cs | 5 +- .../Nethermind.Core/Caching/LruCache.cs | 5 +- .../Nethermind.Core/Caching/SpanLruCache.cs | 5 +- .../Collections/IListExtensions.cs | 4 +- .../Collections/LinkedHashSet.cs | 20 +++--- .../Collections/SpanDictionary.cs | 15 +---- .../Nethermind.Crypto/PrivateKey.cs | 5 +- .../SecureStringExtensions.cs | 10 +-- .../Nethermind.Db.Rocks/DbOnTheRocks.cs | 66 ++++--------------- .../Nethermind.Db/ReadOnlyDbProvider.cs | 5 +- .../Nethermind.Db/SimpleFilePublicKeyDb.cs | 2 +- .../Tracing/GethStyle/JavaScript/Engine.cs | 5 +- .../Filters/FilterManager.cs | 10 +-- .../Steps/EthereumStepsManager.cs | 5 +- ...BlocksSyncPeerAllocationStrategyFactory.cs | 6 +- .../Nethermind.Network.Dns/EnrTreeParser.cs | 2 +- .../Nethermind.Network/P2P/Session.cs | 4 +- .../Logging/CustomMicrosoftLogger.cs | 5 +- .../Nethermind.Sockets/WebSocketStream.cs | 2 +- .../Nethermind.State/StateProvider.cs | 4 +- .../BlocksSyncPeerSelectionStrategyFactory.cs | 6 +- .../SnapSync/SnapProviderHelper.cs | 5 +- .../Nethermind.Trie/NibbleExtensions.cs | 5 +- .../Nethermind.Trie/PatriciaTree.cs | 4 +- .../Nethermind.Trie/Pruning/TrieStore.cs | 14 ++-- .../Collections/TxDistinctSortedPool.cs | 2 +- 38 files changed, 80 insertions(+), 186 deletions(-) diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs index d615a81b765..55ba958faed 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewPendingUserOpsSubscription.cs @@ -25,7 +25,7 @@ public NewPendingUserOpsSubscription( UserOperationSubscriptionParam? userOperationSubscriptionParam = null) : base(jsonRpcDuplexClient) { - if (userOperationPools is null) throw new ArgumentNullException(nameof(userOperationPools)); + ArgumentNullException.ThrowIfNull(userOperationPools); if (userOperationSubscriptionParam is not null) { if (userOperationSubscriptionParam.EntryPoints.Length == 0) diff --git a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs index 4288b9a5305..49f3c5ed1b2 100644 --- a/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs +++ b/src/Nethermind/Nethermind.AccountAbstraction/Subscribe/NewReceivedUserOpsSubscription.cs @@ -25,7 +25,7 @@ public NewReceivedUserOpsSubscription( UserOperationSubscriptionParam? userOperationSubscriptionParam = null) : base(jsonRpcDuplexClient) { - if (userOperationPools is null) throw new ArgumentNullException(nameof(userOperationPools)); + ArgumentNullException.ThrowIfNull(userOperationPools); if (userOperationSubscriptionParam is not null) { if (userOperationSubscriptionParam.EntryPoints.Length == 0) diff --git a/src/Nethermind/Nethermind.Blockchain/BlockTree.cs b/src/Nethermind/Nethermind.Blockchain/BlockTree.cs index 52207849d4a..14d1f297ca4 100644 --- a/src/Nethermind/Nethermind.Blockchain/BlockTree.cs +++ b/src/Nethermind/Nethermind.Blockchain/BlockTree.cs @@ -560,7 +560,7 @@ public BlockHeader[] FindHeaders(Hash256? blockHash, int numberOfBlocks, int ski { static BlockHeader[] FindHeadersReversedFast(BlockTree tree, BlockHeader startHeader, int numberOfBlocks, bool reverse = false) { - if (startHeader is null) throw new ArgumentNullException(nameof(startHeader)); + ArgumentNullException.ThrowIfNull(startHeader); if (numberOfBlocks == 1) { return new[] { startHeader }; diff --git a/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs b/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs index 21ac2e6079e..e9d4db08c83 100644 --- a/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs +++ b/src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs @@ -45,10 +45,7 @@ public CliModuleLoader(ICliEngine engine, IJsonRpcClient client, ICliConsole cli /// private static Delegate CreateDelegate(MethodInfo methodInfo, CliModuleBase module) { - if (methodInfo is null) - { - throw new ArgumentNullException(nameof(methodInfo)); - } + ArgumentNullException.ThrowIfNull(methodInfo); ParameterInfo[] parameterInfos = methodInfo.GetParameters(); Type[] types = new Type[parameterInfos.Length + 1]; diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs index 17ba98510f5..ddb4590435d 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Rewards/AuRaRewardCalculator.cs @@ -20,9 +20,9 @@ public class AuRaRewardCalculator : IRewardCalculator public AuRaRewardCalculator(AuRaParameters auRaParameters, IAbiEncoder abiEncoder, ITransactionProcessor transactionProcessor) { - if (auRaParameters is null) throw new ArgumentNullException(nameof(auRaParameters)); - if (abiEncoder is null) throw new ArgumentNullException(nameof(abiEncoder)); - if (transactionProcessor is null) throw new ArgumentNullException(nameof(transactionProcessor)); + ArgumentNullException.ThrowIfNull(auRaParameters); + ArgumentNullException.ThrowIfNull(abiEncoder); + ArgumentNullException.ThrowIfNull(transactionProcessor); IList BuildTransitions() { @@ -48,7 +48,7 @@ IList BuildTransitions() return contracts; } - if (auRaParameters is null) throw new ArgumentNullException(nameof(AuRaParameters)); + ArgumentNullException.ThrowIfNull(auRaParameters); _contracts = BuildTransitions(); _blockRewardCalculator = new StaticRewardCalculator(auRaParameters.BlockReward); } diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs index b875b2552fb..a0bcd876ee7 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/ListBasedValidator.cs @@ -12,7 +12,7 @@ public sealed class ListBasedValidator : AuRaValidatorBase public ListBasedValidator(AuRaParameters.Validator validator, IValidSealerStrategy validSealerStrategy, IValidatorStore validatorStore, ILogManager logManager, long startBlockNumber, bool forSealing = false) : base(validSealerStrategy, validatorStore, logManager, startBlockNumber, forSealing) { - if (validator is null) throw new ArgumentNullException(nameof(validator)); + ArgumentNullException.ThrowIfNull(validator); Validators = validator.Addresses?.Length > 0 ? validator.Addresses diff --git a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs index 0e029cde8cd..fc7f041d37c 100644 --- a/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs +++ b/src/Nethermind/Nethermind.Consensus.AuRa/Validators/MultiValidator.cs @@ -38,7 +38,7 @@ public MultiValidator( ILogManager logManager, bool forSealing = false) { - if (validator is null) throw new ArgumentNullException(nameof(validator)); + ArgumentNullException.ThrowIfNull(validator); if (validator.ValidatorType != AuRaParameters.ValidatorType.Multi) throw new ArgumentException("Wrong validator type.", nameof(validator)); _validatorFactory = validatorFactory ?? throw new ArgumentNullException(nameof(validatorFactory)); _blockTree = blockTree ?? throw new ArgumentNullException(nameof(blockTree)); diff --git a/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs b/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs index 697682c2d2f..87c5d4a7bc8 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/CompositeDataRecoveryStep.cs @@ -13,7 +13,7 @@ public class CompositeBlockPreprocessorStep : IBlockPreprocessorStep public CompositeBlockPreprocessorStep(params IBlockPreprocessorStep[] recoverySteps) { - if (recoverySteps is null) throw new ArgumentNullException(nameof(recoverySteps)); + ArgumentNullException.ThrowIfNull(recoverySteps); _recoverySteps = new LinkedList(); for (int i = 0; i < recoverySteps.Length; i++) diff --git a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs index 66d1e91cd4e..060b52ca5dc 100644 --- a/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs +++ b/src/Nethermind/Nethermind.Consensus/Processing/ReadOnlyTxProcessingEnv.cs @@ -38,8 +38,8 @@ public ReadOnlyTxProcessingEnv( ISpecProvider? specProvider, ILogManager? logManager) { - if (specProvider is null) throw new ArgumentNullException(nameof(specProvider)); - if (worldStateManager is null) throw new ArgumentNullException(nameof(worldStateManager)); + ArgumentNullException.ThrowIfNull(specProvider); + ArgumentNullException.ThrowIfNull(worldStateManager); StateReader = worldStateManager.GlobalStateReader; StateProvider = worldStateManager.CreateResettableWorldState(); diff --git a/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs b/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs index 29948b64eb3..ae7c1337776 100644 --- a/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs +++ b/src/Nethermind/Nethermind.Consensus/Producers/IBlockProductionTriggerExtensions.cs @@ -10,21 +10,21 @@ public static class BlockProductionTriggerExtensions { public static IBlockProductionTrigger IfPoolIsNotEmpty(this IBlockProductionTrigger? trigger, ITxPool? txPool) { - if (trigger is null) throw new ArgumentNullException(nameof(trigger)); - if (txPool is null) throw new ArgumentNullException(nameof(txPool)); + ArgumentNullException.ThrowIfNull(trigger); + ArgumentNullException.ThrowIfNull(txPool); return trigger.ButOnlyWhen(() => txPool.GetPendingTransactionsCount() > 0); } public static IBlockProductionTrigger ButOnlyWhen(this IBlockProductionTrigger? trigger, Func condition) { - if (trigger is null) throw new ArgumentNullException(nameof(trigger)); + ArgumentNullException.ThrowIfNull(trigger); return new TriggerWithCondition(trigger, condition); } public static IBlockProductionTrigger Or(this IBlockProductionTrigger? trigger, IBlockProductionTrigger? alternative) { - if (trigger is null) throw new ArgumentNullException(nameof(trigger)); - if (alternative is null) throw new ArgumentNullException(nameof(alternative)); + ArgumentNullException.ThrowIfNull(trigger); + ArgumentNullException.ThrowIfNull(alternative); if (trigger is CompositeBlockProductionTrigger composite1) { diff --git a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs index dd5da483e28..00c2a85147d 100644 --- a/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs +++ b/src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs @@ -53,8 +53,8 @@ We also want to make it read only so the state is not modified persistently in a public void Accept(ITreeVisitor visitor, Hash256 stateRoot) { - if (visitor is null) throw new ArgumentNullException(nameof(visitor)); - if (stateRoot is null) throw new ArgumentNullException(nameof(stateRoot)); + ArgumentNullException.ThrowIfNull(visitor); + ArgumentNullException.ThrowIfNull(stateRoot); _stateProvider.Accept(visitor, stateRoot); } diff --git a/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs b/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs index 318ad9dd4ac..20f607a6ece 100644 --- a/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs +++ b/src/Nethermind/Nethermind.Consensus/Transactions/TxFilterPipelineBuilder.cs @@ -17,7 +17,7 @@ public static ITxFilterPipeline CreateStandardFilteringPipeline( ISpecProvider? specProvider, IBlocksConfig blocksConfig) { - if (specProvider is null) throw new ArgumentNullException(nameof(specProvider)); + ArgumentNullException.ThrowIfNull(specProvider); return new TxFilterPipelineBuilder(logManager) .WithMinGasPriceFilter(blocksConfig, specProvider) diff --git a/src/Nethermind/Nethermind.Core/Address.cs b/src/Nethermind/Nethermind.Core/Address.cs index d92d67e1193..176a4b9cffc 100644 --- a/src/Nethermind/Nethermind.Core/Address.cs +++ b/src/Nethermind/Nethermind.Core/Address.cs @@ -109,10 +109,7 @@ public static bool TryParseVariableLength(string? value, out Address? address) public Address(byte[] bytes) { - if (bytes is null) - { - throw new ArgumentNullException(nameof(bytes)); - } + ArgumentNullException.ThrowIfNull(bytes); if (bytes.Length != Size) { diff --git a/src/Nethermind/Nethermind.Core/Caching/LruCache.cs b/src/Nethermind/Nethermind.Core/Caching/LruCache.cs index af2785f6aeb..6301cd72da5 100644 --- a/src/Nethermind/Nethermind.Core/Caching/LruCache.cs +++ b/src/Nethermind/Nethermind.Core/Caching/LruCache.cs @@ -17,10 +17,7 @@ public sealed class LruCache : ICache where TKey : n public LruCache(int maxCapacity, int startCapacity, string name) { - if (maxCapacity < 1) - { - throw new ArgumentOutOfRangeException(); - } + ArgumentOutOfRangeException.ThrowIfLessThan(maxCapacity, 1); _maxCapacity = maxCapacity; _cacheMap = typeof(TKey) == typeof(byte[]) diff --git a/src/Nethermind/Nethermind.Core/Caching/SpanLruCache.cs b/src/Nethermind/Nethermind.Core/Caching/SpanLruCache.cs index 2c771a1d8b7..11d36c676f4 100644 --- a/src/Nethermind/Nethermind.Core/Caching/SpanLruCache.cs +++ b/src/Nethermind/Nethermind.Core/Caching/SpanLruCache.cs @@ -23,10 +23,7 @@ public sealed class SpanLruCache : ISpanCache where public SpanLruCache(int maxCapacity, int startCapacity, string name, ISpanEqualityComparer comparer) { - if (maxCapacity < 1) - { - throw new ArgumentOutOfRangeException(); - } + ArgumentOutOfRangeException.ThrowIfLessThan(maxCapacity, 1); _maxCapacity = maxCapacity; _cacheMap = new SpanDictionary>(startCapacity, comparer); diff --git a/src/Nethermind/Nethermind.Core/Collections/IListExtensions.cs b/src/Nethermind/Nethermind.Core/Collections/IListExtensions.cs index 06657fb490b..daf8c776961 100644 --- a/src/Nethermind/Nethermind.Core/Collections/IListExtensions.cs +++ b/src/Nethermind/Nethermind.Core/Collections/IListExtensions.cs @@ -30,8 +30,8 @@ public static void ForEach(this IReadOnlyList list, Action action) /// public static int BinarySearch(this IList list, TSearch value, Func comparer) { - if (list is null) throw new ArgumentNullException(nameof(list)); - if (comparer is null) throw new ArgumentNullException(nameof(comparer)); + ArgumentNullException.ThrowIfNull(list); + ArgumentNullException.ThrowIfNull(comparer); int lower = 0; int upper = list.Count - 1; diff --git a/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs b/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs index a98ef4efd75..1d9370d2aab 100644 --- a/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs +++ b/src/Nethermind/Nethermind.Core/Collections/LinkedHashSet.cs @@ -57,7 +57,7 @@ public bool Add(T item) public void ExceptWith(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); foreach (T t in other) { @@ -67,7 +67,7 @@ public void ExceptWith(IEnumerable? other) public void IntersectWith(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); T[] ts = new T[Count]; CopyTo(ts, 0); @@ -83,7 +83,7 @@ public void IntersectWith(IEnumerable? other) public bool IsProperSubsetOf(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); int contains = 0; int noContains = 0; @@ -104,7 +104,7 @@ public bool IsProperSubsetOf(IEnumerable? other) public bool IsProperSupersetOf(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); ISet set = other.ToHashSet(); int otherCount = set.Count; @@ -132,7 +132,7 @@ public bool IsProperSupersetOf(IEnumerable? other) public bool IsSubsetOf(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); ISet set = other.ToHashSet(); return this.All(t => set.Contains(t)); @@ -140,21 +140,21 @@ public bool IsSubsetOf(IEnumerable? other) public bool IsSupersetOf(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); return other.All(Contains); } public bool Overlaps(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); return other.Any(Contains); } public bool SetEquals(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); ISet set = other.ToHashSet(); return Count == set.Count && IsSupersetOf(set); @@ -162,7 +162,7 @@ public bool SetEquals(IEnumerable? other) public void SymmetricExceptWith(IEnumerable other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); T[] ts = new T[Count]; CopyTo(ts, 0); @@ -186,7 +186,7 @@ public void SymmetricExceptWith(IEnumerable other) public void UnionWith(IEnumerable? other) { - if (other is null) throw new ArgumentNullException(nameof(other)); + ArgumentNullException.ThrowIfNull(other); foreach (T t in other) { diff --git a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs index f6dcbb5b08b..e7e634550f2 100644 --- a/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs +++ b/src/Nethermind/Nethermind.Core/Collections/SpanDictionary.cs @@ -39,10 +39,7 @@ public SpanDictionary(ISpanEqualityComparer comparer) : this(0, comparer) public SpanDictionary(int capacity, ISpanEqualityComparer comparer) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); if (capacity > 0) { @@ -946,10 +943,7 @@ void ICollection.CopyTo(Array array, int index) /// public int EnsureCapacity(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); int currentCapacity = _entries == null ? 0 : _entries.Length; if (currentCapacity >= capacity) @@ -992,10 +986,7 @@ public int EnsureCapacity(int capacity) /// public void TrimExcess(int capacity) { - if (capacity < Count) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfLessThan(capacity, Count); int newSize = HashHelpers.GetPrime(capacity); Entry[]? oldEntries = _entries; diff --git a/src/Nethermind/Nethermind.Crypto/PrivateKey.cs b/src/Nethermind/Nethermind.Crypto/PrivateKey.cs index ab5dedc6575..1f2a9ed6b35 100644 --- a/src/Nethermind/Nethermind.Crypto/PrivateKey.cs +++ b/src/Nethermind/Nethermind.Crypto/PrivateKey.cs @@ -27,10 +27,7 @@ public PrivateKey(string hexString) public PrivateKey(byte[] keyBytes) { - if (keyBytes is null) - { - throw new ArgumentNullException(nameof(keyBytes)); - } + ArgumentNullException.ThrowIfNull(keyBytes); if (!SecP256k1.VerifyPrivateKey(keyBytes)) { diff --git a/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs b/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs index 17ba7ca42b4..26c8859dd11 100644 --- a/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs +++ b/src/Nethermind/Nethermind.Crypto/SecureStringExtensions.cs @@ -11,10 +11,7 @@ public static class SecureStringExtensions { public static byte[] ToByteArray(this SecureString secureString, System.Text.Encoding encoding = null) { - if (secureString is null) - { - throw new ArgumentNullException(nameof(secureString)); - } + ArgumentNullException.ThrowIfNull(secureString); encoding ??= System.Text.Encoding.UTF8; @@ -35,10 +32,7 @@ public static byte[] ToByteArray(this SecureString secureString, System.Text.Enc public static string Unsecure(this SecureString secureString) { - if (secureString is null) - { - throw new ArgumentNullException(nameof(secureString)); - } + ArgumentNullException.ThrowIfNull(secureString); IntPtr unmanagedString = IntPtr.Zero; try diff --git a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs index 1dcc79ff0b6..100103c5744 100644 --- a/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs +++ b/src/Nethermind/Nethermind.Db.Rocks/DbOnTheRocks.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.IO; using System.IO.Abstractions; +using System.Net.Sockets; using System.Reflection; using System.Threading; using ConcurrentCollections; @@ -479,10 +480,7 @@ public byte[]? this[ReadOnlySpan key] internal byte[]? GetWithColumnFamily(ReadOnlySpan key, ColumnFamilyHandle? cf, ManagedIterators readaheadIterators, ReadFlags flags = ReadFlags.None) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to read form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); UpdateReadMetrics(); @@ -519,10 +517,7 @@ public void Set(ReadOnlySpan key, byte[]? value, WriteFlags flags = WriteF internal void SetWithColumnFamily(ReadOnlySpan key, ColumnFamilyHandle? cf, ReadOnlySpan value, WriteFlags flags = WriteFlags.None) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to write to a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); UpdateWriteMetrics(); @@ -588,10 +583,7 @@ public Span GetSpan(ReadOnlySpan key, ReadFlags flags) internal Span GetSpanWithColumnFamily(ReadOnlySpan key, ColumnFamilyHandle? cf) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to read form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); UpdateReadMetrics(); @@ -629,10 +621,7 @@ public void DangerousReleaseMemory(in Span span) public void Remove(ReadOnlySpan key) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to delete form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); try { @@ -647,10 +636,7 @@ public void Remove(ReadOnlySpan key) public IEnumerable> GetAll(bool ordered = false) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to create an iterator on a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); Iterator iterator = CreateIterator(ordered); return GetAllCore(iterator); @@ -674,10 +660,7 @@ protected internal Iterator CreateIterator(bool ordered = false, ColumnFamilyHan public IEnumerable GetAllValues(bool ordered = false) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to read form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); Iterator iterator = CreateIterator(ordered); return GetAllValuesCore(iterator); @@ -729,10 +712,7 @@ internal IEnumerable GetAllValuesCore(Iterator iterator) { try { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to read form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); try { @@ -775,10 +755,7 @@ internal IEnumerable GetAllValuesCore(Iterator iterator) public bool KeyExists(ReadOnlySpan key) { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to read form a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); try { @@ -823,10 +800,7 @@ public RocksDbWriteBatch(DbOnTheRocks dbOnTheRocks) _dbOnTheRocks = dbOnTheRocks; _rocksBatch = CreateWriteBatch(); - if (_dbOnTheRocks._isDisposing) - { - throw new ObjectDisposedException($"Attempted to create a batch on a disposed database {_dbOnTheRocks.Name}"); - } + ObjectDisposedException.ThrowIf(_dbOnTheRocks._isDisposing, _dbOnTheRocks); } private static WriteBatch CreateWriteBatch() @@ -853,10 +827,7 @@ private static void ReturnWriteBatch(WriteBatch batch) public void Dispose() { - if (_dbOnTheRocks._isDisposed) - { - throw new ObjectDisposedException($"Attempted to commit a batch on a disposed database {_dbOnTheRocks.Name}"); - } + ObjectDisposedException.ThrowIf(_dbOnTheRocks._isDisposed, _dbOnTheRocks); if (_isDisposed) { @@ -879,20 +850,14 @@ public void Dispose() public void Delete(ReadOnlySpan key, ColumnFamilyHandle? cf = null) { - if (_isDisposed) - { - throw new ObjectDisposedException($"Attempted to write a disposed batch {_dbOnTheRocks.Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposed, this); _rocksBatch.Delete(key, cf); } public void Set(ReadOnlySpan key, ReadOnlySpan value, ColumnFamilyHandle? cf = null, WriteFlags flags = WriteFlags.None) { - if (_isDisposed) - { - throw new ObjectDisposedException($"Attempted to write a disposed batch {_dbOnTheRocks.Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposed, this); if (value.IsNull()) { @@ -938,10 +903,7 @@ private void FlushOnTooManyWrites() public void Flush() { - if (_isDisposing) - { - throw new ObjectDisposedException($"Attempted to flush a disposed database {Name}"); - } + ObjectDisposedException.ThrowIf(_isDisposing, this); InnerFlush(); } diff --git a/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs b/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs index 3c6117e2313..f211ca259bb 100644 --- a/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs +++ b/src/Nethermind/Nethermind.Db/ReadOnlyDbProvider.cs @@ -18,10 +18,7 @@ public ReadOnlyDbProvider(IDbProvider? wrappedProvider, bool createInMemoryWrite { _wrappedProvider = wrappedProvider ?? throw new ArgumentNullException(nameof(wrappedProvider)); _createInMemoryWriteStore = createInMemoryWriteStore; - if (wrappedProvider is null) - { - throw new ArgumentNullException(nameof(wrappedProvider)); - } + ArgumentNullException.ThrowIfNull(wrappedProvider); } public void Dispose() diff --git a/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs b/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs index b917ac18cb4..499f2104b2d 100644 --- a/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs +++ b/src/Nethermind/Nethermind.Db/SimpleFilePublicKeyDb.cs @@ -36,7 +36,7 @@ public class SimpleFilePublicKeyDb : IFullDb public SimpleFilePublicKeyDb(string name, string dbDirectoryPath, ILogManager logManager) { _logger = logManager.GetClassLogger() ?? throw new ArgumentNullException(nameof(logManager)); - if (dbDirectoryPath is null) throw new ArgumentNullException(nameof(dbDirectoryPath)); + ArgumentNullException.ThrowIfNull(dbDirectoryPath); Name = name ?? throw new ArgumentNullException(nameof(name)); DbPath = Path.Combine(dbDirectoryPath, DbFileName); Description = $"{Name}|{DbPath}"; diff --git a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/Engine.cs b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/Engine.cs index 69268330ce1..1b5e26d2ba3 100644 --- a/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/Engine.cs +++ b/src/Nethermind/Nethermind.Evm/Tracing/GethStyle/JavaScript/Engine.cs @@ -134,10 +134,7 @@ public Engine(IReleaseSpec spec) /// private ITypedArray Slice(object input, long start, long end) { - if (input == null) - { - throw new ArgumentNullException(nameof(input)); - } + ArgumentNullException.ThrowIfNull(input); if (start < 0 || end < start || end > Array.MaxLength) { diff --git a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs index fb7c0567339..f8b1c84b50d 100644 --- a/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs +++ b/src/Nethermind/Nethermind.Facade/Filters/FilterManager.cs @@ -158,10 +158,7 @@ public Hash256[] PollPendingTransactionHashes(int filterId) private void AddReceipts(TxReceipt txReceipt) { - if (txReceipt is null) - { - throw new ArgumentNullException(nameof(txReceipt)); - } + ArgumentNullException.ThrowIfNull(txReceipt); IEnumerable filters = _filterStore.GetFilters(); foreach (LogFilter filter in filters) @@ -172,10 +169,7 @@ private void AddReceipts(TxReceipt txReceipt) private void AddBlock(Block block) { - if (block is null) - { - throw new ArgumentNullException(nameof(block)); - } + ArgumentNullException.ThrowIfNull(block); IEnumerable filters = _filterStore.GetFilters(); diff --git a/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs b/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs index c713f5b0fbb..9765801b588 100644 --- a/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs +++ b/src/Nethermind/Nethermind.Init/Steps/EthereumStepsManager.cs @@ -29,10 +29,7 @@ public EthereumStepsManager( INethermindApi context, ILogManager logManager) { - if (loader is null) - { - throw new ArgumentNullException(nameof(loader)); - } + ArgumentNullException.ThrowIfNull(loader); _api = context ?? throw new ArgumentNullException(nameof(context)); _logger = logManager?.GetClassLogger() diff --git a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs index b3e0154176a..2f68659318f 100644 --- a/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs +++ b/src/Nethermind/Nethermind.Merge.Plugin/Synchronization/MergeBlocksSyncPeerAllocationStrategyFactory.cs @@ -29,11 +29,7 @@ public MergeBlocksSyncPeerAllocationStrategyFactory( public IPeerAllocationStrategy Create(BlocksRequest? request) { // because of the way the generics cannot handle T / T? - if (request is null) - { - throw new ArgumentNullException( - $"NULL received for allocation in {nameof(MergeBlocksSyncPeerAllocationStrategyFactory)}"); - } + ArgumentNullException.ThrowIfNull(request); IPeerAllocationStrategy baseStrategy = new BlocksSyncPeerAllocationStrategy(request.NumberOfLatestBlocksToBeIgnored); TotalDiffStrategy preMergeAllocationStrategy = new(baseStrategy); diff --git a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs index 4ba71cc8c36..aeac844f881 100644 --- a/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs +++ b/src/Nethermind/Nethermind.Network.Dns/EnrTreeParser.cs @@ -58,7 +58,7 @@ public static EnrTreeBranch ParseBranch(string enrTreeBranchText) public static EnrTreeRoot ParseEnrRoot(string enrTreeRootText) { - if (enrTreeRootText is null) throw new ArgumentNullException(nameof(enrTreeRootText)); + ArgumentNullException.ThrowIfNull(enrTreeRootText); EnrTreeRoot enrTreeRoot = new(); diff --git a/src/Nethermind/Nethermind.Network/P2P/Session.cs b/src/Nethermind/Nethermind.Network/P2P/Session.cs index 8b1bbda7e85..d458e73556d 100644 --- a/src/Nethermind/Nethermind.Network/P2P/Session.cs +++ b/src/Nethermind/Nethermind.Network/P2P/Session.cs @@ -279,8 +279,8 @@ public void Init(byte p2PVersion, IChannelHandlerContext context, IPacketSender { if (_logger.IsTrace) _logger.Trace($"{nameof(Init)} called on {this}"); - if (context is null) throw new ArgumentNullException(nameof(context)); - if (packetSender is null) throw new ArgumentNullException(nameof(packetSender)); + ArgumentNullException.ThrowIfNull(context); + ArgumentNullException.ThrowIfNull(packetSender); P2PVersion = p2PVersion; lock (_sessionStateLock) diff --git a/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs b/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs index 7e5c99c3afe..c6f352c7582 100644 --- a/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs +++ b/src/Nethermind/Nethermind.Runner/Logging/CustomMicrosoftLogger.cs @@ -22,10 +22,7 @@ public void Log(LogLevel logLevel, EventId eventId, TState state, Except return; } - if (formatter is null) - { - throw new ArgumentNullException(nameof(formatter)); - } + ArgumentNullException.ThrowIfNull(formatter); var message = formatter(state, exception); switch (logLevel) diff --git a/src/Nethermind/Nethermind.Sockets/WebSocketStream.cs b/src/Nethermind/Nethermind.Sockets/WebSocketStream.cs index c2d36755256..a423103ca9b 100644 --- a/src/Nethermind/Nethermind.Sockets/WebSocketStream.cs +++ b/src/Nethermind/Nethermind.Sockets/WebSocketStream.cs @@ -103,6 +103,6 @@ protected override void Dispose(bool disposing) private void ThrowIfDisposed() { - if (_socket == null) throw new ObjectDisposedException(nameof(_socket)); + ObjectDisposedException.ThrowIf(_socket == null, _socket); } } diff --git a/src/Nethermind/Nethermind.State/StateProvider.cs b/src/Nethermind/Nethermind.State/StateProvider.cs index ac0b6c7334d..2e7ebf9d8d2 100644 --- a/src/Nethermind/Nethermind.State/StateProvider.cs +++ b/src/Nethermind/Nethermind.State/StateProvider.cs @@ -48,8 +48,8 @@ public StateProvider(ITrieStore? trieStore, IKeyValueStore? codeDb, ILogManager? public void Accept(ITreeVisitor? visitor, Hash256? stateRoot, VisitingOptions? visitingOptions = null) { - if (visitor is null) throw new ArgumentNullException(nameof(visitor)); - if (stateRoot is null) throw new ArgumentNullException(nameof(stateRoot)); + ArgumentNullException.ThrowIfNull(visitor); + ArgumentNullException.ThrowIfNull(stateRoot); _tree.Accept(visitor, stateRoot, visitingOptions); } diff --git a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs index e0069f7dd2a..60bb5d79f64 100644 --- a/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs +++ b/src/Nethermind/Nethermind.Synchronization/Blocks/BlocksSyncPeerSelectionStrategyFactory.cs @@ -12,11 +12,7 @@ internal class BlocksSyncPeerAllocationStrategyFactory : IPeerAllocationStrategy public IPeerAllocationStrategy Create(BlocksRequest? request) { // because of the way the generics cannot handle T / T? - if (request is null) - { - throw new ArgumentNullException( - $"NULL received for allocation in {nameof(BlocksSyncPeerAllocationStrategyFactory)}"); - } + ArgumentNullException.ThrowIfNull(request); IPeerAllocationStrategy baseStrategy = new BlocksSyncPeerAllocationStrategy(request.NumberOfLatestBlocksToBeIgnored); diff --git a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs index 17397b6c83c..fbdcc51d133 100644 --- a/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs +++ b/src/Nethermind/Nethermind.Synchronization/SnapSync/SnapProviderHelper.cs @@ -135,10 +135,7 @@ private static (AddRangeResult result, List sortedBoundaryList, bool m return (AddRangeResult.OK, null, false); } - if (tree is null) - { - throw new ArgumentNullException(nameof(tree)); - } + ArgumentNullException.ThrowIfNull(tree); ValueHash256 effectiveStartingHAsh = startingHash.HasValue ? startingHash.Value : ValueKeccak.Zero; List sortedBoundaryList = new(); diff --git a/src/Nethermind/Nethermind.Trie/NibbleExtensions.cs b/src/Nethermind/Nethermind.Trie/NibbleExtensions.cs index a760a021440..e1229aa6727 100644 --- a/src/Nethermind/Nethermind.Trie/NibbleExtensions.cs +++ b/src/Nethermind/Nethermind.Trie/NibbleExtensions.cs @@ -50,10 +50,7 @@ static void ThrowArgumentException() public static Nibble[] FromHexString(string hexString) { - if (hexString is null) - { - throw new ArgumentNullException($"{nameof(hexString)}"); - } + ArgumentNullException.ThrowIfNull(hexString); int startIndex = hexString.StartsWith("0x") ? 2 : 0; int numberChars = hexString.Length - startIndex; diff --git a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs index 65023481773..537f7dcd311 100644 --- a/src/Nethermind/Nethermind.Trie/PatriciaTree.cs +++ b/src/Nethermind/Nethermind.Trie/PatriciaTree.cs @@ -1060,8 +1060,8 @@ public override string ToString() public void Accept(ITreeVisitor visitor, Hash256 rootHash, VisitingOptions? visitingOptions = null) { - if (visitor is null) throw new ArgumentNullException(nameof(visitor)); - if (rootHash is null) throw new ArgumentNullException(nameof(rootHash)); + ArgumentNullException.ThrowIfNull(visitor); + ArgumentNullException.ThrowIfNull(rootHash); visitingOptions ??= VisitingOptions.Default; using TrieVisitContext trieVisitContext = new() diff --git a/src/Nethermind/Nethermind.Trie/Pruning/TrieStore.cs b/src/Nethermind/Nethermind.Trie/Pruning/TrieStore.cs index 976483b4172..ea488534bb2 100644 --- a/src/Nethermind/Nethermind.Trie/Pruning/TrieStore.cs +++ b/src/Nethermind/Nethermind.Trie/Pruning/TrieStore.cs @@ -207,7 +207,7 @@ public int CachedNodesCount public void CommitNode(long blockNumber, NodeCommitInfo nodeCommitInfo, WriteFlags writeFlags = WriteFlags.None) { - if (blockNumber < 0) throw new ArgumentOutOfRangeException(nameof(blockNumber)); + ArgumentOutOfRangeException.ThrowIfNegative(blockNumber); EnsureCommitSetExistsForBlock(blockNumber); if (_logger.IsTrace) _logger.Trace($"Committing {nodeCommitInfo} at {blockNumber}"); @@ -278,7 +278,7 @@ private TrieNode SaveOrReplaceInDirtyNodesCache(NodeCommitInfo nodeCommitInfo, T public void FinishBlockCommit(TrieType trieType, long blockNumber, TrieNode? root, WriteFlags writeFlags = WriteFlags.None) { - if (blockNumber < 0) throw new ArgumentOutOfRangeException(nameof(blockNumber)); + ArgumentOutOfRangeException.ThrowIfNegative(blockNumber); EnsureCommitSetExistsForBlock(blockNumber); try @@ -367,10 +367,7 @@ public TrieNode FindCachedOrUnknown(Hash256? hash) internal TrieNode FindCachedOrUnknown(Hash256? hash, bool isReadOnly) { - if (hash is null) - { - throw new ArgumentNullException(nameof(hash)); - } + ArgumentNullException.ThrowIfNull(hash); if (!_pruningStrategy.PruningEnabled) { @@ -638,10 +635,7 @@ private void Persist(BlockCommitSet commitSet, WriteFlags writeFlags = WriteFlag private void Persist(TrieNode currentNode, long blockNumber, WriteFlags writeFlags = WriteFlags.None) { _currentBatch ??= _keyValueStore.StartWriteBatch(); - if (currentNode is null) - { - throw new ArgumentNullException(nameof(currentNode)); - } + ArgumentNullException.ThrowIfNull(currentNode); if (currentNode.Keccak is not null) { diff --git a/src/Nethermind/Nethermind.TxPool/Collections/TxDistinctSortedPool.cs b/src/Nethermind/Nethermind.TxPool/Collections/TxDistinctSortedPool.cs index 0e4163fde18..a035dcd6c4d 100644 --- a/src/Nethermind/Nethermind.TxPool/Collections/TxDistinctSortedPool.cs +++ b/src/Nethermind/Nethermind.TxPool/Collections/TxDistinctSortedPool.cs @@ -121,7 +121,7 @@ private void UpdateGroup(Address groupKey, Account groupValue, EnhancedSortedSet [MethodImpl(MethodImplOptions.Synchronized)] public void UpdateGroup(Address groupKey, Account groupValue, Func, IEnumerable<(Transaction Tx, UInt256? changedGasBottleneck)>> changingElements) { - if (groupKey is null) throw new ArgumentNullException(nameof(groupKey)); + ArgumentNullException.ThrowIfNull(groupKey); if (_buckets.TryGetValue(groupKey, out EnhancedSortedSet? bucket)) { Debug.Assert(bucket.Count > 0);