Skip to content

Commit

Permalink
Review fixes
Browse files Browse the repository at this point in the history
1) throw concrete exceptions
2) Naming
3) Unused removal
4) Function simplified
5) standarizing is all over the solution
  • Loading branch information
OlegJakushkin committed Nov 7, 2022
1 parent 1b08c64 commit 4400fd2
Show file tree
Hide file tree
Showing 259 changed files with 723 additions and 724 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ private void CallAndRestore(
bool treatBlockHeaderAsParentBlock,
ITxTracer tracer)
{
if (transaction.SenderAddress == null)
if (transaction.SenderAddress is null)
{
transaction.SenderAddress = Address.SystemUser;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,8 +262,8 @@ protected virtual TestCase<T> BuildTestCase<T>(IComparer<T> keyComparer = null,
DataContract = dataContract,
BlockTree = blockTree,
ReceiptFinder = receiptsFinder,
ContractDataStore = keyComparer == null
? (IContractDataStore<T>)new ContractDataStore<T>(new HashSetContractDataStoreCollection<T>(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance)
ContractDataStore = keyComparer is null
? new ContractDataStore<T>(new HashSetContractDataStoreCollection<T>(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance)
: new DictionaryContractDataStore<T>(new SortedListContractDataStoreCollection<T>(keyComparer, valueComparer), dataContract, blockTree, receiptsFinder, LimboLogs.Instance)
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,8 @@ private TestCase<T> BuildTestCase<T>(ILocalDataSource<IEnumerable<T>> localDataS
DataContract = dataContract,
BlockTree = blockTree,
ReceiptFinder = receiptsFinder,
ContractDataStore = keyComparer == null
? (IContractDataStore<T>)new ContractDataStoreWithLocalData<T>(new HashSetContractDataStoreCollection<T>(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource)
ContractDataStore = keyComparer is null
? new ContractDataStoreWithLocalData<T>(new HashSetContractDataStoreCollection<T>(), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource)
: new DictionaryContractDataStore<T>(new SortedListContractDataStoreCollection<T>(keyComparer, valueComparer), dataContract, blockTree, receiptsFinder, LimboLogs.Instance, localDataSource)
};
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ public async Task whitelist_should_return_correctly_with_local_storage([Values(t

if (!await semaphoreSlim.WaitAsync(100))
{
if (chain.LocalDataSource.Data == null)
if (chain.LocalDataSource.Data is null)
{
Assert.Fail("Local file rule storage has not been loaded.");
}
Expand Down Expand Up @@ -207,7 +207,7 @@ public async Task priority_should_return_correctly_with_local_storage([Values(tr

if (!await semaphoreSlim.WaitAsync(100))
{
if (chain.LocalDataSource.Data == null)
if (chain.LocalDataSource.Data is null)
{
Assert.Fail("Local file rule storage has not been loaded.");
}
Expand Down Expand Up @@ -253,7 +253,7 @@ public async Task mingas_should_return_correctly_with_local_storage([Values(true

if (!await semaphoreSlim.WaitAsync(100))
{
if (chain.LocalDataSource.Data == null)
if (chain.LocalDataSource.Data is null)
{
Assert.Fail("Local file rule storage has not been loaded.");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ public void DeleteChainSlice_throws_when_endNumber_other_than_bestKnownNumber()
[TestCase(10, 20, 15, 16, false, TestName = "Allow deletion.")]
public void DeleteChainSlice_throws_when_corrupted_blocks_not_found(long? head, long bestKnown, long start, long? corruptedBlock, bool throws)
{
_innerBlockTree.Head.Returns(head == null ? null : Build.A.Block.WithHeader(Build.A.BlockHeader.WithNumber(head.Value).TestObject).TestObject);
_innerBlockTree.Head.Returns(head is null ? null : Build.A.Block.WithHeader(Build.A.BlockHeader.WithNumber(head.Value).TestObject).TestObject);
_innerBlockTree.BestKnownNumber.Returns(bestKnown);
_innerBlockTree.FindHeader(Arg.Any<long>(), Arg.Any<BlockTreeLookupOptions>())
.Returns(c => c.Arg<long>() == corruptedBlock ? null : Build.A.BlockHeader.WithNumber(c.Arg<long>()).TestObject);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ public void When_gas_used_is_negative()
public void When_total_difficulty_0_or_null_we_should_skip_total_difficulty_validation(long? totalDifficulty)
{
_block.Header.Difficulty = 1;
_block.Header.TotalDifficulty = totalDifficulty == null ? null : (UInt256)totalDifficulty;
_block.Header.TotalDifficulty = totalDifficulty is null ? null : (UInt256)totalDifficulty;
_block.Header.SealEngineType = SealEngineType.None;
_block.Header.Hash = _block.CalculateHash();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,10 @@ public async Task Accept(IBlockTreeVisitor visitor, CancellationToken cancellati
// if we delete blocks during the process then the number of blocks at this level will be falling and we need to adjust the index
Keccak hash = level!.BlockInfos[blockIndex - (numberOfBlocksAtThisLevel - level.BlockInfos.Length)].BlockHash;
Block block = FindBlock(hash, BlockTreeLookupOptions.None);
if (block == null)
if (block is null)
{
BlockHeader header = FindHeader(hash, BlockTreeLookupOptions.None);
if (header == null)
if (header is null)
{
if (await VisitMissing(visitor, hash, cancellationToken)) break;
}
Expand Down
8 changes: 4 additions & 4 deletions src/Nethermind/Nethermind.Blockchain/BlockTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -1349,7 +1349,7 @@ public void UpdateMainChain(IReadOnlyList<Block> blocks, bool wereProcessed, boo

public void UpdateBeaconMainChain(BlockInfo[]? blockInfos, long clearBeaconMainChainStartPoint)
{
if (blockInfos == null || blockInfos.Length == 0)
if (blockInfos is null || blockInfos.Length == 0)
return;

using BatchWrite batch = _chainLevelInfoRepository.StartBatch();
Expand Down Expand Up @@ -1502,7 +1502,7 @@ private bool HeadImprovementRequirementsSatisfied(BlockHeader header)
bool preMergeImprovementRequirementSatisfied = header.TotalDifficulty > (Head?.TotalDifficulty ?? 0)
&& (header.TotalDifficulty <
_specProvider.TerminalTotalDifficulty
|| _specProvider.TerminalTotalDifficulty == null);
|| _specProvider.TerminalTotalDifficulty is null);

// after the merge, we will accept only the blocks with Difficulty = 0. However, during the transition process
// we can have terminal PoW blocks with Difficulty > 0. That is why we accept everything greater or equal
Expand All @@ -1515,7 +1515,7 @@ private bool HeadImprovementRequirementsSatisfied(BlockHeader header)

private bool BestSuggestedImprovementRequirementsSatisfied(BlockHeader header)
{
if (BestSuggestedHeader == null) return true;
if (BestSuggestedHeader is null) return true;

bool reachedTtd = header.IsPostTTD(_specProvider);
bool isPostMerge = header.IsPoS();
Expand Down Expand Up @@ -1811,7 +1811,7 @@ BlockHeader GetParentHeader(BlockHeader current) =>
while (stack.TryPop(out (BlockHeader child, ChainLevelInfo level, BlockInfo blockInfo) item))
{
item.child.TotalDifficulty = current.TotalDifficulty + item.child.Difficulty;
if (item.level == null)
if (item.level is null)
{
item.blockInfo = new(item.child.Hash, item.child.TotalDifficulty.Value);
item.level = new(false, item.blockInfo);
Expand Down
6 changes: 3 additions & 3 deletions src/Nethermind/Nethermind.Blockchain/BlockhashProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number)
bool isFastSyncSearch = false;

BlockHeader header = _blockTree.FindParentHeader(currentBlock, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (header == null)
if (header is null)
{
throw new InvalidDataException("Parent header cannot be found when executing BLOCKHASH operation");
}
Expand All @@ -61,7 +61,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number)
}

header = _blockTree.FindParentHeader(header, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (header == null)
if (header is null)
{
throw new InvalidDataException("Parent header cannot be found when executing BLOCKHASH operation");
}
Expand All @@ -72,7 +72,7 @@ public Keccak GetBlockhash(BlockHeader currentBlock, in long number)
{
BlockHeader currentHeader = header;
header = _blockTree.FindHeader(number, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (header == null)
if (header is null)
{
isFastSyncSearch = true;
header = currentHeader;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public override AbiDefinition ReadJson(
{
string name = definitionToken[_nameTokenName]?.Value<string>();
JToken typeToken = definitionToken[_typeTokenName];
if (typeToken == null)
if (typeToken is null)
{
continue;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ private void SetupWatcher(string filePath)
catch (PathTooLongException) { }
catch (NotSupportedException) { }

if (fileInfo == null)
if (fileInfo is null)
{
// file name is not valid
if (_logger.IsError) _logger.Error($"Invalid file path to watch: {filePath}.");
Expand Down
16 changes: 8 additions & 8 deletions src/Nethermind/Nethermind.Blockchain/Find/IBlockFinder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,11 +70,11 @@ public interface IBlockFinder

public Block? FindLatestBlock() => FindHeadBlock();

public Block? FindPendingBlock() => PendingHash == null ? null : FindBlock(PendingHash, BlockTreeLookupOptions.None);
public Block? FindPendingBlock() => PendingHash is null ? null : FindBlock(PendingHash, BlockTreeLookupOptions.None);

public Block? FindFinalizedBlock() => FinalizedHash == null ? null : FindBlock(FinalizedHash, BlockTreeLookupOptions.None);
public Block? FindFinalizedBlock() => FinalizedHash is null ? null : FindBlock(FinalizedHash, BlockTreeLookupOptions.None);

public Block? FindSafeBlock() => SafeHash == null ? null : FindBlock(SafeHash, BlockTreeLookupOptions.None);
public Block? FindSafeBlock() => SafeHash is null ? null : FindBlock(SafeHash, BlockTreeLookupOptions.None);

public BlockHeader? FindHeader(Keccak blockHash) => FindHeader(blockHash, BlockTreeLookupOptions.None);

Expand All @@ -86,17 +86,17 @@ public interface IBlockFinder

public BlockHeader? FindLatestHeader() => Head?.Header;

public BlockHeader? FindPendingHeader() => PendingHash == null ? null : FindHeader(PendingHash, BlockTreeLookupOptions.None);
public BlockHeader? FindPendingHeader() => PendingHash is null ? null : FindHeader(PendingHash, BlockTreeLookupOptions.None);

public BlockHeader? FindFinalizedHeader() => FinalizedHash == null ? null : FindHeader(FinalizedHash, BlockTreeLookupOptions.None);
public BlockHeader? FindFinalizedHeader() => FinalizedHash is null ? null : FindHeader(FinalizedHash, BlockTreeLookupOptions.None);

public BlockHeader? FindSafeHeader() => SafeHash == null ? null : FindHeader(SafeHash, BlockTreeLookupOptions.None);
public BlockHeader? FindSafeHeader() => SafeHash is null ? null : FindHeader(SafeHash, BlockTreeLookupOptions.None);

BlockHeader FindBestSuggestedHeader();

public Block? FindBlock(BlockParameter? blockParameter, bool headLimit = false)
{
if (blockParameter == null)
if (blockParameter is null)
{
return FindLatestBlock();
}
Expand Down Expand Up @@ -124,7 +124,7 @@ public interface IBlockFinder

public BlockHeader? FindHeader(BlockParameter? blockParameter, bool headLimit = false)
{
if (blockParameter == null)
if (blockParameter is null)
{
return FindLatestHeader();
}
Expand Down
4 changes: 2 additions & 2 deletions src/Nethermind/Nethermind.Blockchain/ReadOnlyBlockTree.cs
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ public event EventHandler<BlockEventArgs> NewHeadBlock
public int DeleteChainSlice(in long startNumber, long? endNumber = null)
{
var bestKnownNumber = BestKnownNumber;
if (endNumber == null || endNumber == bestKnownNumber)
if (endNumber is null || endNumber == bestKnownNumber)
{
if (Head?.Number > 0)
{
Expand All @@ -181,7 +181,7 @@ IEnumerable<BlockHeader> GetPotentiallyCorruptedBlocks(long start)
}
}

if (GetPotentiallyCorruptedBlocks(startNumber).Any(b => b == null))
if (GetPotentiallyCorruptedBlocks(startNumber).Any(b => b is null))
{
return _wrapped.DeleteChainSlice(startNumber);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,14 @@ public PersistentReceiptStorage(IColumnsDb<ReceiptsColumns> receiptsDb, ISpecPro
_transactionDb = _database.GetColumnDb(ReceiptsColumns.Transactions);

byte[] lowestBytes = _database.Get(Keccak.Zero);
_lowestInsertedReceiptBlock = lowestBytes == null ? (long?)null : new RlpStream(lowestBytes).DecodeLong();
_lowestInsertedReceiptBlock = lowestBytes is null ? (long?)null : new RlpStream(lowestBytes).DecodeLong();
_migratedBlockNumber = Get(MigrationBlockNumberKey, long.MaxValue);
}

public Keccak FindBlockHash(Keccak txHash)
{
var blockHashData = _transactionDb.Get(txHash);
return blockHashData == null ? FindReceiptObsolete(txHash)?.BlockHash : new Keccak(blockHashData);
return blockHashData is null ? FindReceiptObsolete(txHash)?.BlockHash : new Keccak(blockHashData);
}

// Find receipt stored with old - obsolete format.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public ReceiptsIterator(TxReceipt[] receipts)

public bool TryGetNext(out TxReceiptStructRef current)
{
if (_receipts == null)
if (_receipts is null)
{
if (_decoderContext.Position < _length)
{
Expand Down Expand Up @@ -87,7 +87,7 @@ public void Reset()

public void Dispose()
{
if (_receipts == null && !_decoderContext.Data.IsEmpty)
if (_receipts is null && !_decoderContext.Data.IsEmpty)
{
_blocksDb?.DangerousReleaseMemory(_decoderContext.Data);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ public ReceiptsRecoveryResult TryRecover(Block block, TxReceipt[] receipts, bool
return ReceiptsRecoveryResult.Fail;
}

public bool NeedRecover(TxReceipt[] receipts, bool forceRecoverSender = true) => receipts?.Length > 0 && (receipts[0].BlockHash == null || (forceRecoverSender && receipts[0].Sender == null));
public bool NeedRecover(TxReceipt[] receipts, bool forceRecoverSender = true) => receipts?.Length > 0 && (receipts[0].BlockHash is null || (forceRecoverSender && receipts[0].Sender is null));

private void RecoverReceiptData(IReleaseSpec releaseSpec, TxReceipt receipt, Block block, Transaction transaction, int transactionIndex, long gasUsedBefore, bool force)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public interface ISyncConfig : IConfig
UInt256 PivotTotalDifficultyParsed => UInt256.Parse(PivotTotalDifficulty ?? "0");

[ConfigItem(DisabledForCli = true, HiddenFromDocs = true)]
Keccak PivotHashParsed => PivotHash == null ? null : new Keccak(Bytes.FromHexString(PivotHash));
Keccak PivotHashParsed => PivotHash is null ? null : new Keccak(Bytes.FromHexString(PivotHash));

[ConfigItem(Description = "[EXPERIMENTAL] Defines the earliest body downloaded in fast sync when DownloadBodiesInFastSync is enabled. Actual values used will be Math.Max(1, Math.Min(PivotNumber, AncientBodiesBarrier))", DefaultValue = "0")]
public long AncientBodiesBarrier { get; set; }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ Task<LevelVisitOutcome> IBlockTreeVisitor.VisitLevelStart(ChainLevelInfo chainLe
return Task.FromResult(LevelVisitOutcome.DeleteLevel);
}

if (chainLevelInfo == null)
if (chainLevelInfo is null)
{
_gapStart = _currentLevelNumber;
}
Expand Down Expand Up @@ -255,8 +255,8 @@ private bool CanSuggestBlocks(Block block)
if (block?.ParentHash != null)
{
BlockHeader? parentHeader = _blockTree.FindParentHeader(block.Header, BlockTreeLookupOptions.TotalDifficultyNotNeeded);
if (parentHeader == null || parentHeader.StateRoot == null ||
_stateDb.Get(parentHeader.StateRoot) == null)
if (parentHeader is null || parentHeader.StateRoot is null ||
_stateDb.Get(parentHeader.StateRoot) is null)
return false;
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public CliFunctionAttribute(string objectName, string functionName)

public override string ToString()
{
return $"{ObjectName}.{FunctionName}{(Description == null ? "" : $" {Description}")}";
return $"{ObjectName}.{FunctionName}{(Description is null ? "" : $" {Description}")}";
}
}
}
6 changes: 3 additions & 3 deletions src/Nethermind/Nethermind.Cli/Modules/CliModuleLoader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public CliModuleLoader(ICliEngine engine, IJsonRpcClient client, ICliConsole cli
/// <exception cref="ArgumentNullException"></exception>
private static Delegate CreateDelegate(MethodInfo methodInfo, CliModuleBase module)
{
if (methodInfo == null)
if (methodInfo is null)
{
throw new ArgumentNullException(nameof(methodInfo));
}
Expand All @@ -78,7 +78,7 @@ private static Delegate CreateDelegate(MethodInfo methodInfo, CliModuleBase modu
private void LoadModule(CliModuleBase module)
{
CliModuleAttribute? cliModuleAttribute = module.GetType().GetCustomAttribute<CliModuleAttribute>();
if (cliModuleAttribute == null)
if (cliModuleAttribute is null)
{
_cliConsole.WriteErrorLine(
$"Could not load module {module.GetType().Name} bacause of a missing {nameof(CliModuleAttribute)}.");
Expand All @@ -100,7 +100,7 @@ private void LoadModule(CliModuleBase module)
string? objectName = cliProperty?.ObjectName ?? cliFunction?.ObjectName;
string? itemName = cliProperty?.PropertyName ?? cliFunction?.FunctionName;

if (objectName == null)
if (objectName is null)
{
throw new InvalidDataException($"Method {methodInfo.Name} of {module.GetType().Name} should be decorated with one of {nameof(CliPropertyAttribute)} or {nameof(CliFunctionAttribute)}");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public CliPropertyAttribute(string objectName, string propertyName)

public override string ToString()
{
return $"{ObjectName}.{PropertyName}{(Description == null ? "" : $" {Description}")}";
return $"{ObjectName}.{PropertyName}{(Description is null ? "" : $" {Description}")}";
}
}
}
Loading

0 comments on commit 4400fd2

Please sign in to comment.