dht_bootstrap.go 5.62 KB
Newer Older
1 2 3
package dht

import (
Jeromy's avatar
Jeromy committed
4
	"context"
5
	"fmt"
Aarsh Shah's avatar
Aarsh Shah committed
6 7
	"strings"
	"sync"
8 9
	"time"

10 11
	"github.com/libp2p/go-libp2p-core/routing"
	"github.com/multiformats/go-multiaddr"
Hector Sanjuan's avatar
Hector Sanjuan committed
12
	_ "github.com/multiformats/go-multiaddr-dns"
Aarsh Shah's avatar
Aarsh Shah committed
13
	"github.com/pkg/errors"
14 15
)

16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
var DefaultBootstrapPeers []multiaddr.Multiaddr

func init() {
	for _, s := range []string{
		"/dnsaddr/bootstrap.libp2p.io/ipfs/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
		"/dnsaddr/bootstrap.libp2p.io/ipfs/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
		"/dnsaddr/bootstrap.libp2p.io/ipfs/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb",
		"/dnsaddr/bootstrap.libp2p.io/ipfs/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
		"/ip4/104.131.131.82/tcp/4001/ipfs/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ",            // mars.i.ipfs.io
		"/ip4/104.236.179.241/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM",           // pluto.i.ipfs.io
		"/ip4/128.199.219.111/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu",           // saturn.i.ipfs.io
		"/ip4/104.236.76.40/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64",             // venus.i.ipfs.io
		"/ip4/178.62.158.247/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd",            // earth.i.ipfs.io
		"/ip6/2604:a880:1:20::203:d001/tcp/4001/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM",  // pluto.i.ipfs.io
		"/ip6/2400:6180:0:d0::151:6001/tcp/4001/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu",  // saturn.i.ipfs.io
		"/ip6/2604:a880:800:10::4a:5001/tcp/4001/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64", // venus.i.ipfs.io
		"/ip6/2a03:b0c0:0:1010::23:1001/tcp/4001/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd", // earth.i.ipfs.io
	} {
		ma, err := multiaddr.NewMultiaddr(s)
		if err != nil {
			panic(err)
		}
		DefaultBootstrapPeers = append(DefaultBootstrapPeers, ma)
	}
}

42
// Runs cfg.Queries bootstrap queries every cfg.BucketPeriod.
43
func (dht *IpfsDHT) Bootstrap(ctx context.Context) error {
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
	seedRTIfEmpty := func(tag string) {
		if dht.routingTable.Size() == 0 {
			req := mkRtRecoveryReq()
			logger.Warningf("dht bootstrap: %s: RT is empty, will attempt to initiate recovery, reqID=%s", tag, req.id)
			select {
			case <-ctx.Done():
				return
			case dht.rtRecoveryChan <- req:
				select {
				case <-ctx.Done():
					return
				case <-req.errorChan:
					// TODO Should we abort the ONGOING bootstrap attempt if seeder returns an error on the channel ?
				}
			}
		}
	}
61

Aarsh Shah's avatar
Aarsh Shah committed
62 63 64
	// we should query for self periodically so we can discover closer peers
	go func() {
		for {
65 66
			seedRTIfEmpty("self walk")
			err := dht.selfWalk(ctx)
Aarsh Shah's avatar
Aarsh Shah committed
67
			if err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
68
				logger.Warningf("error bootstrapping while searching for my self (I'm Too Shallow ?): %s", err)
Aarsh Shah's avatar
Aarsh Shah committed
69 70
			}
			select {
71
			case <-time.After(dht.bootstrapCfg.SelfQueryInterval):
Aarsh Shah's avatar
Aarsh Shah committed
72 73 74 75 76 77 78
			case <-ctx.Done():
				return
			}
		}
	}()

	// scan the RT table periodically & do a random walk on k-buckets that haven't been queried since the given bucket period
Matt Joiner's avatar
Matt Joiner committed
79
	go func() {
80
		for {
81 82
			seedRTIfEmpty("buckets")
			err := dht.bootstrapBuckets(ctx)
Matt Joiner's avatar
Matt Joiner committed
83
			if err != nil {
Matt Joiner's avatar
Matt Joiner committed
84
				logger.Warningf("error bootstrapping: %s", err)
Matt Joiner's avatar
Matt Joiner committed
85
			}
86
			select {
87
			case <-time.After(dht.bootstrapCfg.RoutingTableScanInterval):
Matt Joiner's avatar
Matt Joiner committed
88
			case <-ctx.Done():
89 90 91
				return
			}
		}
Matt Joiner's avatar
Matt Joiner committed
92 93
	}()
	return nil
Matt Joiner's avatar
Matt Joiner committed
94
}
vyzo's avatar
vyzo committed
95

Aarsh Shah's avatar
Aarsh Shah committed
96
//scan the RT,& do a random walk on k-buckets that haven't been queried since the given bucket period
97
func (dht *IpfsDHT) bootstrapBuckets(ctx context.Context) error {
Matt Joiner's avatar
Matt Joiner committed
98
	doQuery := func(n int, target string, f func(context.Context) error) error {
Aarsh Shah's avatar
Aarsh Shah committed
99 100
		logger.Infof("starting bootstrap query for bucket %d to %s (routing table size was %d)",
			n, target, dht.routingTable.Size())
101
		defer func() {
Aarsh Shah's avatar
Aarsh Shah committed
102 103
			logger.Infof("finished bootstrap query for bucket %d to %s (routing table size is now %d)",
				n, target, dht.routingTable.Size())
104
		}()
105
		queryCtx, cancel := context.WithTimeout(ctx, dht.bootstrapCfg.Timeout)
106
		defer cancel()
107 108 109 110 111
		err := f(queryCtx)
		if err == context.DeadlineExceeded && queryCtx.Err() == context.DeadlineExceeded && ctx.Err() == nil {
			return nil
		}
		return err
112 113
	}

Aarsh Shah's avatar
Aarsh Shah committed
114 115 116 117 118
	buckets := dht.routingTable.GetAllBuckets()
	var wg sync.WaitGroup
	errChan := make(chan error)

	for bucketID, bucket := range buckets {
119
		if time.Since(bucket.RefreshedAt()) > dht.bootstrapCfg.BucketPeriod {
Aarsh Shah's avatar
Aarsh Shah committed
120 121 122 123
			wg.Add(1)
			go func(bucketID int, errChan chan<- error) {
				defer wg.Done()
				// gen rand peer in the bucket
Steven Allen's avatar
Steven Allen committed
124
				randPeerInBucket := dht.routingTable.GenRandPeerID(bucketID)
Aarsh Shah's avatar
Aarsh Shah committed
125 126 127

				// walk to the generated peer
				walkFnc := func(c context.Context) error {
128
					_, err := dht.FindPeer(ctx, randPeerInBucket)
Aarsh Shah's avatar
Aarsh Shah committed
129 130 131 132 133 134 135 136 137 138
					if err == routing.ErrNotFound {
						return nil
					}
					return err
				}

				if err := doQuery(bucketID, randPeerInBucket.String(), walkFnc); err != nil {
					errChan <- errors.Wrapf(err, "failed to do a random walk on bucket %d", bucketID)
				}
			}(bucketID, errChan)
Matt Joiner's avatar
Matt Joiner committed
139
		}
Steven Allen's avatar
Steven Allen committed
140 141
	}

Aarsh Shah's avatar
Aarsh Shah committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
	// wait for all walks to finish & close the error channel
	go func() {
		wg.Wait()
		close(errChan)
	}()

	// accumulate errors from all go-routines
	var errStrings []string
	for err := range errChan {
		errStrings = append(errStrings, err.Error())
	}
	if len(errStrings) == 0 {
		return nil
	} else {
		return fmt.Errorf("errors encountered while running bootstrap on RT: %s", strings.Join(errStrings, "\n"))
	}
}

160 161 162
// synchronous bootstrap.
func (dht *IpfsDHT) bootstrapOnce(ctx context.Context) error {
	if err := dht.selfWalk(ctx); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
163 164
		return errors.Wrap(err, "failed bootstrap while searching for self")
	} else {
165
		return dht.bootstrapBuckets(ctx)
Aarsh Shah's avatar
Aarsh Shah committed
166
	}
167
}
168

169 170 171 172 173 174 175
// Traverse the DHT toward the self ID
func (dht *IpfsDHT) selfWalk(ctx context.Context) error {
	_, err := dht.FindPeer(ctx, dht.self)
	if err == routing.ErrNotFound {
		return nil
	}
	return err
176
}