Skip to content

Commit

Permalink
strategy should be only for Keccak
Browse files Browse the repository at this point in the history
  • Loading branch information
Scooletz committed Aug 10, 2023
1 parent 07f9d4e commit 5193b91
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
7 changes: 2 additions & 5 deletions src/Paprika/Merkle/CommitExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,9 @@ public static void SetBranch(this ICommit commit, in Key key, NibbleSet.Readonly
commit.Set(key, branch.WriteTo(stackalloc byte[branch.MaxByteLength]));
}

public static void SetBranch(this ICommit commit, in Key key, NibbleSet.Readonly children, KeccakOrRlp keccak)
public static void SetBranch(this ICommit commit, in Key key, NibbleSet.Readonly children, Keccak keccak)
{
Debug.Assert(keccak.DataType == KeccakOrRlp.Type.Keccak);
var actual = new Keccak(keccak.Span);

var branch = new Node.Branch(children, actual);
var branch = new Node.Branch(children, keccak);
commit.Set(key, branch.WriteTo(stackalloc byte[branch.MaxByteLength]));
}

Expand Down
10 changes: 7 additions & 3 deletions src/Paprika/Merkle/ComputeMerkleBehavior.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,17 +150,21 @@ private KeccakOrRlp EncodeBranch(Key key, ICommit commit, scoped in Node.Branch

ArrayPool<byte>.Shared.Return(bytes);

if (ShouldMemoizeBranchKeccak(key.Path))
if (result.DataType == KeccakOrRlp.Type.Keccak && ShouldMemoizeBranchKeccak(key.Path))
{
commit.SetBranch(key, branch.Children, result);
// Memoize only if Keccak and falls into the criteria.
// Storing RLP for an embedded node is useless as it can be easily re-calculated.
commit.SetBranch(key, branch.Children, new Keccak(result.Span));
}

return result;
}

private bool ShouldMemoizeBranchKeccak(NibblePath branchPath)
private bool ShouldMemoizeBranchKeccak(in NibblePath branchPath)
{
var level = NibblePath.KeccakNibbleCount - branchPath.Length - _minimumTreeLevelToMemoizeKeccak;

// memoize only if the branch is deeper than _minimumTreeLevelToMemoizeKeccak and every _memoizeKeccakEvery
return level >= 0 && level % _memoizeKeccakEvery == 0;
}

Expand Down

0 comments on commit 5193b91

Please sign in to comment.