diff --git a/README.md b/README.md index f948af6..9ed96f3 100644 --- a/README.md +++ b/README.md @@ -200,6 +200,10 @@ See the [Hypercore docs](https://github.com/hypercore-protocol/hypercore) for mo Append a block or array of blocks to the hypercore +#### `await feed.getBitfield([start], [length]) + +Get a bitfield of downloaded blocks. Optionally restrict to the range from `start` for `length` blocks. Resolves to a [bitfield](https://github.com/fb55/bitfield) instance. + #### `feed.peers` A list of peers this feed is connected to. diff --git a/index.js b/index.js index 6fba3a2..d145c35 100644 --- a/index.js +++ b/index.js @@ -1,4 +1,6 @@ const { EventEmitter } = require('events') +const rle = require('bitfield-rle') +const Bitfield = require('bitfield') const maybe = require('call-me-maybe') const codecs = require('codecs') const hypercoreCrypto = require('hypercore-crypto') @@ -545,6 +547,17 @@ class RemoteHypercore extends Nanoresource { return rsp.has } + async _getBitfield (start, length) { + const rsp = await this._client.hypercore.has({ + seq: start || 0, + bitfield: true, + length, + id: this._id + }) + if (!rsp.bitfield) throw new Error('Did not receive a bitfield') + return new Bitfield(rle.decode(rsp.bitfield)) + } + async _download (range, resourceId) { if (!this.opened) await this.open() if (this.closed) throw new Error('Feed is closed') @@ -611,6 +624,10 @@ class RemoteHypercore extends Nanoresource { return maybe(cb, this._has(seq)) } + getBitfield (start, length, cb) { + return maybe(cb, this._getBitfield(start, length)) + } + cancel (get) { if (typeof get.resourceId !== 'number') throw new Error('Must pass a get return value') return this._cancel(get.resourceId) diff --git a/package.json b/package.json index 80e239e..cdbc3ed 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "homepage": "https://github.com/hyperspace-org/hyperspace#readme", "dependencies": { "@hyperspace/rpc": "^1.0.0", + "bitfield": "^3.0.0", + "bitfield-rle": "^2.2.1", "call-me-maybe": "^1.0.1", "codecs": "^2.1.0", "freemap": "^1.0.0",