Skip to content

Commit

Permalink
Add initial 'Leaf' node
Browse files Browse the repository at this point in the history
  • Loading branch information
emlautarom1 committed Jun 19, 2023
1 parent 21db9f5 commit 2310146
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/Paprika.Tests/Merkle/NodeTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,25 @@ public void Extension_encoding()
Assert.That(extension.IsDirty, Is.EqualTo(true));
Assert.That(extension.Type, Is.EqualTo(NodeType.Extension));
}


[Test]
public void Leaf_encoding()
{
var rawPath = new byte[] { 0x2, 0x4, 0x6 };
var nibblePath = new NibblePath(rawPath, 0, rawPath.Length);
var leaf = new LeafNode(nibblePath);

// TODO: Figure how to store var-length encoded `NibblePath`
// Assert.That(leaf.Path.Equals(nibblePath));

// TODO: Test without unsafe
unsafe
{
Assert.That(sizeof(LeafNode), Is.EqualTo(33));
}

Assert.That(leaf.IsDirty, Is.EqualTo(true));
Assert.That(leaf.Type, Is.EqualTo(NodeType.Leaf));
}
}
28 changes: 28 additions & 0 deletions src/Paprika/Merkle/Node.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,31 @@ public Extension(NibblePath path)
_header = (byte)NodeType.Extension << 1 | IsDirtyFlag;
}
}

[StructLayout(LayoutKind.Explicit, Pack = 1, Size = Size)]
// Temporary name due to clash with existing `Leaf`
public readonly struct LeafNode
{
// Leaf: 1 byte for type + dirty, var-length for path, 32 bytes for keccak
private const int Size = 33;
private const byte IsDirtyFlag = 0b1000;
private const byte NodeTypeFlag = 0b0110;

[FieldOffset(0)]
private readonly byte _header;

[FieldOffset(1)]
private readonly Keccak _keccak;

public Keccak Keccak => _keccak;

public NibblePath Path => default;

public bool IsDirty => (_header & IsDirtyFlag) != 0;
public NodeType Type => (NodeType)((_header & NodeTypeFlag) >> 1);

public LeafNode(NibblePath path)
{
_header = (byte)NodeType.Leaf << 1 | IsDirtyFlag;
}
}

0 comments on commit 2310146

Please sign in to comment.