Skip to content

Commit

Permalink
indexers: add ResetFlatFileState()
Browse files Browse the repository at this point in the history
ResetFlatFileState() allows the caller to reset the flatfile state so
that all the data can be removed and the flatfile state restored to the
initial state.
  • Loading branch information
kcalvinalvin committed Feb 3, 2025
1 parent 1058f4d commit c68bd4f
Show file tree
Hide file tree
Showing 2 changed files with 79 additions and 0 deletions.
20 changes: 20 additions & 0 deletions blockchain/indexers/flatfile.go
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,26 @@ func (ff *FlatFileState) BestHeight() int32 {
return ff.currentHeight
}

// ResetFlatFileState removes all of the data in the files and resets the
// state to 0.
func (ff *FlatFileState) ResetFlatFileState() error {
ff.mtx.Lock()
defer ff.mtx.Unlock()

ff.currentHeight = 0
ff.currentOffset = 0
ff.offsets = ff.offsets[:1]

err := ff.dataFile.Truncate(0)
if err != nil {
return err
}

// We truncate to 8 because each offset is 8 bytes and we reserve the
// space for the genesis block.
return ff.offsetFile.Truncate(8)
}

// deleteFileFile removes the flat file state directory and all the contents
// in it.
func deleteFlatFile(path string) error {
Expand Down
59 changes: 59 additions & 0 deletions blockchain/indexers/flatfile_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -846,3 +846,62 @@ func TestRecover(t *testing.T) {
}
}
}

func TestReset(t *testing.T) {
t.Parallel()

rnd := rand.New(rand.NewSource(time.Now().UnixNano()))

ff, tmpDir, err := initFF("TestReset")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tmpDir) // clean up. Always runs

for i := 0; i < 100; i++ {
data, err := createRandByteSlice(rnd)
if err != nil {
t.Fatal(err)
}
err = ff.StoreData(int32(i)+1, data)
if err != nil {
t.Fatal(err)
}
}

err = ff.ResetFlatFileState()
if err != nil {
t.Fatal(err)
}

// Check that we've successfully reset the flat file.
if ff.currentHeight != 0 {
t.Fatalf("expected 0 but got %v", ff.currentHeight)
}

if ff.currentOffset != 0 {
t.Fatalf("expected 0 but got %v", ff.currentOffset)
}

if len(ff.offsets) != 1 {
t.Fatalf("expected 1 but got %v", len(ff.offsets))
}

dataFileSize, err := ff.dataFile.Seek(0, 2)
if err != nil {
t.Fatal(err)
}

if dataFileSize != 0 {
t.Fatalf("expected 0 but got %v", dataFileSize)
}

offsetFileSize, err := ff.offsetFile.Seek(0, 2)
if err != nil {
t.Fatal(err)
}

if offsetFileSize != 8 {
t.Fatalf("expected 8 but got %v", offsetFileSize)
}
}

0 comments on commit c68bd4f

Please sign in to comment.