68 lines
1.3 KiB
Go
68 lines
1.3 KiB
Go
package node
|
|
|
|
import (
|
|
"log"
|
|
"net/netip"
|
|
"runtime/debug"
|
|
"sort"
|
|
"time"
|
|
)
|
|
|
|
type pubAddrStore struct {
|
|
lastSeen map[netip.AddrPort]time.Time
|
|
addrList []netip.AddrPort
|
|
}
|
|
|
|
func newPubAddrStore() *pubAddrStore {
|
|
return &pubAddrStore{
|
|
lastSeen: map[netip.AddrPort]time.Time{},
|
|
addrList: make([]netip.AddrPort, 0, 32),
|
|
}
|
|
}
|
|
|
|
func (store *pubAddrStore) Store(add netip.AddrPort) {
|
|
if localPub {
|
|
log.Printf("OOPS: Local pub but storage attempt: %s", debug.Stack())
|
|
return
|
|
}
|
|
|
|
if _, exists := store.lastSeen[add]; !exists {
|
|
store.addrList = append(store.addrList, add)
|
|
}
|
|
store.lastSeen[add] = time.Now()
|
|
store.sort()
|
|
}
|
|
|
|
func (store *pubAddrStore) Get() (addrs [8]netip.AddrPort) {
|
|
if localPub {
|
|
addrs[0] = localAddr
|
|
return
|
|
}
|
|
|
|
copy(addrs[:], store.addrList)
|
|
return
|
|
}
|
|
|
|
func (store *pubAddrStore) Clean() {
|
|
if localPub {
|
|
return
|
|
}
|
|
|
|
for ip, lastSeen := range store.lastSeen {
|
|
if time.Since(lastSeen) > timeoutInterval {
|
|
delete(store.lastSeen, ip)
|
|
}
|
|
}
|
|
store.addrList = store.addrList[:0]
|
|
for ip := range store.lastSeen {
|
|
store.addrList = append(store.addrList, ip)
|
|
}
|
|
store.sort()
|
|
}
|
|
|
|
func (store *pubAddrStore) sort() {
|
|
sort.Slice(store.addrList, func(i, j int) bool {
|
|
return store.lastSeen[store.addrList[j]].Before(store.lastSeen[store.addrList[i]])
|
|
})
|
|
}
|