dht_relay_discovery.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright © 2022 Ettore Di Giacinto <[email protected]>
  2. //
  3. // This program is free software; you can redistribute it and/or modify
  4. // it under the terms of the GNU General Public License as published by
  5. // the Free Software Foundation; either version 2 of the License, or
  6. // (at your option) any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program; if not, see <http://www.gnu.org/licenses/>.
  15. package services
  16. import (
  17. "context"
  18. "time"
  19. "github.com/ipfs/go-log"
  20. "github.com/libp2p/go-libp2p-core/peer"
  21. "github.com/mudler/edgevpn/pkg/blockchain"
  22. "github.com/mudler/edgevpn/pkg/discovery"
  23. "github.com/mudler/edgevpn/pkg/node"
  24. )
  25. // AutoRelayFeederService is a service responsible to returning periodically peers to
  26. // scan for relays from a DHT discovery service
  27. func AutoRelayFeederService(ll log.StandardLogger, peerChan chan peer.AddrInfo, dht *discovery.DHT, duration time.Duration) node.NetworkService {
  28. return func(ctx context.Context, c node.Config, n *node.Node, b *blockchain.Ledger) error {
  29. ll.Debug("[relay discovery] Service starts")
  30. ctx, cancel := context.WithCancel(ctx)
  31. go func() {
  32. t := time.NewTicker(duration)
  33. defer t.Stop()
  34. defer cancel()
  35. for {
  36. select {
  37. case <-t.C:
  38. case <-ctx.Done():
  39. ll.Debug("[relay discovery] stopped")
  40. return
  41. }
  42. ll.Debug("[relay discovery] Finding relays from closest peer")
  43. closestPeers, err := dht.GetClosestPeers(ctx, n.Host().ID().String())
  44. if err != nil {
  45. ll.Error(err)
  46. continue
  47. }
  48. for _, p := range closestPeers {
  49. addrs := n.Host().Peerstore().Addrs(p)
  50. if len(addrs) == 0 {
  51. continue
  52. }
  53. ll.Debugf("[relay discovery] Found close peer '%s'", p.Pretty())
  54. select {
  55. case peerChan <- peer.AddrInfo{ID: p, Addrs: addrs}:
  56. case <-ctx.Done():
  57. return
  58. }
  59. }
  60. }
  61. }()
  62. return nil
  63. }
  64. }