Skip to content
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

prefixdb: fix bug with Compact nil limit #3000

Merged
merged 6 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion database/prefixdb/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ var (
// a unique value.
type Database struct {
// All keys in this db begin with this byte slice
dbPrefix []byte
dbPrefix []byte
// Lexically one greater than dbPrefix, defining the end of this db's key range
dbLimit []byte
bufferPool *utils.BytesPool

// lock needs to be held during Close to guarantee db will not be set to nil
Expand All @@ -37,11 +39,25 @@ type Database struct {
func newDB(prefix []byte, db database.Database) *Database {
return &Database{
dbPrefix: prefix,
dbLimit: incrementByteSlice(prefix),
db: db,
bufferPool: utils.NewBytesPool(),
}
}

func incrementByteSlice(orig []byte) []byte {
n := len(orig)
buf := make([]byte, n)
copy(buf, orig)
for i := n - 1; i >= 0; i-- {
buf[i]++
if buf[i] != 0 {
break
}
}
return buf
}

// New returns a new prefixed database
func New(prefix []byte, db database.Database) *Database {
if prefixDB, ok := db.(*Database); ok {
Expand Down Expand Up @@ -189,6 +205,9 @@ func (db *Database) Compact(start, limit []byte) error {
prefixedStart := db.prefix(start)
defer db.bufferPool.Put(prefixedStart)

if limit == nil {
return db.db.Compact(*prefixedStart, db.dbLimit)
}
prefixedLimit := db.prefix(limit)
defer db.bufferPool.Put(prefixedLimit)

Expand Down
11 changes: 11 additions & 0 deletions database/prefixdb/db_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"fmt"
"testing"

"github.com/stretchr/testify/require"

"github.com/ava-labs/avalanchego/database"
"github.com/ava-labs/avalanchego/database/memdb"
)
Expand All @@ -25,6 +27,15 @@ func TestInterface(t *testing.T) {
}
}

func TestPrefixLimit(t *testing.T) {
testString := []string{"hello", "world", "a\xff", "\x01\xff\xff\xff\xff"}
expected := []string{"hellp", "worle", "b\x00", "\x02\x00\x00\x00\x00"}
for i, str := range testString {
db := newDB([]byte(str), nil)
require.Equal(t, db.dbLimit, []byte(expected[i]))
}
}

func FuzzKeyValue(f *testing.F) {
database.FuzzKeyValue(f, New([]byte(""), memdb.New()))
}
Expand Down
Loading