From 5193b91d587a59ce180299fdbad8efb553d13ef5 Mon Sep 17 00:00:00 2001 From: scooletz Date: Thu, 10 Aug 2023 11:19:40 +0200 Subject: [PATCH] strategy should be only for Keccak --- src/Paprika/Merkle/CommitExtensions.cs | 7 ++----- src/Paprika/Merkle/ComputeMerkleBehavior.cs | 10 +++++++--- 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/src/Paprika/Merkle/CommitExtensions.cs b/src/Paprika/Merkle/CommitExtensions.cs index 43d1ac39..38b647e6 100644 --- a/src/Paprika/Merkle/CommitExtensions.cs +++ b/src/Paprika/Merkle/CommitExtensions.cs @@ -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])); } diff --git a/src/Paprika/Merkle/ComputeMerkleBehavior.cs b/src/Paprika/Merkle/ComputeMerkleBehavior.cs index 6fc064d1..22a083f4 100644 --- a/src/Paprika/Merkle/ComputeMerkleBehavior.cs +++ b/src/Paprika/Merkle/ComputeMerkleBehavior.cs @@ -150,17 +150,21 @@ private KeccakOrRlp EncodeBranch(Key key, ICommit commit, scoped in Node.Branch ArrayPool.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; }