commit inicial do projeto
This commit is contained in:
52
internal/p2p/dht.go
Normal file
52
internal/p2p/dht.go
Normal file
@ -0,0 +1,52 @@
|
||||
package p2p
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
dht "github.com/libp2p/go-libp2p-kad-dht"
|
||||
routingdiscovery "github.com/libp2p/go-libp2p/p2p/discovery/routing"
|
||||
)
|
||||
|
||||
const rendezvousString = "dejo-global"
|
||||
|
||||
// InitDHT inicializa o Kademlia DHT e ativa descoberta global de peers.
|
||||
func (p *P2PNode) InitDHT(ctx context.Context) error {
|
||||
d, err := dht.New(ctx, p.Host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erro ao iniciar DHT: %w", err)
|
||||
}
|
||||
|
||||
if err := d.Bootstrap(ctx); err != nil {
|
||||
return fmt.Errorf("erro ao bootstrap DHT: %w", err)
|
||||
}
|
||||
|
||||
routing := routingdiscovery.NewRoutingDiscovery(d)
|
||||
_, err = routing.Advertise(ctx, rendezvousString)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erro ao anunciar no DHT: %w", err)
|
||||
}
|
||||
|
||||
fmt.Println("📡 Anunciado no DHT com tag:", rendezvousString)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
peers, err := routing.FindPeers(ctx, rendezvousString)
|
||||
if err != nil {
|
||||
fmt.Println("Erro ao buscar peers:", err)
|
||||
continue
|
||||
}
|
||||
for pinfo := range peers {
|
||||
if pinfo.ID == p.Host.ID() {
|
||||
continue // ignora si mesmo
|
||||
}
|
||||
fmt.Println("🌍 Peer encontrado via DHT:", pinfo.ID)
|
||||
_ = p.Host.Connect(ctx, pinfo)
|
||||
}
|
||||
time.Sleep(10 * time.Second)
|
||||
}
|
||||
}()
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user