Skip to content

Commit

Permalink
Make MaskLeft of NodeID return an explicit copy. (#1612)
Browse files Browse the repository at this point in the history
Currently we're copying everything twice as do n.Copy().MaskLeft().
  • Loading branch information
Martin2112 authored May 20, 2019
1 parent abff50a commit 1de36a8
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions merkle/map_verifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ func VerifyMapInclusionProof(treeID int64, leaf *trillian.MapLeaf, expectedRoot
// for the branch that we are on before combining it with the neighbor.
if len(runningHash) == 0 && len(pElement) != 0 {
depth := nID.PrefixLenBits - height
emptyBranch := nID.Copy().MaskLeft(depth)
emptyBranch := nID.MaskLeft(depth)
runningHash = h.HashEmpty(treeID, emptyBranch.Path, height)
}

Expand All @@ -83,7 +83,7 @@ func VerifyMapInclusionProof(treeID int64, leaf *trillian.MapLeaf, expectedRoot
}
if len(runningHash) == 0 {
depth := 0
emptyBranch := nID.Copy().MaskLeft(depth)
emptyBranch := nID.MaskLeft(depth)
runningHash = h.HashEmpty(treeID, emptyBranch.Path, h.BitLen())
}

Expand Down
13 changes: 8 additions & 5 deletions storage/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,7 +389,7 @@ func (n *NodeID) FlipRightBit(i int) *NodeID {
// is 0. leftmask is only used to mask the last byte.
var leftmask = [8]byte{0xFF, 0x80, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE}

// MaskLeft returns NodeID with only the left n bits set
// MaskLeft returns a new copy of NodeID with only the left n bits set.
func (n *NodeID) MaskLeft(depth int) *NodeID {
r := make([]byte, len(n.Path))
if depth > 0 {
Expand All @@ -399,11 +399,14 @@ func (n *NodeID) MaskLeft(depth int) *NodeID {
// Mask off unwanted bits in the last byte.
r[depthBytes-1] = r[depthBytes-1] & leftmask[depth%8]
}
b := n.PrefixLenBits
if depth < n.PrefixLenBits {
n.PrefixLenBits = depth
b = depth
}
return &NodeID{
PrefixLenBits: b,
Path: r,
}
n.Path = r
return n
}

// Neighbor returns the same node with the bit at PrefixLenBits flipped.
Expand All @@ -425,7 +428,7 @@ func (n *NodeID) Siblings() []NodeID {
sibs := make([]NodeID, n.PrefixLenBits)
for height := range sibs {
depth := n.PrefixLenBits - height
sibs[height] = *(n.Copy().MaskLeft(depth).Neighbor())
sibs[height] = *(n.MaskLeft(depth).Neighbor())
}
return sibs
}
Expand Down

0 comments on commit 1de36a8

Please sign in to comment.