prysm-pulse/beacon-chain/cache/sync_committee_head_state.go
terence 5a66807989
Update to V5 (#13622)
* First take at updating everything to v5

* Patch gRPC gateway to use prysm v5

Fix patch

* Update go ssz

---------

Co-authored-by: Preston Van Loon <pvanloon@offchainlabs.com>
2024-02-15 05:46:47 +00:00

61 lines
1.7 KiB
Go

package cache
import (
"sync"
lru "github.com/hashicorp/golang-lru"
"github.com/prysmaticlabs/prysm/v5/beacon-chain/state"
lruwrpr "github.com/prysmaticlabs/prysm/v5/cache/lru"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
"github.com/prysmaticlabs/prysm/v5/runtime/version"
)
// SyncCommitteeHeadStateCache for the latest head state requested by a sync committee participant.
type SyncCommitteeHeadStateCache struct {
cache *lru.Cache
lock sync.RWMutex
}
// NewSyncCommitteeHeadState initializes a LRU cache for `SyncCommitteeHeadState` with size of 1.
func NewSyncCommitteeHeadState() *SyncCommitteeHeadStateCache {
c := lruwrpr.New(1) // only need size of 1 to avoid redundant state copies, hashing, and slot processing.
return &SyncCommitteeHeadStateCache{cache: c}
}
// Put `slot` as key and `state` as value onto the cache.
func (c *SyncCommitteeHeadStateCache) Put(slot primitives.Slot, st state.BeaconState) error {
c.lock.Lock()
defer c.lock.Unlock()
// Make sure that the provided state is non nil
// and is of the correct type.
if st == nil || st.IsNil() {
return ErrNilValueProvided
}
if st.Version() == version.Phase0 {
return ErrIncorrectType
}
c.cache.Add(slot, st)
return nil
}
// Get `state` using `slot` as key. Return nil if nothing is found.
func (c *SyncCommitteeHeadStateCache) Get(slot primitives.Slot) (state.BeaconState, error) {
c.lock.RLock()
defer c.lock.RUnlock()
val, exists := c.cache.Get(slot)
if !exists {
return nil, ErrNotFound
}
st, ok := val.(state.BeaconState)
if !ok {
return nil, ErrIncorrectType
}
// Sync committee is not supported in phase 0.
if st.Version() == version.Phase0 {
return nil, ErrIncorrectType
}
return st, nil
}