dht_bootstrap.go 5.85 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
var DefaultBootstrapPeers []multiaddr.Multiaddr

Aarsh Shah's avatar
Aarsh Shah committed
18 19
var minRTBootstrapThreshold = 4

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
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)
	}
}

Aarsh Shah's avatar
Aarsh Shah committed
44
// BootstrapConfig runs cfg.Queries bootstrap queries every cfg.BucketPeriod.
45
func (dht *IpfsDHT) Bootstrap(ctx context.Context) error {
Aarsh Shah's avatar
Aarsh Shah committed
46 47 48 49 50 51 52 53 54 55
	triggerBootstrapFnc := func() {
		logger.Infof("triggerBootstrapFnc: RT only has %d peers which is less than the min threshold of %d, triggering self & bucket bootstrap",
			dht.routingTable.Size(), minRTBootstrapThreshold)

		if err := dht.selfWalk(ctx); err != nil {
			logger.Warningf("triggerBootstrapFnc: self walk: error: %s", err)
		}

		if err := dht.bootstrapBuckets(ctx); err != nil {
			logger.Warningf("triggerBootstrapFnc: bootstrap buckets: error bootstrapping: %s", err)
56 57
		}
	}
58

Aarsh Shah's avatar
Aarsh Shah committed
59 60 61
	// we should query for self periodically so we can discover closer peers
	go func() {
		for {
62
			err := dht.selfWalk(ctx)
Aarsh Shah's avatar
Aarsh Shah committed
63
			if err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
64
				logger.Warningf("self walk: error: %s", err)
Aarsh Shah's avatar
Aarsh Shah committed
65 66
			}
			select {
67
			case <-time.After(dht.bootstrapCfg.SelfQueryInterval):
Aarsh Shah's avatar
Aarsh Shah committed
68 69 70 71 72 73 74
			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
75
	go func() {
76
		for {
77
			err := dht.bootstrapBuckets(ctx)
Matt Joiner's avatar
Matt Joiner committed
78
			if err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
79
				logger.Warningf("bootstrap buckets: error bootstrapping: %s", err)
Matt Joiner's avatar
Matt Joiner committed
80
			}
81
			select {
82
			case <-time.After(dht.bootstrapCfg.RoutingTableScanInterval):
Aarsh Shah's avatar
Aarsh Shah committed
83 84
			case <-dht.triggerBootstrap:
				triggerBootstrapFnc()
Matt Joiner's avatar
Matt Joiner committed
85
			case <-ctx.Done():
86 87 88
				return
			}
		}
Matt Joiner's avatar
Matt Joiner committed
89
	}()
Aarsh Shah's avatar
Aarsh Shah committed
90

Matt Joiner's avatar
Matt Joiner committed
91
	return nil
Matt Joiner's avatar
Matt Joiner committed
92
}
vyzo's avatar
vyzo committed
93

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

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

	for bucketID, bucket := range buckets {
117
		if time.Since(bucket.RefreshedAt()) > dht.bootstrapCfg.BucketPeriod {
Aarsh Shah's avatar
Aarsh Shah committed
118 119 120 121
			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
122
				randPeerInBucket := dht.routingTable.GenRandPeerID(bucketID)
Aarsh Shah's avatar
Aarsh Shah committed
123 124 125

				// walk to the generated peer
				walkFnc := func(c context.Context) error {
126
					_, err := dht.FindPeer(ctx, randPeerInBucket)
Aarsh Shah's avatar
Aarsh Shah committed
127 128 129 130 131 132 133 134 135 136
					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
137
		}
Steven Allen's avatar
Steven Allen committed
138 139
	}

Aarsh Shah's avatar
Aarsh Shah committed
140 141 142 143 144 145
	// wait for all walks to finish & close the error channel
	go func() {
		wg.Wait()
		close(errChan)
	}()

Aarsh Shah's avatar
Aarsh Shah committed
146
	// accumulate errors from all go-routines. ensures wait group is completed by reading errChan until closure.
Aarsh Shah's avatar
Aarsh Shah committed
147 148 149 150 151 152 153
	var errStrings []string
	for err := range errChan {
		errStrings = append(errStrings, err.Error())
	}
	if len(errStrings) == 0 {
		return nil
	} else {
Aarsh Shah's avatar
Aarsh Shah committed
154 155 156 157 158 159 160 161 162 163 164
		return fmt.Errorf("errors encountered while running bootstrap on RT:\n%s", strings.Join(errStrings, "\n"))
	}
}

// Traverse the DHT toward the self ID
func (dht *IpfsDHT) selfWalk(ctx context.Context) error {
	queryCtx, cancel := context.WithTimeout(ctx, dht.bootstrapCfg.Timeout)
	defer cancel()
	_, err := dht.FindPeer(queryCtx, dht.self)
	if err == routing.ErrNotFound {
		return nil
Aarsh Shah's avatar
Aarsh Shah committed
165
	}
Aarsh Shah's avatar
Aarsh Shah committed
166
	return err
Aarsh Shah's avatar
Aarsh Shah committed
167 168
}

169 170 171
// synchronous bootstrap.
func (dht *IpfsDHT) bootstrapOnce(ctx context.Context) error {
	if err := dht.selfWalk(ctx); err != nil {
Aarsh Shah's avatar
Aarsh Shah committed
172 173
		return errors.Wrap(err, "failed bootstrap while searching for self")
	} else {
174
		return dht.bootstrapBuckets(ctx)
Aarsh Shah's avatar
Aarsh Shah committed
175
	}
176
}