Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modernise C# #5607

Merged
merged 1 commit into from
Apr 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Abi/AbiDefinition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Abi/AbiUInt.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public override (object, int) Decode(byte[] data, int position, bool packed)

public override byte[] Encode(object? arg, bool packed)
{
Span<byte> bytes = null;
Span<byte> bytes;
if (arg is UInt256 uint256)
{
bytes = ((BigInteger)uint256).ToBigEndianByteArray();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,7 @@ private UserOperationTxSource UserOperationTxSource
{
get
{
if (_userOperationTxSource is null)
{
_userOperationTxSource = new UserOperationTxSource
_userOperationTxSource ??= new UserOperationTxSource
(
_userOperationTxBuilders,
_userOperationPools,
Expand All @@ -159,7 +157,6 @@ private UserOperationTxSource UserOperationTxSource
_nethermindApi.EngineSigner!,
_logger
);
}

return _userOperationTxSource;
}
Expand All @@ -169,10 +166,7 @@ private IUserOperationBroadcaster UserOperationBroadcaster
{
get
{
if (_userOperationBroadcaster is null)
{
_userOperationBroadcaster = new UserOperationBroadcaster(_logger);
}
_userOperationBroadcaster ??= new UserOperationBroadcaster(_logger);

return _userOperationBroadcaster;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public TxReceipt[] Get(Keccak blockHash)
return receipts;
}

return new TxReceipt[] { };
return Array.Empty<TxReceipt>();
}

public bool CanGetReceiptsByHash(long blockNumber) => true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public AutoCompletionHandler(CliModuleLoader cliModuleLoader)
public string[] GetSuggestions(string text, int index)
{
string[] suggestions = Array.Empty<string>();
if (text.IndexOf('.') == -1)
if (!text.Contains('.'))
{
suggestions = _cliModuleLoader.ModuleNames.OrderBy(x => x).Where(x => x.StartsWith(text)).ToArray();
}
Expand All @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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://"))
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Config/ConfigProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Config/ConfigSourceHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 3 additions & 5 deletions src/Nethermind/Nethermind.Config/JsonConfigSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down Expand Up @@ -98,7 +96,7 @@ private void ApplyConfigValues(string configModule, Dictionary<string, string> i
{
if (!configModule.EndsWith("Config"))
{
configModule = configModule + "Config";
configModule += "Config";
}

_values[configModule] = items;
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Config/StringExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public void Remove(IEnumerable<T> items)
public bool TryGetValue(T key, out T value)
{
// ReSharper disable once InconsistentlySynchronizedField
if (!(_inner is IDictionaryContractDataStoreCollection<T> dictionaryContractDataStoreCollection))
if (_inner is not IDictionaryContractDataStoreCollection<T> dictionaryContractDataStoreCollection)
{
throw new InvalidOperationException("Inner collection is not dictionary based.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public IEnumerable<Transaction> GetTransactions(BlockHeader parent, long gasLimi
{
using (privateKey)
{
bytes = _eciesCipher.Decrypt(privateKey, cipher).Item2;
bytes = _eciesCipher.Decrypt(privateKey, cipher).PlainText;
}
}
else
Expand All @@ -108,7 +108,7 @@ public IEnumerable<Transaction> 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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,7 @@ internal static Address[] ExtractSigners(BlockHeader blockHeader)
throw new Exception(string.Empty);
}

Span<byte> signersData = blockHeader.ExtraData.AsSpan()
.Slice(Clique.ExtraVanityLength, blockHeader.ExtraData.Length - Clique.ExtraSealLength - Clique.ExtraVanityLength);
Span<byte> 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++)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Consensus.Clique/CliqueSealer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Consensus.Clique/SnapshotManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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));
}
Expand Down
3 changes: 1 addition & 2 deletions src/Nethermind/Nethermind.Consensus.Ethash/HintBasedCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion src/Nethermind/Nethermind.Consensus.Ethash/NethDevPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ public Task<IBlockProducer> 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();
Expand Down
5 changes: 1 addition & 4 deletions src/Nethermind/Nethermind.Consensus/MiningConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Consensus/Tracing/Tracer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Core/Bytes32.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
}
}
5 changes: 1 addition & 4 deletions src/Nethermind/Nethermind.Core/Collections/CompactStack.cs
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,7 @@ public CompactStack(ObjectPool<Node>? nodePool = null)

public void Push(T item)
{
if (_head == null)
{
_head = _nodePool.Get();
}
_head ??= _nodePool.Get();

if (_head._count == _head._array.Length)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.");
}
Expand Down Expand Up @@ -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.");
}
Expand All @@ -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.");
}
Expand Down
Loading