2019-11-08 15:40:21 +00:00
|
|
|
package consensus
|
|
|
|
|
|
|
|
import (
|
|
|
|
"container/list"
|
|
|
|
"sync"
|
|
|
|
|
2020-03-03 14:21:42 +00:00
|
|
|
"github.com/nspcc-dev/neo-go/pkg/util"
|
2019-11-08 15:40:21 +00:00
|
|
|
)
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// relayCache is payload cache which is used to store
|
2019-11-08 15:40:21 +00:00
|
|
|
// last consensus payloads.
|
|
|
|
type relayCache struct {
|
|
|
|
*sync.RWMutex
|
|
|
|
|
|
|
|
maxCap int
|
|
|
|
elems map[util.Uint256]*list.Element
|
|
|
|
queue *list.List
|
|
|
|
}
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// hashable is the type of items which can be stored in the relayCache.
|
2019-11-15 10:32:40 +00:00
|
|
|
type hashable interface {
|
|
|
|
Hash() util.Uint256
|
|
|
|
}
|
|
|
|
|
2019-11-08 15:40:21 +00:00
|
|
|
func newFIFOCache(capacity int) *relayCache {
|
|
|
|
return &relayCache{
|
|
|
|
RWMutex: new(sync.RWMutex),
|
|
|
|
|
|
|
|
maxCap: capacity,
|
|
|
|
elems: make(map[util.Uint256]*list.Element),
|
|
|
|
queue: list.New(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// Add adds payload into cache if it doesn't already exist there.
|
2019-11-15 10:32:40 +00:00
|
|
|
func (c *relayCache) Add(p hashable) {
|
2019-11-08 15:40:21 +00:00
|
|
|
c.Lock()
|
|
|
|
defer c.Unlock()
|
|
|
|
|
|
|
|
h := p.Hash()
|
|
|
|
if c.elems[h] != nil {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.queue.Len() >= c.maxCap {
|
|
|
|
first := c.queue.Front()
|
|
|
|
c.queue.Remove(first)
|
2019-11-15 10:32:40 +00:00
|
|
|
delete(c.elems, first.Value.(hashable).Hash())
|
2019-11-08 15:40:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
e := c.queue.PushBack(p)
|
|
|
|
c.elems[h] = e
|
|
|
|
}
|
|
|
|
|
2022-04-20 18:30:09 +00:00
|
|
|
// Has checks if the item is already in cache.
|
2019-11-15 10:32:40 +00:00
|
|
|
func (c *relayCache) Has(h util.Uint256) bool {
|
|
|
|
c.RLock()
|
|
|
|
defer c.RUnlock()
|
|
|
|
|
|
|
|
return c.elems[h] != nil
|
|
|
|
}
|
|
|
|
|
2019-11-08 15:40:21 +00:00
|
|
|
// Get returns payload with the specified hash from cache.
|
2019-11-15 10:32:40 +00:00
|
|
|
func (c *relayCache) Get(h util.Uint256) hashable {
|
2019-11-08 15:40:21 +00:00
|
|
|
c.RLock()
|
|
|
|
defer c.RUnlock()
|
|
|
|
|
|
|
|
e, ok := c.elems[h]
|
|
|
|
if !ok {
|
2019-11-15 10:32:40 +00:00
|
|
|
return hashable(nil)
|
2019-11-08 15:40:21 +00:00
|
|
|
}
|
2019-11-15 10:32:40 +00:00
|
|
|
return e.Value.(hashable)
|
2019-11-08 15:40:21 +00:00
|
|
|
}
|