Skip to content

Commit

Permalink
Add initial scaffold for Root Hash calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
emlautarom1 committed Jun 23, 2023
1 parent e46b2fc commit 7155c90
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Paprika.Tests/Merkle/RootHashTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using NUnit.Framework;
using Paprika.Chain;
using Paprika.Crypto;
using Paprika.Merkle;
using Paprika.Store;

namespace Paprika.Tests.Merkle;

public class RootHashTests
{
private const int SmallDb = 256 * Page.PageSize;
private readonly Keccak _blockKeccak = Keccak.Compute("block"u8);

[Test]
public async Task Empty_database()
{
using var db = PagedDb.NativeMemoryDb(SmallDb);
await using var blockchain = new Blockchain(db, preCommit: new ComputeMerkleBehavior());

using var block = blockchain.StartNew(Keccak.Zero, _blockKeccak, 1);

block.Commit();

var rootHash = block.GetMerkleRootHash();
var expectedRootHash =
new Keccak(Convert.FromHexString("56E81F171BCC55A6FF8345E692C0F86E5B48E01B996CADC001622FB5E363B421"));

Assert.That(rootHash, Is.EqualTo(expectedRootHash));
}

[Test]
[Ignore("Not working yet")]
public async Task Single_account()
{
using var db = PagedDb.NativeMemoryDb(SmallDb);
await using var blockchain = new Blockchain(db, preCommit: new ComputeMerkleBehavior());

var key = Values.Key0;
var account = new Account(Values.Balance0, Values.Nonce0);

using var block = blockchain.StartNew(Keccak.Zero, _blockKeccak, 1);

block.SetAccount(key, account);
block.Commit();

var rootHash = block.GetMerkleRootHash();
var expectedRootHash =
new Keccak(Convert.FromHexString("E2533A0A0C4F1DDB72FEB7BFAAD12A83853447DEAAB6F28FA5C443DD2D37C3FB"));

Assert.That(rootHash, Is.EqualTo(expectedRootHash));
}
}
15 changes: 15 additions & 0 deletions src/Paprika/Merkle/ComputeMerkleBehavior.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using Paprika.Chain;

namespace Paprika.Merkle;

public class ComputeMerkleBehavior : IPreCommitBehavior
{
public void BeforeCommit(ICommit commit)
{
// Foreach key in the commit:
// > Set each intermediate Merkle node as 'Dirty'
// Modify any intermediate Merkle node if there were any inserts (7 cases)
// Recompute the Keccak of all Merkle nodes
// The root Merkle node should exist on the Empty Path (''), and it's Keccak is the Merkle Root Hash
}
}
12 changes: 12 additions & 0 deletions src/Paprika/Merkle/WorldStateExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using Paprika.Chain;
using Paprika.Crypto;

namespace Paprika.Merkle;

public static class WorldStateExtensions
{
public static Keccak GetMerkleRootHash(this IWorldState state)
{
return Keccak.EmptyTreeHash;
}
}

0 comments on commit 7155c90

Please sign in to comment.