Files
oc-discovery/daemons/node/common/utils.go

69 lines
1.3 KiB
Go
Raw Normal View History

2026-02-17 13:11:22 +01:00
package common
import (
"context"
"fmt"
2026-03-11 16:28:15 +01:00
"math/rand"
2026-02-17 13:11:22 +01:00
"net"
"time"
"github.com/libp2p/go-libp2p/core/host"
pp "github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
)
func PeerIsAlive(h host.Host, ad pp.AddrInfo) bool {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
err := h.Connect(ctx, ad)
return err == nil
}
func ExtractIP(addr string) (net.IP, error) {
ma, err := multiaddr.NewMultiaddr(addr)
if err != nil {
return nil, err
}
2026-03-03 16:38:24 +01:00
ipStr, err := ma.ValueForProtocol(multiaddr.P_IP4)
2026-02-17 13:11:22 +01:00
if err != nil {
2026-03-03 16:38:24 +01:00
ipStr, err = ma.ValueForProtocol(multiaddr.P_IP6)
if err != nil {
return nil, err
}
2026-02-17 13:11:22 +01:00
}
2026-03-03 16:38:24 +01:00
ip := net.ParseIP(ipStr)
2026-02-17 13:11:22 +01:00
if ip == nil {
2026-03-03 16:38:24 +01:00
return nil, fmt.Errorf("invalid IP: %s", ipStr)
2026-02-17 13:11:22 +01:00
}
return ip, nil
}
2026-03-11 16:28:15 +01:00
func GetIndexer(addrOrId string) *pp.AddrInfo {
return Indexers.GetAddr(addrOrId)
}
func GetIndexersIDs() []pp.ID {
return Indexers.GetAddrIDs()
}
func GetIndexersStr() []string {
return Indexers.GetAddrsStr()
}
func GetIndexers() []*pp.AddrInfo {
entries := Indexers.GetAddrs()
result := make([]*pp.AddrInfo, 0, len(entries))
for _, e := range entries {
result = append(result, e.Info)
}
return result
}
func Shuffle[T any](slice []T) []T {
rand.Shuffle(len(slice), func(i, j int) {
slice[i], slice[j] = slice[j], slice[i]
})
return slice
}