Skip to content

Commit

Permalink
Restore the GetDeterministicByteArrays method to facilitate problem d…
Browse files Browse the repository at this point in the history
…iagnosis
  • Loading branch information
chopin-fan committed Jul 23, 2024
1 parent 252338a commit 698562e
Showing 1 changed file with 17 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -149,27 +149,33 @@ protected virtual Task CleanUpReturnSetCollectionAsync(BlockHeader blockHeader,
private Hash CalculateWorldStateMerkleTreeRoot(BlockStateSet blockStateSet)
{
Logger.LogTrace("Start world state calculation.");
Hash merkleTreeRootOfWorldState;
var byteArrays = GetDeterministicByteArrays(blockStateSet);
using var hashAlgorithm = SHA256.Create();
foreach (var bytes in byteArrays)
using (var hashAlgorithm = SHA256.Create())
{
hashAlgorithm.TransformBlock(bytes, 0, bytes.Length, null, 0);
foreach (var bytes in byteArrays) hashAlgorithm.TransformBlock(bytes, 0, bytes.Length, null, 0);

hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);
merkleTreeRootOfWorldState = Hash.LoadFromByteArray(hashAlgorithm.Hash);
}

hashAlgorithm.TransformFinalBlock(new byte[0], 0, 0);
var merkleTreeRootOfWorldState = Hash.LoadFromByteArray(hashAlgorithm.Hash);

return merkleTreeRootOfWorldState;
}

private IEnumerable<byte[]> GetDeterministicByteArrays(BlockStateSet blockStateSet)
{
var sortedKeys = new SortedSet<string>(blockStateSet.Changes.Keys.Concat(blockStateSet.Deletes));
foreach (var k in sortedKeys)
var keys = blockStateSet.Changes.Keys;
foreach (var k in new SortedSet<string>(keys))
{
yield return Encoding.UTF8.GetBytes(k);
yield return blockStateSet.Changes[k].ToByteArray();
}

keys = blockStateSet.Deletes;
foreach (var k in new SortedSet<string>(keys))
{
yield return Encoding.UTF8.GetBytes(k);
yield return blockStateSet.Changes.TryGetValue(k, out var value)
? value.ToByteArray()
: ByteString.Empty.ToByteArray();
yield return ByteString.Empty.ToByteArray();
}
}

Expand Down

0 comments on commit 698562e

Please sign in to comment.