Skip to content

Commit c8dd270

Browse files
committed
factor out bitCeil
1 parent e814add commit c8dd270

2 files changed

Lines changed: 24 additions & 4 deletions

File tree

proof/proof.go

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -219,10 +219,27 @@ func reverse(ids []compact.NodeID) {
219219
}
220220
}
221221

222+
// isSubTreeValid returns whether a subtree covers a valid range.
223+
// A subtree is valid if there exist a parent tree node to:
224+
// - all the subtree nodes
225+
// - no extra node to the left of the subtree
226+
// - potentially extra nodes to the right of the subtree
222227
func isSubtreeValid(start, end uint64) bool {
223-
shift := bits.Len64(end - start - 1)
224-
if shift >= 64 {
225-
return start == 0
228+
l := end - start
229+
if start == 0 {
230+
return true
231+
} else if (l) > uint64(1)<<63 {
232+
// special-case large subtree to avoid panic
233+
return false
226234
}
227-
return start%(uint64(1)<<shift) == 0
235+
return start%bitCeil(l) == 0
236+
}
237+
238+
// bitCeil returns the smallest power of 2 larger than n.
239+
// Panics if n > 2^63.
240+
func bitCeil(n uint64) uint64 {
241+
if n <= 1 {
242+
return 1
243+
}
244+
return uint64(1) << bits.Len64(n-1)
228245
}

proof/proof_test.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,9 @@ func TestInclusion(t *testing.T) {
7171
{size: 2, index: 1, want: nodes(id(0, 0))}, // a
7272
{size: 3, index: 1, want: rehash(1, 2, id(0, 0), id(0, 2))}, // a c
7373

74+
{size: 8, index: 2, want: rehash(1, 2, id(0, 0), id(0, 2))}, // a c
75+
{size: 4, index: 1, want: rehash(1, 2, id(0, 0), id(0, 2))}, // a c
76+
7477
// Tree of size 7.
7578
{size: 7, index: 0, want: rehash(2, 4, // l=hash(i,j)
7679
id(0, 1), id(1, 1), id(0, 6), id(1, 2))}, // b h j i

0 commit comments

Comments
 (0)