Skip to content

Commit 9b03087

Browse files
authored
feat(store): store recovery tools (#325)
Unsafe tools to manipulate the store's state
1 parent 38be935 commit 9b03087

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

store/store_recover.go

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
package store
2+
3+
import (
4+
"context"
5+
"errors"
6+
7+
"github.com/ipfs/go-datastore"
8+
9+
"github.com/celestiaorg/go-header"
10+
)
11+
12+
// ResetTail resets the tail of the store to be at the given height.
13+
// The new tail must be present in the store.
14+
// WARNING: Only use this function if you know what you are doing.
15+
func UnsafeResetTail[H header.Header[H]](
16+
ctx context.Context,
17+
store *Store[H],
18+
height uint64,
19+
) error {
20+
if err := store.setTail(ctx, store.ds, height); err != nil {
21+
return err
22+
}
23+
24+
return nil
25+
}
26+
27+
// ResetHead resets the head of the store to be at the given height.
28+
// The new head must be present in the store.
29+
// WARNING: Only use this function if you know what you are doing.
30+
func UnsafeResetHead[H header.Header[H]](
31+
ctx context.Context,
32+
store *Store[H],
33+
height uint64,
34+
) error {
35+
newHead, err := store.getByHeight(ctx, height)
36+
if err != nil {
37+
return err
38+
}
39+
40+
if err := writeHeaderHashTo(ctx, store.ds, newHead, headKey); err != nil {
41+
return err
42+
}
43+
44+
store.contiguousHead.Store(&newHead)
45+
return nil
46+
}
47+
48+
// FindHeader forward iterates over the store starting from the given height until it finds any stored header
49+
// or the context is canceled.
50+
func FindHeader[H header.Header[H]](
51+
ctx context.Context,
52+
store *Store[H],
53+
startFrom uint64,
54+
) (hdr H, err error) {
55+
ctx, done := store.withReadTransaction(ctx)
56+
defer done()
57+
58+
for height := startFrom; ctx.Err() == nil; height++ {
59+
hash, err := store.heightIndex.HashByHeight(ctx, height, false)
60+
if errors.Is(err, datastore.ErrNotFound) {
61+
continue
62+
}
63+
if err != nil {
64+
return hdr, err
65+
}
66+
67+
ok, err := store.Has(ctx, hash)
68+
if err != nil {
69+
return hdr, err
70+
}
71+
if ok {
72+
return store.Get(ctx, hash)
73+
}
74+
}
75+
76+
return hdr, ctx.Err()
77+
}

0 commit comments

Comments
 (0)