prysm-pulse/beacon-chain/cache/payload_id.go

64 lines
1.7 KiB
Go
Raw Permalink Normal View History

2022-04-06 23:36:52 +00:00
package cache
import (
"sync"
"github.com/prysmaticlabs/prysm/v5/consensus-types/primitives"
2022-04-06 23:36:52 +00:00
)
// RootToPayloadIDMap is a map with keys the head root and values the
// corresponding PayloadID
type RootToPayloadIDMap map[[32]byte]primitives.PayloadID
2022-04-06 23:36:52 +00:00
// PayloadIDCache is a cache that keeps track of the prepared payload ID for the
// given slot and with the given head root.
type PayloadIDCache struct {
slotToPayloadID map[primitives.Slot]RootToPayloadIDMap
sync.Mutex
2022-04-06 23:36:52 +00:00
}
// NewPayloadIDCache returns a new payload ID cache
func NewPayloadIDCache() *PayloadIDCache {
return &PayloadIDCache{slotToPayloadID: make(map[primitives.Slot]RootToPayloadIDMap)}
2022-04-06 23:36:52 +00:00
}
// PayloadID returns the payload ID for the given slot and parent block root
func (p *PayloadIDCache) PayloadID(slot primitives.Slot, root [32]byte) (primitives.PayloadID, bool) {
p.Lock()
defer p.Unlock()
inner, ok := p.slotToPayloadID[slot]
2022-04-06 23:36:52 +00:00
if !ok {
return primitives.PayloadID{}, false
2022-04-06 23:36:52 +00:00
}
pid, ok := inner[root]
if !ok {
return primitives.PayloadID{}, false
}
return pid, true
2022-04-06 23:36:52 +00:00
}
// SetPayloadID updates the payload ID for the given slot and head root
// it also prunes older entries in the cache
func (p *PayloadIDCache) Set(slot primitives.Slot, root [32]byte, pid primitives.PayloadID) {
p.Lock()
defer p.Unlock()
if slot > 1 {
p.prune(slot - 2)
}
inner, ok := p.slotToPayloadID[slot]
if !ok {
inner = make(RootToPayloadIDMap)
p.slotToPayloadID[slot] = inner
2022-04-06 23:36:52 +00:00
}
inner[root] = pid
2022-04-06 23:36:52 +00:00
}
// Prune prunes old payload IDs. Requires a Lock in the cache
func (p *PayloadIDCache) prune(slot primitives.Slot) {
for key := range p.slotToPayloadID {
if key < slot {
delete(p.slotToPayloadID, key)
2022-04-06 23:36:52 +00:00
}
}
}