66 "os"
77 "path/filepath"
88 "sync"
9+ "sync/atomic"
910)
1011
1112// Cache is a generic cache that maintains items that are seen and hard confirmed
@@ -18,6 +19,8 @@ type Cache[T any] struct {
1819 daIncluded * sync.Map
1920 // hashByHeight tracks the hash associated with each height for pruning
2021 hashByHeight * sync.Map
22+ // maxDAHeight tracks the maximum DA height seen
23+ maxDAHeight atomic.Uint64
2124}
2225
2326// NewCache returns a new Cache struct
@@ -27,6 +30,7 @@ func NewCache[T any]() *Cache[T] {
2730 hashes : new (sync.Map ),
2831 daIncluded : new (sync.Map ),
2932 hashByHeight : new (sync.Map ),
33+ maxDAHeight : atomic.Uint64 {},
3034 }
3135}
3236
@@ -91,13 +95,29 @@ func (c *Cache[T]) getDAIncluded(hash string) (uint64, bool) {
9195func (c * Cache [T ]) setDAIncluded (hash string , daHeight uint64 , blockHeight uint64 ) {
9296 c .daIncluded .Store (hash , daHeight )
9397 c .hashByHeight .Store (blockHeight , hash )
98+
99+ // Update max DA height if necessary
100+ current := c .maxDAHeight .Load ()
101+ if daHeight <= current {
102+ return
103+ }
104+
105+ if c .maxDAHeight .CompareAndSwap (current , daHeight ) {
106+ return
107+ }
94108}
95109
96110// removeDAIncluded removes the DA-included status of the hash
97111func (c * Cache [T ]) removeDAIncluded (hash string ) {
98112 c .daIncluded .Delete (hash )
99113}
100114
115+ // daHeight returns the maximum DA height from all DA-included items.
116+ // Returns 0 if no items are DA-included.
117+ func (c * Cache [T ]) daHeight () uint64 {
118+ return c .maxDAHeight .Load ()
119+ }
120+
101121// deleteAllForHeight removes all items and their associated data from the cache at the given height
102122func (c * Cache [T ]) deleteAllForHeight (height uint64 ) {
103123 c .itemsByHeight .Delete (height )
@@ -231,6 +251,11 @@ func (c *Cache[T]) LoadFromDisk(folderPath string) error {
231251 }
232252 for k , v := range daIncludedMap {
233253 c .daIncluded .Store (k , v )
254+ // Update max DA height during load
255+ current := c .maxDAHeight .Load ()
256+ if v > current {
257+ _ = c .maxDAHeight .CompareAndSwap (current , v )
258+ }
234259 }
235260
236261 return nil
0 commit comments