Skip to content

Commit

Permalink
Make methods static and/or readonly (and others) (#6376)
Browse files Browse the repository at this point in the history
* Make methods static and/or readonly

* Hashtable Contains+Add -> Add

* Hashtable Contains+Remove -> Remove

* Span Fill(0) -> Clear()

* Fix Ethereum tests

* Whitespace

* Fix

* Fix benchmarks

* Remove unneeded methods
  • Loading branch information
benaadams authored Dec 15, 2023
1 parent 9bed546 commit b8b0a8e
Show file tree
Hide file tree
Showing 171 changed files with 360 additions and 369 deletions.
2 changes: 1 addition & 1 deletion src/Nethermind/Ethereum.PoW.Test/EthashTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public void Test(EthashTest test)
Assert.That(Bytes.AreEqual(test.Result.Bytes, resultHalfTest), Is.True, "half test");

// here we confirm that the whole mix hash calculation is fine
(byte[] mixHash, ValueHash256 result, bool success) = ethash.Hashimoto((ulong)test.FullSize, cache, headerHash, blockHeader.MixHash, test.Nonce);
(byte[] mixHash, ValueHash256 result, bool success) = Ethash.Hashimoto((ulong)test.FullSize, cache, headerHash, blockHeader.MixHash, test.Nonce);
Assert.That(Bytes.AreEqual(mixHash, test.MixHash.Bytes), Is.True, "mix hash");
Assert.That(Bytes.AreEqual(result.Bytes, test.Result.Bytes), Is.True, "result");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public class AbiDefinitionParserTests
public void Can_load_contract(Type contractType)
{
var parser = new AbiDefinitionParser();
var json = parser.LoadContract(contractType);
var json = AbiDefinitionParser.LoadContract(contractType);
var contract = parser.Parse(json);
var serialized = parser.Serialize(contract);
var serialized = AbiDefinitionParser.Serialize(contract);
JToken.Parse(serialized).Should().ContainSubtree(json);
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Abi/AbiTuple.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public override (object, int) Decode(byte[] data, int position, bool packed)

public override byte[] Encode(object? arg, bool packed)
{
IEnumerable<object?> GetEnumerable(ITuple tuple)
static IEnumerable<object?> GetEnumerable(ITuple tuple)
{
for (int i = 0; i < tuple.Length; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ protected override BlockProcessor CreateBlockProcessor()
AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple<UserOperationAbi>()));

var parser = new AbiDefinitionParser();
var json = parser.LoadContract(typeof(EntryPoint));
var json = AbiDefinitionParser.LoadContract(typeof(EntryPoint));
EntryPointContractAbi = parser.Parse(json);

foreach (Address entryPoint in entryPointContractAddresses)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private AbiDefinition LoadContract(Type contractType)
AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple<UserOperationAbi>()));

var parser = new AbiDefinitionParser();
var json = parser.LoadContract(contractType);
var json = AbiDefinitionParser.LoadContract(contractType);
return parser.Parse(json);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -386,12 +386,12 @@ public Task<IBlockProducer> InitBlockProducer(IConsensusPlugin consensusPlugin)
public bool BundleMiningEnabled => _accountAbstractionConfig.Enabled && (_nethermindApi.Config<IInitConfig>().IsMining || _nethermindApi.Config<IMiningConfig>().Enabled);
public bool Enabled => BundleMiningEnabled && !MevPluginEnabled; // IConsensusWrapperPlugin.Enabled

private AbiDefinition LoadEntryPointContract()
private static AbiDefinition LoadEntryPointContract()
{
AbiParameterConverter.RegisterFactory(new AbiTypeFactory(new AbiTuple<UserOperationAbi>()));

AbiDefinitionParser parser = new();
string json = parser.LoadContract(typeof(EntryPoint));
string json = AbiDefinitionParser.LoadContract(typeof(EntryPoint));
return parser.Parse(json);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ public int GetLength(UserOperationsMessage message, out int contentLength)
return Rlp.LengthOfSequence(contentLength);
}

private UserOperationWithEntryPoint[] DeserializeUOps(NettyRlpStream rlpStream)
private static UserOperationWithEntryPoint[] DeserializeUOps(NettyRlpStream rlpStream)
{
return Rlp.DecodeArray<UserOperationWithEntryPoint>(rlpStream);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ protected void UpdateUserOperationMaps(object source, EventArgs args)
* @param dividend: Dividend, or numerator of the division.
* @param divisor: Divisor, or denominator of the division.
*/
private uint FloorDivision(uint dividend, uint divisor)
private static uint FloorDivision(uint dividend, uint divisor)
{
if (divisor == 0) throw new Exception("PaymasterThrottler: Divisor cannot be == 0");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ public IEnumerable<Transaction> GetTransactions(BlockHeader parent, long gasLimi
}
}

private UInt256 CalculateUserOperationPremiumGasPrice(UserOperation op, UInt256 baseFeePerGas)
private static UInt256 CalculateUserOperationPremiumGasPrice(UserOperation op, UInt256 baseFeePerGas)
{
return UInt256.Min(op.MaxPriorityFeePerGas, op.MaxFeePerGas - baseFeePerGas);
}
Expand Down
3 changes: 1 addition & 2 deletions src/Nethermind/Nethermind.Analytics/SupplyVerifier.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,8 @@ public bool ShouldVisit(Hash256 nextNode)
_logger.Warn($"Ignore count leak -> {_ignoreThisOne.Count}");
}

if (_ignoreThisOne.Contains(nextNode))
if (_ignoreThisOne.Remove(nextNode))
{
_ignoreThisOne.Remove(nextNode);
return false;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ private ReceiptsIterator CreateIterator(TxReceipt[] receipts, Block block)
false
);

ReceiptsIterator iterator = new ReceiptsIterator(span, blockDb, () => recovery.CreateRecoveryContext(new ReceiptRecoveryBlock(block)), _decoder.GetRefDecoder(span));
ReceiptsIterator iterator = new ReceiptsIterator(span, blockDb, () => recovery.CreateRecoveryContext(new ReceiptRecoveryBlock(block)), ReceiptArrayStorageDecoder.GetRefDecoder(span));
return iterator;
}
}
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Blockchain/Blocks/BlockStore.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public void Delete(long blockNumber, Hash256 blockHash)
memoryOwner = _blockDb.GetOwnedMemory(blockHash.Bytes);
}

return _blockDecoder.DecodeToReceiptRecoveryBlock(memoryOwner, memoryOwner?.Memory ?? Memory<byte>.Empty, RlpBehaviors.None);
return BlockDecoder.DecodeToReceiptRecoveryBlock(memoryOwner, memoryOwner?.Memory ?? Memory<byte>.Empty, RlpBehaviors.None);
}

public void Cache(Block block)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ protected bool TryCall(BlockHeader header, string functionName, Address sender,
/// Creates <see cref="Address.SystemUser"/> account if its not in current state.
/// </summary>
/// <param name="stateProvider">State provider.</param>
protected void EnsureSystemAccount(IWorldState stateProvider)
protected static void EnsureSystemAccount(IWorldState stateProvider)
{
if (!stateProvider.AccountExists(Address.SystemUser))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public ConstantContract(Contract contract, IReadOnlyTxProcessorSource readOnlyTx

public override object[] Call(CallInfo callInfo)
{
Hash256 GetState(BlockHeader parentHeader) => parentHeader?.StateRoot ?? Keccak.EmptyTreeHash;
static Hash256 GetState(BlockHeader parentHeader) => parentHeader?.StateRoot ?? Keccak.EmptyTreeHash;

lock (_readOnlyTxProcessorSource)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@ public void RegisterAbiTypeFactory(IAbiTypeFactory abiTypeFactory)
_abiTypeFactories.Add(abiTypeFactory);
}

public string LoadContract(Type type)
public static string LoadContract(Type type)
{
using var reader = new StreamReader(LoadResource(type));
return reader.ReadToEnd();
}

public string Serialize(AbiDefinition contract)
public static string Serialize(AbiDefinition contract)
{
return JsonSerializer.Serialize(contract, SourceGenerationContext.Default.AbiDefinition);
}
Expand Down
1 change: 0 additions & 1 deletion src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ public BlockHeader? LowestInsertedBeaconHeader
public Block Head => _wrapped.Head;
public void MarkChainAsProcessed(IReadOnlyList<Block> blocks) => throw new InvalidOperationException($"{nameof(ReadOnlyBlockTree)} does not expect {nameof(MarkChainAsProcessed)} calls");
public (BlockInfo Info, ChainLevelInfo Level) GetInfo(long number, Hash256 blockHash) => _wrapped.GetInfo(number, blockHash);
public UInt256? UpdateTotalDifficulty(Block block, UInt256 totalDifficulty) => throw new InvalidOperationException();
public bool CanAcceptNewBlocks { get; } = false;

public async Task Accept(IBlockTreeVisitor blockTreeVisitor, CancellationToken cancellationToken)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ public long? LowestInsertedReceiptBlockNumber

public long MigratedBlockNumber { get; set; } = 0;

public event EventHandler<ReceiptsEventArgs> ReceiptsInserted
{
add { }
remove { }
}

public bool HasBlock(long blockNumber, Hash256 hash)
{
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ public bool TryGetReceiptsIterator(long blockNumber, Hash256 blockHash, out Rece

Func<IReceiptsRecovery.IRecoveryContext?> recoveryContextFactory = () => null;

if (_storageDecoder.IsCompactEncoding(receiptsData))
if (ReceiptArrayStorageDecoder.IsCompactEncoding(receiptsData))
{
recoveryContextFactory = () =>
{
Expand All @@ -248,7 +248,7 @@ public bool TryGetReceiptsIterator(long blockNumber, Hash256 blockHash, out Rece
};
}

IReceiptRefDecoder refDecoder = _storageDecoder.GetRefDecoder(receiptsData);
IReceiptRefDecoder refDecoder = ReceiptArrayStorageDecoder.GetRefDecoder(receiptsData);

iterator = result ? new ReceiptsIterator(receiptsData, _blocksDb, recoveryContextFactory, refDecoder) : new ReceiptsIterator();
return result;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public void RecoverIfNeeded(ref TxReceiptStructRef current)
_recoveryContextConfigured = true;
}

public void Dispose()
public readonly void Dispose()
{
if (_receipts is null && !_decoderContext.Data.IsEmpty)
{
Expand All @@ -113,16 +113,16 @@ public void Dispose()
_recoveryContext?.Dispose();
}

public LogEntriesIterator IterateLogs(TxReceiptStructRef receipt)
public readonly LogEntriesIterator IterateLogs(TxReceiptStructRef receipt)
{
return receipt.Logs is null ? new LogEntriesIterator(receipt.LogsRlp, _receiptRefDecoder) : new LogEntriesIterator(receipt.Logs);
}

public Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext)
public readonly Hash256[] DecodeTopics(Rlp.ValueDecoderContext valueDecoderContext)
{
return _receiptRefDecoder.DecodeTopics(valueDecoderContext);
}

public bool CanDecodeBloom => _receiptRefDecoder == null || _receiptRefDecoder.CanDecodeBloom;
public readonly bool CanDecodeBloom => _receiptRefDecoder == null || _receiptRefDecoder.CanDecodeBloom;
}
}
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Cli/Console/CliConsole.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public CliConsole()
System.Console.WriteLine();
}

protected Terminal GetTerminal()
protected static Terminal GetTerminal()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Expand All @@ -60,7 +60,7 @@ protected Terminal GetTerminal()
return Terminal.Unknown;
}

protected Terminal PrepareConsoleForTerminal()
protected static Terminal PrepareConsoleForTerminal()
{
_terminal = GetTerminal();
if (_terminal != Terminal.Powershell)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ public ColorfulCliConsole(ColorScheme colorScheme)
Colorful.Console.WriteLine();
}

private Color GetColor(Color defaultColor)
private static Color GetColor(Color defaultColor)
{
return _terminal == Terminal.LinuxBash ? _colorScheme.Text : defaultColor;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Cli/Modules/NodeCliModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace Nethermind.Cli.Modules
public class NodeCliModule : CliModuleBase
{
[CliFunction("node", "setNodeKey")]
public string SetNodeKey(string key)
public static string SetNodeKey(string key)
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory!, "node.key.plain");
File.WriteAllBytes("node.key.plain", new PrivateKey(Bytes.FromHexString(key)).KeyBytes);
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Cli/Modules/SystemCliModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ namespace Nethermind.Cli.Modules
public class SystemCliModule : CliModuleBase
{
[CliFunction("system", "getVariable")]
public string? GetVariable(string name, string defaultValue)
public static string? GetVariable(string name, string defaultValue)
{
var value = Environment.GetEnvironmentVariable(name.ToUpperInvariant());
return string.IsNullOrWhiteSpace(value) ? value : defaultValue;
}

[CliProperty("system", "memory")]
public string Memory(string name, string defaultValue)
public static string Memory(string name, string defaultValue)
{
return $"Allocated: {GC.GetTotalMemory(false)}, GC0: {GC.CollectionCount(0)}, GC1: {GC.CollectionCount(1)}, GC2: {GC.CollectionCount(2)}";
}
Expand Down
2 changes: 1 addition & 1 deletion src/Nethermind/Nethermind.Cli/Modules/Web3CliModule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,6 @@ public Web3CliModule(ICliEngine cliEngine, INodeManager nodeManager) : base(cliE
public JsValue ToDecimal(string hex) => Engine.Execute(hex);

[CliFunction("web3", "abi")]
public string Abi(string name) => new AbiSignature(name).Address.ToHexString();
public static string Abi(string name) => new AbiSignature(name).Address.ToHexString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ private void ValidateStepDurations(IDictionary<long, long> stepDurations)
}
}

private IList<StepDurationInfo> CreateStepDurations(IDictionary<long, long> stepDurations)
private static IList<StepDurationInfo> CreateStepDurations(IDictionary<long, long> stepDurations)
{
StepDurationInfo[] result = new StepDurationInfo[stepDurations.Count];
KeyValuePair<long, long> firstStep = stepDurations.First();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ public static Destination GetTransactionKey(Transaction tx)
return new Destination(tx.To, fnSignature, UInt256.Zero);
}

public bool Equals(Destination x, Destination y) => Equals(x.Target, y.Target) && Equals(x.FnSignature, y.FnSignature);
public readonly bool Equals(Destination x, Destination y) => Equals(x.Target, y.Target) && Equals(x.FnSignature, y.FnSignature);

public int GetHashCode(Destination obj) => HashCode.Combine(obj.Target, obj.FnSignature);
public readonly int GetHashCode(Destination obj) => HashCode.Combine(obj.Target, obj.FnSignature);

public override string ToString() => $"{Target}.{FnSignature.ToHexString()}={Value}@{Source}.{BlockNumber}";
public override readonly string ToString() => $"{Target}.{FnSignature.ToHexString()}={Value}@{Source}.{BlockNumber}";
}

public class ValueDestinationMethodComparer : IComparer<Destination>
Expand Down Expand Up @@ -93,7 +93,7 @@ public int Compare(Destination x, Destination y)
// if same method, we want to treat destinations as same - to be unique
int targetComparison = Comparer<Address>.Default.Compare(x.Target, y.Target);
if (targetComparison != 0) return targetComparison;
return Bytes.Comparer.Compare(x.FnSignature, y.FnSignature);
return Bytes.BytesComparer.Compare(x.FnSignature, y.FnSignature);
}

public bool Equals(Destination x, Destination y) =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public Address[] DecodeAddresses(byte[] data)
return (Address[])objects[0];
}

private Destination DecodeDestination(LogEntry log, BlockHeader blockHeader) =>
private static Destination DecodeDestination(LogEntry log, BlockHeader blockHeader) =>
new Destination(
new Address(log.Topics[1]),
log.Topics[2].Bytes.Slice(0, 4).ToArray(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ public BlockReward[] CalculateRewards(Block block)
}


private BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract)
private static BlockReward[] CalculateRewardsWithContract(Block block, IRewardContract contract)
{
(Address[] beneficieries, ushort[] kinds) GetBeneficiaries()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public BlockReward[] CalculateRewards(Block block)
return new[] { new BlockReward(block.Beneficiary, blockReward.Reward) };
}

private IList<BlockRewardInfo> CreateBlockRewards(IDictionary<long, UInt256>? blockRewards)
private static IList<BlockRewardInfo> CreateBlockRewards(IDictionary<long, UInt256>? blockRewards)
{
List<BlockRewardInfo> blockRewardInfos = new();
if (blockRewards?.Count > 0)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ public AcceptTxResult IsAllowed(Transaction tx, BlockHeader parentHeader)
private ITransactionPermissionContract? GetVersionedContract(BlockHeader blockHeader)
=> _contract.ResolveVersion(blockHeader);

private ITransactionPermissionContract.TxPermissions GetTxType(Transaction tx, bool contractExists) =>
private static ITransactionPermissionContract.TxPermissions GetTxType(Transaction tx, bool contractExists) =>
tx.IsContractCreation
? ITransactionPermissionContract.TxPermissions.Create
: contractExists
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public void Encode(RlpStream rlpStream, PendingValidators item, RlpBehaviors rlp
public int GetLength(PendingValidators item, RlpBehaviors rlpBehaviors) =>
item is null ? 1 : Rlp.LengthOfSequence(GetContentLength(item, rlpBehaviors).Total);

private (int Total, int Addresses) GetContentLength(PendingValidators item, RlpBehaviors rlpBehaviors)
private static (int Total, int Addresses) GetContentLength(PendingValidators item, RlpBehaviors rlpBehaviors)
{
int contentLength = Rlp.LengthOf(item.BlockNumber)
+ Rlp.LengthOf(item.BlockHash)
Expand All @@ -84,6 +84,6 @@ public int GetLength(PendingValidators item, RlpBehaviors rlpBehaviors) =>
return (contentLength, addressesLength);
}

private int GetAddressesLength(Address[] addresses) => addresses.Sum(Rlp.LengthOf);
private static int GetAddressesLength(Address[] addresses) => addresses.Sum(Rlp.LengthOf);
}
}
Loading

0 comments on commit b8b0a8e

Please sign in to comment.