Skip to content

[Issue-1368]: Panic in serializedPath.HasPrefix #1371

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Apr 20, 2023
18 changes: 12 additions & 6 deletions x/merkledb/path.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,28 @@ func (s SerializedPath) deserialize() path {
return result[:len(result)-s.NibbleLength&1]
}

// Returns true iff [prefix] is a prefix of [s] or equal to it.
// HasPrefix returns true iff [prefix] is a prefix of [s] or equal to it.
func (s SerializedPath) HasPrefix(prefix SerializedPath) bool {
if len(s.Value) < len(prefix.Value) {
prefixValue := prefix.Value
prefixLength := len(prefix.Value)
if s.NibbleLength < prefix.NibbleLength || len(s.Value) < prefixLength {
return false
}
prefixValue := prefix.Value
if !prefix.hasOddLength() {
return bytes.HasPrefix(s.Value, prefixValue)
}
reducedSize := len(prefixValue) - 1
reducedSize := prefixLength - 1

// the input was invalid so just return false
if reducedSize < 0 {
return false
}

// grab the last nibble in the prefix and serialized path
prefixRemainder := prefixValue[reducedSize] >> 4
valueRemainder := s.Value[reducedSize] >> 4
prefixValue = prefixValue[:reducedSize]
return bytes.HasPrefix(s.Value, prefixValue) && valueRemainder == prefixRemainder
// s has prefix if the last nibbles are equal and s has every byte but the last of prefix as a prefix
return valueRemainder == prefixRemainder && bytes.HasPrefix(s.Value, prefixValue[:reducedSize])
}

// Returns true iff [prefix] is a prefix of [s] but not equal to it.
Expand Down
14 changes: 14 additions & 0 deletions x/merkledb/path_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ func Test_SerializedPath_Has_Prefix(t *testing.T) {
prefix = SerializedPath{Value: []byte{}, NibbleLength: 0}
require.True(t, first.HasPrefix(prefix))
require.False(t, first.HasStrictPrefix(prefix))

a := SerializedPath{Value: []byte{0x10}, NibbleLength: 1}
b := SerializedPath{Value: []byte{0x10}, NibbleLength: 2}
require.False(t, a.HasPrefix(b))
}

func Test_SerializedPath_HasPrefix_BadInput(t *testing.T) {
a := SerializedPath{Value: []byte{}}
b := SerializedPath{Value: []byte{}, NibbleLength: 1}
require.False(t, a.HasPrefix(b))

a = SerializedPath{Value: []byte{}, NibbleLength: 10}
b = SerializedPath{Value: []byte{0x10}, NibbleLength: 1}
require.False(t, a.HasPrefix(b))
}

func Test_SerializedPath_Equal(t *testing.T) {
Expand Down