2023-05-04 11:26:27 +00:00
|
|
|
package peer_exchange
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
|
|
|
|
"github.com/ethereum/go-ethereum/p2p/enode"
|
2023-12-06 18:34:58 +00:00
|
|
|
|
2023-05-04 11:26:27 +00:00
|
|
|
"github.com/waku-org/go-waku/waku/v2/protocol/peer_exchange/pb"
|
|
|
|
)
|
|
|
|
|
2023-05-04 12:03:13 +00:00
|
|
|
// simpleLRU internal uses container/list, which is ring buffer(double linked list)
|
2023-05-04 11:26:27 +00:00
|
|
|
type enrCache struct {
|
2023-12-06 18:34:58 +00:00
|
|
|
// using lru, saves us from periodically cleaning the cache to mauintain a certain size
|
|
|
|
data *shardLRU
|
2023-05-04 11:26:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// err on negative size
|
2023-12-06 18:34:58 +00:00
|
|
|
func newEnrCache(size int) *enrCache {
|
|
|
|
inner := newShardLRU(int(size))
|
2023-05-04 11:26:27 +00:00
|
|
|
return &enrCache{
|
|
|
|
data: inner,
|
2023-12-06 18:34:58 +00:00
|
|
|
}
|
2023-05-04 11:26:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// updating cache
|
2023-12-06 18:34:58 +00:00
|
|
|
func (c *enrCache) updateCache(node *enode.Node) error {
|
|
|
|
currNode := c.data.Get(node.ID())
|
|
|
|
if currNode == nil || node.Seq() > currNode.Seq() {
|
|
|
|
return c.data.Add(node)
|
2023-10-16 15:46:11 +00:00
|
|
|
}
|
2023-12-06 18:34:58 +00:00
|
|
|
return nil
|
2023-05-04 11:26:27 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// get `numPeers` records of enr
|
2023-12-06 18:34:58 +00:00
|
|
|
func (c *enrCache) getENRs(neededPeers int, clusterIndex *ShardInfo) ([]*pb.PeerInfo, error) {
|
2023-05-04 11:26:27 +00:00
|
|
|
//
|
2023-12-06 18:34:58 +00:00
|
|
|
nodes := c.data.GetRandomNodes(clusterIndex, neededPeers)
|
2023-05-04 11:26:27 +00:00
|
|
|
result := []*pb.PeerInfo{}
|
2023-12-06 18:34:58 +00:00
|
|
|
for _, node := range nodes {
|
|
|
|
//
|
2023-05-04 11:26:27 +00:00
|
|
|
var b bytes.Buffer
|
|
|
|
writer := bufio.NewWriter(&b)
|
2023-12-06 18:34:58 +00:00
|
|
|
err := node.Record().EncodeRLP(writer)
|
2023-05-04 11:26:27 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
writer.Flush()
|
|
|
|
result = append(result, &pb.PeerInfo{
|
2023-11-07 19:48:43 +00:00
|
|
|
Enr: b.Bytes(),
|
2023-05-04 11:26:27 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
return result, nil
|
|
|
|
}
|