dht_bootstrap.go 5.61 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"

Steven Allen's avatar
Steven Allen committed
10 11
	process "github.com/jbenet/goprocess"
	processctx "github.com/jbenet/goprocess/context"
12 13
	"github.com/libp2p/go-libp2p-core/routing"
	"github.com/multiformats/go-multiaddr"
Hector Sanjuan's avatar
Hector Sanjuan committed
14
	_ "github.com/multiformats/go-multiaddr-dns"
Aarsh Shah's avatar
Aarsh Shah committed
15
	"github.com/pkg/errors"
16 17
)

18 19
var DefaultBootstrapPeers []multiaddr.Multiaddr

Aarsh Shah's avatar
Aarsh Shah committed
20 21
var minRTBootstrapThreshold = 4

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

Steven Allen's avatar
Steven Allen committed
46
// Start the bootstrap worker.
Steven Allen's avatar
Steven Allen committed
47 48 49 50
func (dht *IpfsDHT) startBootstrapping() error {
	// scan the RT table periodically & do a random walk on k-buckets that haven't been queried since the given bucket period
	dht.proc.Go(func(proc process.Process) {
		ctx := processctx.OnClosingContext(proc)
51

52
		scanInterval := time.NewTicker(dht.bootstrapPeriod)
Steven Allen's avatar
Steven Allen committed
53
		defer scanInterval.Stop()
Aarsh Shah's avatar
Aarsh Shah committed
54

55
		// run bootstrap if option is set
56 57
		if dht.autoBootstrap {
			dht.doBootstrap(ctx)
58
		} else {
Steven Allen's avatar
Steven Allen committed
59
			// disable the "auto-bootstrap" ticker so that no more ticks are sent to this channel
60
			scanInterval.Stop()
61
		}
Steven Allen's avatar
Steven Allen committed
62

63
		for {
64
			select {
65
			case <-scanInterval.C:
66
			case <-dht.triggerBootstrap:
Steven Allen's avatar
Steven Allen committed
67
				logger.Infof("triggering a bootstrap: RT has %d peers", dht.routingTable.Size())
Matt Joiner's avatar
Matt Joiner committed
68
			case <-ctx.Done():
69 70
				return
			}
71
			dht.doBootstrap(ctx)
72
		}
Steven Allen's avatar
Steven Allen committed
73
	})
Aarsh Shah's avatar
Aarsh Shah committed
74

Matt Joiner's avatar
Matt Joiner committed
75
	return nil
Matt Joiner's avatar
Matt Joiner committed
76
}
vyzo's avatar
vyzo committed
77

78 79 80
func (dht *IpfsDHT) doBootstrap(ctx context.Context) {
	if err := dht.selfWalk(ctx); err != nil {
		logger.Warningf("error while bootstrapping self: %s", err)
81 82
	}
	if err := dht.bootstrapBuckets(ctx); err != nil {
83
		logger.Warningf("error while bootstrapping buckets: %s", err)
84 85 86
	}
}

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

Aarsh Shah's avatar
Aarsh Shah committed
105 106 107 108 109
	buckets := dht.routingTable.GetAllBuckets()
	var wg sync.WaitGroup
	errChan := make(chan error)

	for bucketID, bucket := range buckets {
110
		if time.Since(bucket.RefreshedAt()) > dht.bootstrapPeriod {
Aarsh Shah's avatar
Aarsh Shah committed
111 112 113 114
			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
115
				randPeerInBucket := dht.routingTable.GenRandPeerID(bucketID)
Aarsh Shah's avatar
Aarsh Shah committed
116 117 118

				// walk to the generated peer
				walkFnc := func(c context.Context) error {
119
					_, err := dht.FindPeer(ctx, randPeerInBucket)
Aarsh Shah's avatar
Aarsh Shah committed
120 121 122 123 124 125 126 127 128 129
					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
130
		}
Steven Allen's avatar
Steven Allen committed
131 132
	}

Aarsh Shah's avatar
Aarsh Shah committed
133 134 135 136 137 138
	// wait for all walks to finish & close the error channel
	go func() {
		wg.Wait()
		close(errChan)
	}()

Aarsh Shah's avatar
Aarsh Shah committed
139
	// accumulate errors from all go-routines. ensures wait group is completed by reading errChan until closure.
Aarsh Shah's avatar
Aarsh Shah committed
140 141 142 143 144 145 146
	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
147 148 149 150 151 152
		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 {
153
	queryCtx, cancel := context.WithTimeout(ctx, dht.bootstrapTimeout)
Aarsh Shah's avatar
Aarsh Shah committed
154 155 156 157
	defer cancel()
	_, err := dht.FindPeer(queryCtx, dht.self)
	if err == routing.ErrNotFound {
		return nil
Aarsh Shah's avatar
Aarsh Shah committed
158
	}
Aarsh Shah's avatar
Aarsh Shah committed
159
	return err
Aarsh Shah's avatar
Aarsh Shah committed
160 161
}

Steven Allen's avatar
Steven Allen committed
162 163 164 165 166
// Bootstrap tells the DHT to get into a bootstrapped state.
//
// Note: the context is ignored.
func (dht *IpfsDHT) Bootstrap(_ context.Context) error {
	select {
167
	case dht.triggerBootstrap <- struct{}{}:
Steven Allen's avatar
Steven Allen committed
168
	default:
Aarsh Shah's avatar
Aarsh Shah committed
169
	}
Steven Allen's avatar
Steven Allen committed
170
	return nil
171
}