bitswap.go 18.4 KB
Newer Older
1
// Package bitswap implements the DMS3 exchange interface with the BitSwap
Brian Tiger Chow's avatar
Brian Tiger Chow committed
2
// bilateral exchange protocol.
3 4 5
package bitswap

import (
6
	"context"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
7
	"errors"
8
	"fmt"
dirkmc's avatar
dirkmc committed
9

10
	"sync"
Jeromy's avatar
Jeromy committed
11 12
	"time"

13 14
	delay "gitlab.dms3.io/dms3/go-dms3-delay"

Jeromy's avatar
Jeromy committed
15 16
	process "github.com/jbenet/goprocess"
	procctx "github.com/jbenet/goprocess/context"
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
	deciface "gitlab.dms3.io/dms3/go-bitswap/decision"
	bsbpm "gitlab.dms3.io/dms3/go-bitswap/internal/blockpresencemanager"
	decision "gitlab.dms3.io/dms3/go-bitswap/internal/decision"
	bsgetter "gitlab.dms3.io/dms3/go-bitswap/internal/getter"
	bsmq "gitlab.dms3.io/dms3/go-bitswap/internal/messagequeue"
	notifications "gitlab.dms3.io/dms3/go-bitswap/internal/notifications"
	bspm "gitlab.dms3.io/dms3/go-bitswap/internal/peermanager"
	bspqm "gitlab.dms3.io/dms3/go-bitswap/internal/providerquerymanager"
	bssession "gitlab.dms3.io/dms3/go-bitswap/internal/session"
	bssim "gitlab.dms3.io/dms3/go-bitswap/internal/sessioninterestmanager"
	bssm "gitlab.dms3.io/dms3/go-bitswap/internal/sessionmanager"
	bsspm "gitlab.dms3.io/dms3/go-bitswap/internal/sessionpeermanager"
	bsmsg "gitlab.dms3.io/dms3/go-bitswap/message"
	bsnet "gitlab.dms3.io/dms3/go-bitswap/network"
	blocks "gitlab.dms3.io/dms3/go-block-format"
	cid "gitlab.dms3.io/dms3/go-cid"
	blockstore "gitlab.dms3.io/dms3/go-dms3-blockstore"
	exchange "gitlab.dms3.io/dms3/go-dms3-exchange-interface"
	logging "gitlab.dms3.io/dms3/go-log"
	metrics "gitlab.dms3.io/dms3/go-metrics-interface"
	peer "gitlab.dms3.io/p2p/go-p2p-core/peer"
38 39
)

Jeromy's avatar
Jeromy committed
40
var log = logging.Logger("bitswap")
41
var sflog = log.Desugar()
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42

43 44
var _ exchange.SessionExchange = (*Bitswap)(nil)

Brian Tiger Chow's avatar
Brian Tiger Chow committed
45
const (
46
	// these requests take at _least_ two minutes at the moment.
47 48
	provideTimeout         = time.Minute * 3
	defaultProvSearchDelay = time.Second
49 50 51

	// Number of concurrent workers in decision engine that process requests to the blockstore
	defaulEngineBlockstoreWorkerCount = 128
Jeromy's avatar
Jeromy committed
52
)
53

Jeromy's avatar
Jeromy committed
54
var (
55 56 57 58
	// HasBlockBufferSize is the buffer size of the channel for new blocks
	// that need to be provided. They should get pulled over by the
	// provideCollector even before they are actually provided.
	// TODO: Does this need to be this large givent that?
59 60
	HasBlockBufferSize    = 256
	provideKeysBufferSize = 2048
Steven Allen's avatar
Steven Allen committed
61
	provideWorkerMax      = 6
62 63 64

	// the 1<<18+15 is to observe old file chunks that are 1<<18 + 14 in size
	metricsBuckets = []float64{1 << 6, 1 << 10, 1 << 14, 1 << 18, 1<<18 + 15, 1 << 22}
Brian Tiger Chow's avatar
Brian Tiger Chow committed
65
)
Jeromy's avatar
Jeromy committed
66

67 68 69 70 71 72 73 74 75 76 77
// Option defines the functional option type that can be used to configure
// bitswap instances
type Option func(*Bitswap)

// ProvideEnabled is an option for enabling/disabling provide announcements
func ProvideEnabled(enabled bool) Option {
	return func(bs *Bitswap) {
		bs.provideEnabled = enabled
	}
}

78 79 80 81 82 83 84 85 86 87 88 89 90 91
// ProviderSearchDelay overwrites the global provider search delay
func ProviderSearchDelay(newProvSearchDelay time.Duration) Option {
	return func(bs *Bitswap) {
		bs.provSearchDelay = newProvSearchDelay
	}
}

// RebroadcastDelay overwrites the global provider rebroadcast delay
func RebroadcastDelay(newRebroadcastDelay delay.D) Option {
	return func(bs *Bitswap) {
		bs.rebroadcastDelay = newRebroadcastDelay
	}
}

92 93 94 95 96 97 98 99 100 101 102
// EngineBlockstoreWorkerCount sets the number of worker threads used for
// blockstore operations in the decision engine
func EngineBlockstoreWorkerCount(count int) Option {
	if count <= 0 {
		panic(fmt.Sprintf("Engine blockstore worker count is %d but must be > 0", count))
	}
	return func(bs *Bitswap) {
		bs.engineBstoreWorkerCount = count
	}
}

103 104 105 106 107 108 109 110 111 112 113
// SetSendDontHaves indicates what to do when the engine receives a want-block
// for a block that is not in the blockstore. Either
// - Send a DONT_HAVE message
// - Simply don't respond
// This option is only used for testing.
func SetSendDontHaves(send bool) Option {
	return func(bs *Bitswap) {
		bs.engine.SetSendDontHaves(send)
	}
}

114 115 116
// Configures the engine to use the given score decision logic.
func WithScoreLedger(scoreLedger deciface.ScoreLedger) Option {
	return func(bs *Bitswap) {
117
		bs.engineScoreLedger = scoreLedger
118 119 120
	}
}

Brian Tiger Chow's avatar
Brian Tiger Chow committed
121 122
// New initializes a BitSwap instance that communicates over the provided
// BitSwapNetwork. This function registers the returned instance as the network
123
// delegate. Runs until context is cancelled or bitswap.Close is called.
Łukasz Magiera's avatar
Łukasz Magiera committed
124
func New(parent context.Context, network bsnet.BitSwapNetwork,
125
	bstore blockstore.Blockstore, options ...Option) exchange.Interface {
126

127 128
	// important to use provided parent context (since it may include important
	// loggable data). It's probably not a good idea to allow bitswap to be
129
	// coupled to the concerns of the dms3 daemon in this way.
130 131 132 133
	//
	// FIXME(btc) Now that bitswap manages itself using a process, it probably
	// shouldn't accept a context anymore. Clients should probably use Close()
	// exclusively. We should probably find another way to share logging data
134
	ctx, cancelFunc := context.WithCancel(parent)
135
	ctx = metrics.CtxSubScope(ctx, "bitswap")
136
	dupHist := metrics.NewCtx(ctx, "recv_dup_blocks_bytes", "Summary of duplicate"+
137
		" data blocks recived").Histogram(metricsBuckets)
138
	allHist := metrics.NewCtx(ctx, "recv_all_blocks_bytes", "Summary of all"+
139
		" data blocks recived").Histogram(metricsBuckets)
140

141 142 143
	sentHistogram := metrics.NewCtx(ctx, "sent_all_blocks_bytes", "Histogram of blocks sent by"+
		" this bitswap").Histogram(metricsBuckets)

144 145 146 147
	px := process.WithTeardown(func() error {
		return nil
	})

148 149
	// onDontHaveTimeout is called when a want-block is sent to a peer that
	// has an old version of Bitswap that doesn't support DONT_HAVE messages,
150
	// or when no response is received within a timeout.
Dirk McCormick's avatar
Dirk McCormick committed
151
	var sm *bssm.SessionManager
152
	onDontHaveTimeout := func(p peer.ID, dontHaves []cid.Cid) {
Dirk McCormick's avatar
Dirk McCormick committed
153 154
		// Simulate a message arriving with DONT_HAVEs
		sm.ReceiveFrom(ctx, p, nil, nil, dontHaves)
155
	}
156
	peerQueueFactory := func(ctx context.Context, p peer.ID) bspm.PeerQueue {
157
		return bsmq.New(ctx, p, network, onDontHaveTimeout)
158 159
	}

dirkmc's avatar
dirkmc committed
160 161 162
	sim := bssim.New()
	bpm := bsbpm.New()
	pm := bspm.New(ctx, peerQueueFactory, network.Self())
163 164
	pqm := bspqm.New(ctx, network)

165 166 167 168 169
	sessionFactory := func(
		sessctx context.Context,
		sessmgr bssession.SessionManager,
		id uint64,
		spm bssession.SessionPeerManager,
dirkmc's avatar
dirkmc committed
170 171 172
		sim *bssim.SessionInterestManager,
		pm bssession.PeerManager,
		bpm *bsbpm.BlockPresenceManager,
173
		notif notifications.PubSub,
174
		provSearchDelay time.Duration,
dirkmc's avatar
dirkmc committed
175 176
		rebroadcastDelay delay.D,
		self peer.ID) bssm.Session {
177
		return bssession.New(sessctx, sessmgr, id, spm, pqm, sim, pm, bpm, notif, provSearchDelay, rebroadcastDelay, self)
178
	}
dirkmc's avatar
dirkmc committed
179
	sessionPeerManagerFactory := func(ctx context.Context, id uint64) bssession.SessionPeerManager {
180
		return bsspm.New(id, network.ConnectionManager())
181
	}
182
	notif := notifications.New()
Dirk McCormick's avatar
Dirk McCormick committed
183
	sm = bssm.New(ctx, sessionFactory, sim, sessionPeerManagerFactory, bpm, pm, notif, network.Self())
184

185
	bs := &Bitswap{
186 187 188 189 190 191 192
		blockstore:              bstore,
		network:                 network,
		process:                 px,
		newBlocks:               make(chan cid.Cid, HasBlockBufferSize),
		provideKeys:             make(chan cid.Cid, provideKeysBufferSize),
		pm:                      pm,
		pqm:                     pqm,
193 194 195 196 197 198 199 200 201 202 203
		sm:                      sm,
		sim:                     sim,
		notif:                   notif,
		counters:                new(counters),
		dupMetric:               dupHist,
		allMetric:               allHist,
		sentHistogram:           sentHistogram,
		provideEnabled:          true,
		provSearchDelay:         defaultProvSearchDelay,
		rebroadcastDelay:        delay.Fixed(time.Minute),
		engineBstoreWorkerCount: defaulEngineBlockstoreWorkerCount,
204 205 206 207 208
	}

	// apply functional options before starting and running bitswap
	for _, option := range options {
		option(bs)
209
	}
210

211 212 213
	// Set up decision engine
	bs.engine = decision.NewEngine(bstore, bs.engineBstoreWorkerCount, network.ConnectionManager(), network.Self(), bs.engineScoreLedger)

214
	bs.pqm.Startup()
Brian Tiger Chow's avatar
Brian Tiger Chow committed
215
	network.SetDelegate(bs)
216

217
	// Start up bitswaps async worker routines
218
	bs.startWorkers(ctx, px)
219
	bs.engine.StartWorkers(ctx, px)
220 221 222 223 224

	// bind the context and process.
	// do it over here to avoid closing before all setup is done.
	go func() {
		<-px.Closing() // process closes first
225
		sm.Shutdown()
226
		cancelFunc()
227
		notif.Shutdown()
228 229 230
	}()
	procctx.CloseAfterContext(px, ctx) // parent cancelled first

231 232 233
	return bs
}

234 235
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
dirkmc's avatar
dirkmc committed
236 237
	pm *bspm.PeerManager

238 239 240
	// the provider query manager manages requests to find providers
	pqm *bspqm.ProviderQueryManager

241 242
	// the engine is the bit of logic that decides who to send which blocks to
	engine *decision.Engine
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
243

244 245
	// network delivers messages on behalf of the session
	network bsnet.BitSwapNetwork
246 247 248 249 250

	// blockstore is the local database
	// NB: ensure threadsafety
	blockstore blockstore.Blockstore

251 252 253
	// manages channels of outgoing blocks for sessions
	notif notifications.PubSub

254 255 256
	// newBlocks is a channel for newly added blocks to be provided to the
	// network.  blocks pushed down this channel get buffered and fed to the
	// provideKeys channel later on to avoid too much network activity
257
	newBlocks chan cid.Cid
258
	// provideKeys directly feeds provide workers
259
	provideKeys chan cid.Cid
260

261 262 263
	process process.Process

	// Counters for various statistics
264 265
	counterLk sync.Mutex
	counters  *counters
266 267

	// Metrics interface metrics
268 269 270
	dupMetric     metrics.Histogram
	allMetric     metrics.Histogram
	sentHistogram metrics.Histogram
Jeromy's avatar
Jeromy committed
271

Tomasz Zdybał's avatar
Tomasz Zdybał committed
272 273 274
	// External statistics interface
	wiretap WireTap

dirkmc's avatar
dirkmc committed
275
	// the SessionManager routes requests to interested sessions
276
	sm *bssm.SessionManager
277

dirkmc's avatar
dirkmc committed
278 279 280 281
	// the SessionInterestManager keeps track of which sessions are interested
	// in which CIDs
	sim *bssim.SessionInterestManager

282 283
	// whether or not to make provide announcements
	provideEnabled bool
284 285 286 287 288 289

	// how long to wait before looking for providers in a session
	provSearchDelay time.Duration

	// how often to rebroadcast providing requests to find more optimized providers
	rebroadcastDelay delay.D
290 291 292 293 294 295

	// how many worker threads to start for decision engine blockstore worker
	engineBstoreWorkerCount int

	// the score ledger used by the decision engine
	engineScoreLedger deciface.ScoreLedger
296 297
}

298 299 300 301 302 303 304 305 306 307
type counters struct {
	blocksRecvd    uint64
	dupBlocksRecvd uint64
	dupDataRecvd   uint64
	blocksSent     uint64
	dataSent       uint64
	dataRecvd      uint64
	messagesRecvd  uint64
}

308
// GetBlock attempts to retrieve a particular block from peers within the
309
// deadline enforced by the context.
310
func (bs *Bitswap) GetBlock(parent context.Context, k cid.Cid) (blocks.Block, error) {
311
	return bsgetter.SyncGetBlock(parent, k, bs.GetBlocks)
312 313
}

314 315
// WantlistForPeer returns the currently understood list of blocks requested by a
// given peer.
316 317
func (bs *Bitswap) WantlistForPeer(p peer.ID) []cid.Cid {
	var out []cid.Cid
318
	for _, e := range bs.engine.WantlistForPeer(p) {
319
		out = append(out, e.Cid)
320 321 322 323
	}
	return out
}

324 325
// LedgerForPeer returns aggregated data about blocks swapped and communication
// with a given peer.
326 327 328 329
func (bs *Bitswap) LedgerForPeer(p peer.ID) *decision.Receipt {
	return bs.engine.LedgerForPeer(p)
}

330 331 332 333 334 335 336
// GetBlocks returns a channel where the caller may receive blocks that
// correspond to the provided |keys|. Returns an error if BitSwap is unable to
// begin this request within the deadline enforced by the context.
//
// NB: Your request remains open until the context expires. To conserve
// resources, provide a context with a reasonably short deadline (ie. not one
// that lasts throughout the lifetime of the server)
337
func (bs *Bitswap) GetBlocks(ctx context.Context, keys []cid.Cid) (<-chan blocks.Block, error) {
338
	session := bs.sm.NewSession(ctx, bs.provSearchDelay, bs.rebroadcastDelay)
339
	return session.GetBlocks(ctx, keys)
Jeromy's avatar
Jeromy committed
340 341
}

Łukasz Magiera's avatar
Łukasz Magiera committed
342
// HasBlock announces the existence of a block to this bitswap service. The
343
// service will potentially notify its peers.
344
func (bs *Bitswap) HasBlock(blk blocks.Block) error {
dirkmc's avatar
dirkmc committed
345
	return bs.receiveBlocksFrom(context.Background(), "", []blocks.Block{blk}, nil, nil)
346 347 348 349 350 351
}

// TODO: Some of this stuff really only needs to be done when adding a block
// from the user, not when receiving it from the network.
// In case you run `git blame` on this comment, I'll save you some time: ask
// @whyrusleeping, I don't know the answers you seek.
dirkmc's avatar
dirkmc committed
352
func (bs *Bitswap) receiveBlocksFrom(ctx context.Context, from peer.ID, blks []blocks.Block, haves []cid.Cid, dontHaves []cid.Cid) error {
353 354 355 356 357
	select {
	case <-bs.process.Closing():
		return errors.New("bitswap is closed")
	default:
	}
358

359 360 361 362
	wanted := blks

	// If blocks came from the network
	if from != "" {
dirkmc's avatar
dirkmc committed
363 364 365 366
		var notWanted []blocks.Block
		wanted, notWanted = bs.sim.SplitWantedUnwanted(blks)
		for _, b := range notWanted {
			log.Debugf("[recv] block not in wantlist; cid=%s, peer=%s", b.Cid(), from)
367 368 369 370
		}
	}

	// Put wanted blocks into blockstore
dirkmc's avatar
dirkmc committed
371 372 373 374 375 376
	if len(wanted) > 0 {
		err := bs.blockstore.PutMany(wanted)
		if err != nil {
			log.Errorf("Error writing %d blocks to datastore: %s", len(wanted), err)
			return err
		}
377
	}
378

379 380 381 382 383
	// NOTE: There exists the possiblity for a race condition here.  If a user
	// creates a node, then adds it to the dagservice while another goroutine
	// is waiting on a GetBlock for that object, they will receive a reference
	// to the same node. We should address this soon, but i'm not going to do
	// it now as it requires more thought and isnt causing immediate problems.
Jeromy's avatar
Jeromy committed
384

385 386 387 388 389
	allKs := make([]cid.Cid, 0, len(blks))
	for _, b := range blks {
		allKs = append(allKs, b.Cid())
	}

390 391 392 393 394 395 396
	// If the message came from the network
	if from != "" {
		// Inform the PeerManager so that we can calculate per-peer latency
		combined := make([]cid.Cid, 0, len(allKs)+len(haves)+len(dontHaves))
		combined = append(combined, allKs...)
		combined = append(combined, haves...)
		combined = append(combined, dontHaves...)
Dirk McCormick's avatar
Dirk McCormick committed
397
		bs.pm.ResponseReceived(from, combined)
398 399
	}

400
	// Send all block keys (including duplicates) to any sessions that want them.
401
	// (The duplicates are needed by sessions for accounting purposes)
Dirk McCormick's avatar
Dirk McCormick committed
402
	bs.sm.ReceiveFrom(ctx, from, allKs, haves, dontHaves)
403

dirkmc's avatar
dirkmc committed
404 405
	// Send wanted blocks to decision engine
	bs.engine.ReceiveFrom(from, wanted, haves)
406

407
	// Publish the block to any Bitswap clients that had requested blocks.
dirkmc's avatar
dirkmc committed
408
	// (the sessions use this pubsub mechanism to inform clients of incoming
409 410 411 412 413
	// blocks)
	for _, b := range wanted {
		bs.notif.Publish(b)
	}

414
	// If the reprovider is enabled, send wanted blocks to reprovider
415
	if bs.provideEnabled {
dirkmc's avatar
dirkmc committed
416
		for _, blk := range wanted {
417
			select {
dirkmc's avatar
dirkmc committed
418
			case bs.newBlocks <- blk.Cid():
419 420 421 422
				// send block off to be reprovided
			case <-bs.process.Closing():
				return bs.process.Close()
			}
423
		}
424
	}
425

426 427
	if from != "" {
		for _, b := range wanted {
428
			log.Debugw("Bitswap.GetBlockRequest.End", "cid", b.Cid())
429 430 431
		}
	}

432
	return nil
433 434
}

435 436
// ReceiveMessage is called by the network interface when a new message is
// received.
437
func (bs *Bitswap) ReceiveMessage(ctx context.Context, p peer.ID, incoming bsmsg.BitSwapMessage) {
Steven Allen's avatar
Steven Allen committed
438 439 440
	bs.counterLk.Lock()
	bs.counters.messagesRecvd++
	bs.counterLk.Unlock()
Jeromy's avatar
Jeromy committed
441

Jeromy's avatar
Jeromy committed
442 443
	// This call records changes to wantlists, blocks received,
	// and number of bytes transfered.
444
	bs.engine.MessageReceived(ctx, p, incoming)
Jeromy's avatar
Jeromy committed
445 446
	// TODO: this is bad, and could be easily abused.
	// Should only track *useful* messages in ledger
447

Tomasz Zdybał's avatar
Tomasz Zdybał committed
448 449 450 451
	if bs.wiretap != nil {
		bs.wiretap.MessageReceived(p, incoming)
	}

452 453
	iblocks := incoming.Blocks()

dirkmc's avatar
dirkmc committed
454 455 456 457 458
	if len(iblocks) > 0 {
		bs.updateReceiveCounters(iblocks)
		for _, b := range iblocks {
			log.Debugf("[recv] block; cid=%s, peer=%s", b.Cid(), p)
		}
459
	}
460

dirkmc's avatar
dirkmc committed
461 462 463 464 465 466
	haves := incoming.Haves()
	dontHaves := incoming.DontHaves()
	if len(iblocks) > 0 || len(haves) > 0 || len(dontHaves) > 0 {
		// Process blocks
		err := bs.receiveBlocksFrom(ctx, p, iblocks, haves, dontHaves)
		if err != nil {
467
			log.Warnf("ReceiveMessage recvBlockFrom error: %s", err)
dirkmc's avatar
dirkmc committed
468 469
			return
		}
470
	}
471 472 473 474 475 476 477
}

func (bs *Bitswap) updateReceiveCounters(blocks []blocks.Block) {
	// Check which blocks are in the datastore
	// (Note: any errors from the blockstore are simply logged out in
	// blockstoreHas())
	blocksHas := bs.blockstoreHas(blocks)
478

479 480 481
	bs.counterLk.Lock()
	defer bs.counterLk.Unlock()

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499
	// Do some accounting for each block
	for i, b := range blocks {
		has := blocksHas[i]

		blkLen := len(b.RawData())
		bs.allMetric.Observe(float64(blkLen))
		if has {
			bs.dupMetric.Observe(float64(blkLen))
		}

		c := bs.counters

		c.blocksRecvd++
		c.dataRecvd += uint64(blkLen)
		if has {
			c.dupBlocksRecvd++
			c.dupDataRecvd += uint64(blkLen)
		}
500 501 502
	}
}

503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
func (bs *Bitswap) blockstoreHas(blks []blocks.Block) []bool {
	res := make([]bool, len(blks))

	wg := sync.WaitGroup{}
	for i, block := range blks {
		wg.Add(1)
		go func(i int, b blocks.Block) {
			defer wg.Done()

			has, err := bs.blockstore.Has(b.Cid())
			if err != nil {
				log.Infof("blockstore.Has error: %s", err)
				has = false
			}

			res[i] = has
		}(i, block)
	}
	wg.Wait()

	return res
}

526 527
// PeerConnected is called by the network interface
// when a peer initiates a new connection to bitswap.
528
func (bs *Bitswap) PeerConnected(p peer.ID) {
Dirk McCormick's avatar
Dirk McCormick committed
529
	bs.pm.Connected(p)
530
	bs.engine.PeerConnected(p)
531 532
}

533 534
// PeerDisconnected is called by the network interface when a peer
// closes a connection
535
func (bs *Bitswap) PeerDisconnected(p peer.ID) {
Dirk McCormick's avatar
Dirk McCormick committed
536
	bs.pm.Disconnected(p)
537
	bs.engine.PeerDisconnected(p)
538 539
}

540 541
// ReceiveError is called by the network interface when an error happens
// at the network layer. Currently just logs error.
542
func (bs *Bitswap) ReceiveError(err error) {
543
	log.Infof("Bitswap ReceiveError: %s", err)
544 545
	// TODO log the network error
	// TODO bubble the network error up to the parent context/error logger
546 547
}

548
// Close is called to shutdown Bitswap
549
func (bs *Bitswap) Close() error {
550
	return bs.process.Close()
551
}
552

553 554
// GetWantlist returns the current local wantlist (both want-blocks and
// want-haves).
555
func (bs *Bitswap) GetWantlist() []cid.Cid {
dirkmc's avatar
dirkmc committed
556 557 558
	return bs.pm.CurrentWants()
}

559 560 561 562 563
// GetWantBlocks returns the current list of want-blocks.
func (bs *Bitswap) GetWantBlocks() []cid.Cid {
	return bs.pm.CurrentWantBlocks()
}

dirkmc's avatar
dirkmc committed
564 565 566
// GetWanthaves returns the current list of want-haves.
func (bs *Bitswap) GetWantHaves() []cid.Cid {
	return bs.pm.CurrentWantHaves()
567
}
568

569
// IsOnline is needed to match go-dms3-exchange-interface
570 571 572
func (bs *Bitswap) IsOnline() bool {
	return true
}
573

574 575 576 577 578 579
// NewSession generates a new Bitswap session. You should use this, rather
// that calling Bitswap.GetBlocks, any time you intend to do several related
// block requests in a row. The session returned will have it's own GetBlocks
// method, but the session will use the fact that the requests are related to
// be more efficient in its requests to peers. If you are using a session
// from go-blockservice, it will create a bitswap session automatically.
580
func (bs *Bitswap) NewSession(ctx context.Context) exchange.Fetcher {
581
	return bs.sm.NewSession(ctx, bs.provSearchDelay, bs.rebroadcastDelay)
582
}