BitSwap协议是IPFS的数据交易模块,用来请求块和发送块到网络上的其他节点。主要有两个功能:
- 获取请求的Block
Wantmanager负责
- 有选择的发送被请求的Block
选择性由Decision Manager来决定
Bitswap
// Bitswap instances implement the bitswap protocol.
type Bitswap struct {
// the peermanager manages sending messages to peers in a way that
// wont block bitswap operation
wm *WantManager
// the engine is the bit of logic that decides who to send which blocks to
engine *decision.Engine
// network delivers messages on behalf of the session
network bsnet.BitSwapNetwork
// blockstore is the local database
// NB: ensure threadsafety
blockstore blockstore.Blockstore
// notifications engine for receiving new blocks and routing them to the
// appropriate user requests
notifications notifications.PubSub
// findKeys sends keys to a worker to find and connect to providers for them
findKeys chan *blockRequest
// 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
newBlocks chan *cid.Cid
// provideKeys directly feeds provide workers
provideKeys chan *cid.Cid
process process.Process
// Counters for various statistics
counterLk sync.Mutex
blocksRecvd int
dupBlocksRecvd int
dupDataRecvd uint64
blocksSent int
dataSent uint64
dataRecvd uint64
// Metrics interface metrics
dupMetric metrics.Histogram
allMetric metrics.Histogram
}
New
- Wantmanager Run()
- network setdelegate
- start workers
- close process
Workers
启动以下的Worker协程:
providerQueryManager
taskworker
rebroadcastWorker
provideCollector
provideWorker
WantManager
type WantManager struct {
// sync channels for Run loop
incoming chan []*bsmsg.Entry
connect chan peer.ID // notification channel for new peers connecting
disconnect chan peer.ID // notification channel for peers disconnecting
peerReqs chan chan []peer.ID // channel to request connected peers on
// synchronized by Run loop, only touch inside there
peers map[peer.ID]*msgQueue
wl *wantlist.ThreadSafe
network bsnet.BitSwapNetwork
ctx context.Context
cancel func()
wantlistGauge metrics.Gauge
sentHistogram metrics.Histogram
}
type msgPair struct {
to peer.ID
msg bsmsg.BitSwapMessage
}
type cancellation struct {
who peer.ID
blk *cid.Cid
}
- Run
处理WantManager中的Incoming Channel
处理重新广播的Entries
处理connect消息,为链接好的Peer生成Handler
处理disconnect消息,为断开连接的Peer做关闭处理
PeerReq 处理来自Peers的各种Request
Done 终止处理
type msgQueue struct {
p peer.ID
outlk sync.Mutex
out bsmsg.BitSwapMessage
network bsnet.BitSwapNetwork
sender bsnet.MessageSender
refcnt int
work chan struct{}
done chan struct{}
}
msgQueue有3个比较重要的函数:
- runQueue
遍历work channel,处理各种任务
- doWork
发送Wantlist
等待context或者mq的Done
如果sender发送失败,重开Sender
- openSender
链接msgQueue中的Peer,生成新的sender,存入msgQueue