Skip to content

Instantly share code, notes, and snippets.

@bjoerntx
Last active January 21, 2022 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjoerntx/fce229f9263bd2744554570cf947ef96 to your computer and use it in GitHub Desktop.
Save bjoerntx/fce229f9263bd2744554570cf947ef96 to your computer and use it in GitHub Desktop.
// checks, if the blockchain is consistent by
// re-generating and comparing the hashes in each block
public bool IsValid(string blockHash = "") {
// check all blocks
int iNumberBlocks = Chain.Count;
// check all blocks until the given, optional hash
if (blockHash != "") {
Block block = Chain.FirstOrDefault(h => h.BlockHash == blockHash);
if (block != null) {
iNumberBlocks = block.Index + 1;
}
}
// loop through all blocks, generate their hashes and compare
for (int i = 1; i < iNumberBlocks; i++) {
Block currentBlock = Chain[i];
Block previousBlock = Chain[i - 1];
if (currentBlock.BlockHash != currentBlock.GenerateBlockHash())
return false;
if (currentBlock.PreviousBlockHash != previousBlock.BlockHash)
return false;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment