Skip to content

Commit c889e0b

Browse files
Bitswap 1.2.0 (#269)
* feat: rework bitswap spec to focus on the protocol layer and describe the existing versions of the bitswap protocol Co-authored-by: Gus Eggert <gus@gus.dev>
1 parent 0b123fa commit c889e0b

File tree

1 file changed

+129
-133
lines changed

1 file changed

+129
-133
lines changed

BITSWAP.md

+129-133
Original file line numberDiff line numberDiff line change
@@ -1,202 +1,198 @@
1-
# ![](https://img.shields.io/badge/status-wip-orange.svg?style=flat-square) Bitswap
1+
# ![Status: WIP](https://img.shields.io/badge/status-wip-orange.svg?style=flat-square) Bitswap
22

3-
**Authors(s)**:
3+
**Author(s)**:
4+
- Adin Schmahmann
45
- David Dias
56
- Jeromy Johnson
67
- Juan Benet
78

8-
**Maintainers(s)**:
9+
**Maintainer(s)**:
910

1011
* * *
1112

1213
**Abstract**
1314

14-
Bitswap is the data trading module for IPFS. Its purpose is to request blocks from and send blocks to other peers in the network. Bitswap has two primary jobs:
15+
Bitswap is a data exchange protocol for sending and receiving content addressed blocks of data. Bitswap has two primary jobs:
1516
1. Attempt to acquire blocks from the network that have been requested by the client.
16-
2. Judiciously (though strategically) send blocks in its possession to other peers who want them.
17+
2. Send blocks in its possession to other peers who want them.
1718

18-
# Organization of this document
19+
## Organization of this document
1920

2021
- [Introduction](#introduction)
21-
- [Subsystems](#subsystems)
22-
- [Implementation Details](#implementation-details)
23-
- [API Spec](#api-spec)
22+
- [Bitswap Protocol Versions](#bitswap-protocol-versions)
23+
- [Bitswap 1.0.0](#bitswap-100)
24+
- [Bitswap 1.1.0](#bitswap-110)
25+
- [Bitswap 1.2.0](#bitswap-120)
2426
- [Implementations](#implementations)
2527

26-
# Introduction
28+
## Introduction
2729

28-
Bitswap is IPFS’s central block exchange protocol. It handles the requests made by an IPFS user, human, or application to fetch data blocks from the network. It interacts with other Bitswap agents present in other IPFS nodes, exchanging (fetching + serving) blocks as it needs.
30+
Bitswap is a message-based protocol, as opposed to request-response. All messages contain wantlists, and/or blocks.
31+
Upon receiving a wantlist, a Bitswap server should eventually process and respond to the requester with either information about the block or the block itself.
32+
Upon receiving blocks, the client should send a `Cancel` notification to peers that have asked for the data, signifying that the client no longer wants the block.
2933

30-
Bitswap is a message based protocol, as opposed to response-reply. All messages contain wantlists, or blocks. Upon receiving a wantlist, an IPFS node should consider sending out wanted blocks if it has them. Upon receiving blocks, the node should send out a notification called a `Cancel` signifying that they no longer want the block. At the protocol level, Bitswap is very simple.
34+
Bitswap aims to be a simple protocol, so that implementations can balance aspects such as throughput, latency, fairness, memory usage, etc. for their specific requirements.
3135

32-
While Bitswap is a relatively simple protocol, a time- and memory- performant implementation requires that many details be carefully thought out. We aim to document these details here so that future implementers may build upon the knowledge gathered over the several iterations of Bitswap.
36+
## Bitswap Protocol Versions
3337

34-
# Subsystems
38+
There are multiple Bitswap versions and more may evolve over time. We give brief overviews as to the changes behind each protocol version.
3539

36-
There are two primary flows that Bitswap manages: requesting blocks from and serving blocks to peers. Block requests are primarily mediated by the want-manager, which tells our peers whenever we want a new block. Serving blocks is primarily handled by the decision engine, which decides how resources should be allocated among our peers.
40+
- `/ipfs/bitswap/1.0.0` - Initial version
41+
- `/ipfs/bitswap/1.1.0` - Support CIDv1
42+
- `/ipfs/bitswap/1.2.0` - Support Wantlist Have's and Have/DontHave responses
3743

38-
The subsystems involved in these flows are detailed in the following subsections.
44+
## Block Sizes
3945

40-
**TODO**: Update graphic
46+
Bitswap implementations must support sending and receiving individual blocks of sizes less than or equal to 2MiB. Handling blocks larger than 2MiB is not recommended so as to keep compatibility with implementations which only support up to 2MiB.
4147

42-
![](https://cloud.githubusercontent.com/assets/1211152/21071077/4620387a-be4a-11e6-895c-aa8f2b06aa4e.png)
48+
## Bitswap 1.0.0
4349

44-
## Types
50+
### Bitswap 1.0.0: Interaction Pattern
4551

46-
The following types are used in the descriptions of the Bitswap subsystems.
52+
Given that a client C wants to fetch data from some server S:
4753

48-
- `CID`: A [content-addressed identifier](https://github.com/ipld/cid) that refers to a particular `Block`.
49-
- `Peer`: Another Bitswap instance that we are connected to.
50-
- `Block`: A binary blob.
51-
- `Message`: A Bitswap message.
52-
- `Entry`: A wantlist entry that may be included in a Message when adding/removing a particular `CID` from our wantlist. Contains:
53-
- `CID` referring to a particular block.
54-
- `Priority` relative priority with which the user wants `CID` (relevant only if `Cancel` is not true).
55-
- `Cancel` is a boolean representing whether this `Entry` is meant to remove `CID` from our wantlist.
56-
- `Ledger`: A record of the aggregate data exchanged between two peers. Each peer stores one `Ledger` for each of their peers.
54+
1. C sends a message to S for the blocks it wants, via a stream `s_want`
55+
1. C may either send a complete wantlist, or an update to an outstanding wantlist
56+
2. C may reuse this stream to send new wants
57+
2. S sends back blocks on a stream `s_receive`. S may reuse this stream to send back subsequent responses.
58+
1. S should respect the relative priority of wantlist requests from C, with wants that have higher `priority` values being responded to first.
59+
3. When C no longer needs a block it previously asked for, it should send a `Cancel` message for that block to all peers from which it has not received a response about that block
5760

58-
### Bitswap Message
61+
### Bitswap 1.0.0: Message
5962

6063
A single Bitswap message may contain any of the following content:
6164

62-
1. The sender’s wantlist. This wantlist may either be the sender’s complete wantlist or just the changes to the sender’s wantlist that the receiver needs to know.
63-
2. Data blocks. These are meant to be blocks that the receiver has requested (i.e., blocks that are on the receiver’s wantlist as far as the sender is aware at the time of sending).
65+
1. The sender’s wantlist. This wantlist may either be the sender’s complete wantlist or just the changes to the sender’s wantlist that the receiver needs to know.
66+
2. Data blocks. These are meant to be blocks that the receiver has requested (i.e., blocks that are on the receiver’s wantlist as far as the sender is aware at the time of sending).
6467

65-
#### Wire Format
68+
#### Bitswap 1.0.0: Wire Format
6669

67-
The wire format for Bitswap is simply a stream of Bitswap messages. The following protobuf describes the form of these messages.
70+
The wire format for Bitswap is simply a stream of Bitswap messages. The following protobuf describes the form of these messages. Note: all protobufs are described using proto3 syntax.
6871

69-
```
72+
```protobuf
7073
message Message {
7174
message Wantlist {
7275
message Entry {
73-
optional bytes block = 1; // the block key
74-
optional int32 priority = 2; // the priority (normalized). default to 1
75-
optional bool cancel = 3; // whether this revokes an entry
76+
bytes block = 1; // the block key, i.e. a CIDv0
77+
int32 priority = 2; // the priority (normalized). default to 1
78+
bool cancel = 3; // whether this revokes an entry
7679
}
7780
7881
repeated Entry entries = 1; // a list of wantlist entries
79-
optional bool full = 2; // whether this is the full wantlist. default to false
80-
}
81-
82-
message Block {
83-
bytes prefix = 1; // CID prefix (cid version, multicodec and multihash prefix (type + length)
84-
bytes data = 2;
82+
bool full = 2; // whether this is the full wantlist. default to false
8583
}
8684
8785
Wantlist wantlist = 1;
88-
optional repeated bytes blocks = 2; // used to send Blocks in bitswap 1.0.0
89-
repeated Block payload = 3; // used to send Blocks in bitswap 1.1.0
90-
}
86+
repeated bytes blocks = 2;
9187
```
9288

93-
## Want-Manager
94-
95-
The want-manager handles requests for blocks. For a requested block, identified by `cid`, the `Bitswap.GetBlock(cid)` method is invoked. `Bitswap.GetBlock(cid)` requests `cid` from the network and, if the corresponding `Block` is received, returns it. More concretely, `Bitswap.GetBlock(cid)` adds `cid` to our wantlist. The want-manager then updates all peers with this addition by adding a new `Entry` to each peer’s message queue, who then may or may not respond with the desired block.
96-
97-
## Decision Engine
98-
99-
The decision engine decides how to allocate resources to peers. When a `Message` with a wantlist from a peer is received, the `Message` is sent to the decision engine. For every `CID` in the wantlist that we have the corresponding `Block` for, the block has a `Task` added to the peer’s `TaskQueue`. A `Task` is considered complete once the corresponding `Block` has been sent to the message queue for that peer.
100-
101-
The primary data structure in the decision engine is the peer request queue (`PRQ`). The `PRQ` adds peers to a weighted round-robin queue, where the weights are based on one or more peer-specific metrics. This is where Bitswap *strategies* come in. Currently, a `Strategy` is a function whose input is a peer’s `Ledger` and output is a weight for that peer. The peers are then served the `Task`s in their respective `TaskQueue`s. The amount of data each peer is served in a given round-robin round is determined by their relative weight in the queue. The in-progress Bitswap strategy implementation can be found [here](https://github.com/ipfs/research-bitswap/tree/docs/strategy_impl/strategy-impl). Further Bitswap strategy metrics and configuration interfaces are planned for the near future.
102-
103-
*Note: The Bitswap strategy implementations in the current releases of* `go-ipfs` *and* `js-ipfs` *do not conform to the description here as of the time of this writing.*
104-
105-
## Message Queue
89+
### Bitswap 1.0.0: Protocol Format
10690

107-
Each active peer has an associated message queue. The message queue holds the next message to be sent to that peer. The message queues receive updates from two other subsystems:
91+
All protocol messages sent over a stream are prefixed with the message length in
92+
bytes, encoded as an unsigned variable length integer as defined by the
93+
[multiformats unsigned-varint spec](https://github.com/multiformats/unsigned-varint).
10894

109-
1. Wantlist manager: When a `CID` is added or removed from our wantlist, we must update our peers – these wantlist updates are sent to all relevant peers’ message queues.
110-
2. Decision engine: When we have a block that a peer wants and the decision engine decides to send the block, we propagate the block to that peer’s message queue.
95+
All protocol messages must be less than or equal to 4MiB in size
11196

112-
Task workers watch the message queues, dequeue a waiting message, and send it to the recipient.
97+
## Bitswap 1.1.0
11398

114-
## Network
99+
Bitswap 1.1.0 introduces a 'payload' field to the protobuf message and deprecates the
100+
existing 'blocks' field. The 'payload' field is an array of pairs of cid
101+
prefixes and block data. The cid prefixes are used to ensure the correct
102+
codecs and hash functions are used to handle the block on the receiving
103+
end.
115104

116-
The network is the abstraction representing all Bitswap peers that are connected to us by one or more hops. Bitswap messages flow in and out of the network. This is where a game-theoretical analysis of Bitswap becomes relevant – in an arbitrary network we must assume that all of our peers are rational and self-interested, and we act accordingly. Work along these lines can be found in the [research-bitswap repository](https://github.com/ipfs/research-bitswap), with a preliminary game-theoretical analysis currently in-progress [here](https://github.com/ipfs/research-bitswap/blob/docs/strategy_analysis/analysis/prelim_strategy_analysis.pdf).
105+
It is otherwise identical to 1.0.0
117106

118-
# Implementation Details
107+
### Bitswap 1.1.0: Wire Format
119108

120-
## Coalescing Messages
121-
122-
When a message queue that already contains a Bitswap message receives another, the new message should be coalesced with the original to reduce the overhead of sending separate packets.
123-
124-
## Bitswap Sessions
125-
126-
Bitswap sessions are an attempt to optimize the block requests sent to other Bitswap clients. When requesting a graph of blocks from the network, we send a wantlist update containing the graph’s root block to all of our peers. Then, for each peer who sends the root block back, we add that peer to the graph’s *active set*. We then send all requests for other nodes in the graph only to the peers in the active set. The idea is that peers who have the root node of a graph are likely to have its children as well, while those who do not have the root are unlikely to have its children.
127-
128-
**TODO**: Everything below must either be updated/integrated above, or removed
129-
130-
Also, make sure to read - <https://github.com/ipfs/go-ipfs/tree/master/exchange/bitswap#go-ipfs-implementation>
109+
```protobuf
110+
message Message {
111+
message Entry {
112+
bytes block = 1; // CID of the block
113+
int32 priority = 2; // the priority (normalized). default to 1
114+
bool cancel = 3; // whether this revokes an entry
115+
}
131116
132-
Implementation suggestions:
117+
repeated Entry entries = 1; // a list of wantlist entries
118+
bool full = 2; // whether this is the full wantlist. default to false
119+
}
133120
134-
- maintain a peer set of “live partners”
135-
- protocol listener accept streams for partners to receive messages
136-
- protocol sender opens streams to partners to send messages
137-
- separate out a decision engine that selects which blocks to send to which partners, and at what time. (this is a bit tricky, but it’s super easy to make as a whole if the engine is separated out)
121+
message Block {
122+
bytes prefix = 1; // CID prefix (all of the CID components except for the digest of the multihash)
123+
bytes data = 2;
124+
}
138125
139-
Sender:
126+
Wantlist wantlist = 1;
127+
repeated Block payload = 3;
128+
}
129+
```
140130

141-
1. open a bitswap stream
142-
2. send one or more bitswap messages
143-
3. close bistwap stream
131+
## Bitswap 1.2.0
144132

145-
Listener:
133+
Bitswap 1.2.0 extends the Bitswap 1.1.0 protocol with the three changes:
134+
1. Being able to ask if a peer has the data, not just to send the data
135+
2. A peer can respond that it does not have some data rather than just not responding
136+
3. Nodes can indicate on messages how much data they have queued to send to the peer they are sending the message to
146137

147-
1. accept a bitswap stream
148-
2. receive one or more bitswap messages
149-
3. close bitswap stream
138+
### Bitswap 1.2.0: Interaction Pattern
150139

151-
Events:
140+
Given that a client C wants to fetch data from some server S:
152141

153-
- bitswap.addedBlock(block)
154-
- see if any peers want this block, and send it
155-
- bitswap.getBlock(key, cb)
156-
- add to wantlist
157-
- maybe send wantlist updates to peers
158-
- bitswap.cancelGet(key)
159-
- so that can send wantlist cancels
160-
- bitswap.receivedMessage(msg)
161-
- process the wantlist changes
162-
- process the blocks
163-
- bitswap.peerConnected(peer)
164-
- add peer to peer set + send them wantlist (maybe)
165-
- bitswap.peerDisconnected(peer)
166-
- remove peer from peer set
142+
1. C opens a stream `s_want` to S and sends a message for the blocks it wants
143+
1. C may either send a complete wantlist, or an update to an outstanding wantlist
144+
2. C may reuse this stream to send new wants
145+
3. For each of the items in the wantlist C may ask if S has the block (i.e. a Have request) or for S to send the block (i.e. a block request). C may also ask S to send back a DontHave message in the event it doesn't have the block
146+
2. S responds back on a stream `s_receive`. S may reuse this stream to send back subsequent responses
147+
1. If C sends S a Have request for data S has (and is willing to give to C) it should respond with a Have, although it may instead respond with the block itself (e.g. if the block is very small)
148+
2. If C sends S a Have request for data S does not have (or has but is not willing to give to C) and C has requested for DontHave responses then S should respond with DontHave
149+
3. S may choose to include the number of bytes that are pending to be sent to C in the response message
150+
4. S should respect the relative priority of wantlist requests from C, with wants that have higher `priority` values being responded to first.
151+
3. When C no longer needs a block it previously asked for it should send a Cancel message for that request to any peers that have not already responded about that particular block. It should particularly send Cancel messages for Block requests (as opposed to Have requests) that have not yet been answered.
167152

168-
Tricky Bits:
153+
### Bitswap 1.2.0: Wire Format
169154

170-
- clients to bitswap may call `getBlock` then `cancelBlock`
171-
- partners may spam wantlists
172-
- normalize priorities only per-peer
155+
```protobuf
156+
message Message {
157+
message Wantlist {
158+
enum WantType {
159+
Block = 0;
160+
Have = 1;
161+
}
173162
174-
Modules:
163+
message Entry {
164+
bytes block = 1; // CID of the block
165+
int32 priority = 2; // the priority (normalized). default to 1
166+
bool cancel = 3; // whether this revokes an entry
167+
WantType wantType = 4; // Note: defaults to enum 0, ie Block
168+
bool sendDontHave = 5; // Note: defaults to false
169+
}
175170
176-
- bitswap-decision-engine
177-
- bitswap-message
178-
- bitswap-net
179-
- bitswap-wantlist
171+
repeated Entry entries = 1; // a list of wantlist entries
172+
bool full = 2; // whether this is the full wantlist. default to false
173+
}
174+
message Block {
175+
bytes prefix = 1; // CID prefix (all of the CID components except for the digest of the multihash)
176+
bytes data = 2;
177+
}
180178
181-
Notes:
179+
enum BlockPresenceType {
180+
Have = 0;
181+
DontHave = 1;
182+
}
183+
message BlockPresence {
184+
bytes cid = 1;
185+
BlockPresenceType type = 2;
186+
}
182187
188+
Wantlist wantlist = 1;
189+
repeated Block payload = 3;
190+
repeated BlockPresence blockPresences = 4;
191+
int32 pendingBytes = 5;
192+
}
183193
```
184-
var bs = new BlockService(repo, bitswap)
185-
bs.getBlock(multihash, (err, block) => {
186-
// 1) try to fetch from repo
187-
// 2) if not -> ask bitswap
188-
// 2.1) bitswap will cb() once the block is back, once.
189-
// bitswap will write to the repo as well.
190-
})
191-
```
192-
193-
# API Spec
194-
195-
**TODO**: Fill this in, may need some input from @diasdavid, @whyrusleeping
196-
197-
> **Will be written once it gets stable, by now, it still requires a ton of experimentation**
198194

199-
# Implementations
195+
## Implementations
200196

201-
- <https://github.com/ipfs/go-bitswap>
202-
- <https://github.com/ipfs/js-ipfs-bitswap>
197+
- <https://github.com/ipfs/go-bitswap>
198+
- <https://github.com/ipfs/js-ipfs-bitswap>

0 commit comments

Comments
 (0)