diff --git a/encoding.go b/encoding.go index 14f3c697..9263776d 100644 --- a/encoding.go +++ b/encoding.go @@ -118,7 +118,7 @@ func CreateInternalNode(bitlist []byte, raw []byte, depth byte, comm []byte) (*I return nil, ErrInvalidNodeEncoding } for i, index := range indices { - n.children[index] = &HashedNode{raw[i*32 : (i+1)*32]} + n.children[index] = &HashedNode{commitment: raw[i*32 : (i+1)*32]} } n.commitment = new(Point) n.commitment.SetBytesTrusted(comm) diff --git a/hashednode.go b/hashednode.go index ae292b5b..3851197a 100644 --- a/hashednode.go +++ b/hashednode.go @@ -31,7 +31,8 @@ import ( ) type HashedNode struct { - commitment []byte + commitment []byte + cachedPoint *Point } func (*HashedNode) Insert([]byte, []byte, NodeResolverFn) error { @@ -54,9 +55,11 @@ func (n *HashedNode) Commit() *Point { if n.commitment == nil { panic("nil commitment") } - c := new(Point) - c.SetBytesTrusted(n.commitment) - return c + if n.cachedPoint == nil { + n.cachedPoint = new(Point) + n.cachedPoint.SetBytesTrusted(n.commitment) + } + return n.cachedPoint } func (n *HashedNode) Commitment() *Point { @@ -92,8 +95,8 @@ func (*HashedNode) setDepth(_ byte) { } func (n *HashedNode) Hash() *Fr { - h := new(Fr) - c := n.Commitment() - toFr(h, c) - return h + comm := n.Commitment() + hash := new(Fr) + toFr(hash, comm) + return hash } diff --git a/stateless.go b/stateless.go index 38393187..d99fe873 100644 --- a/stateless.go +++ b/stateless.go @@ -250,7 +250,7 @@ func (n *StatelessNode) InsertAtStem(stem []byte, values [][]byte, resolver Node return nil } - n.children[nChild] = &HashedNode{unresolved} + n.children[nChild] = &HashedNode{commitment: unresolved} // fallthrough to hash resolution } @@ -774,7 +774,7 @@ func (n *StatelessNode) setDepth(d byte) { func (n *StatelessNode) ToHashedNode() *HashedNode { b := n.commitment.Bytes() - return &HashedNode{b[:]} + return &HashedNode{commitment: b[:]} } func (n *StatelessNode) Flush(flush NodeFlushFn) { diff --git a/tree.go b/tree.go index 9c633cab..c01c5a97 100644 --- a/tree.go +++ b/tree.go @@ -333,7 +333,7 @@ func (n *InternalNode) toHashedNode() *HashedNode { panic("nil commitment") } comm := n.commitment.Bytes() - return &HashedNode{comm[:]} + return &HashedNode{commitment: comm[:]} } func (n *InternalNode) InsertOrdered(key []byte, value []byte, flush NodeFlushFn) error { values := make([][]byte, NodeWidth) @@ -774,7 +774,7 @@ func (n *LeafNode) ToHashedNode() *HashedNode { panic("nil commitment") } comm := n.commitment.Bytes() - return &HashedNode{comm[:]} + return &HashedNode{commitment: comm[:]} } func (n *LeafNode) Insert(k []byte, value []byte, _ NodeResolverFn) error {