Skip to content

Commit

Permalink
feat: add bitswap.ledgerForPeer
Browse files Browse the repository at this point in the history
  • Loading branch information
wraithgar authored and vmx committed May 31, 2018
1 parent e602810 commit 871d0d2
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/decision-engine/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,22 @@ class DecisionEngine {
return this.ledgerMap.get(peerIdStr).wantlist.sortedEntries()
}

ledgerForPeer (peerId) {
const peerIdStr = peerId.toB58String()

const ledger = this.ledgerMap.get(peerIdStr)
if (!ledger) {
return null
}
return {
peer: ledger.partner.toB58String(),
value: ledger.debtRatio(),
sent: ledger.accounting.bytesSent,
recv: ledger.accounting.bytesRecv,
exchanged: ledger.exchangeCount
}
}

peers () {
return Array.from(this.ledgerMap.values()).map((l) => l.partner)
}
Expand Down
10 changes: 10 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,16 @@ class Bitswap {
return this.engine.wantlistForPeer(peerId)
}

/**
* Return ledger information for a given `peerId`
*
* @param {PeerId} peerId
* @returns {?Object}
*/
ledgerForPeer (peerId) {
return this.engine.ledgerForPeer(peerId)
}

/**
* Fetch a given block by cid. If the block is in the local
* blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us.
Expand Down
19 changes: 19 additions & 0 deletions test/bitswap-mock-internals.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,13 @@ describe('bitswap with mocks', function () {

expect(blocks[0].data).to.eql(b1.data)
expect(blocks[1].data).to.eql(b2.data)

const ledger = bs.ledgerForPeer(other)
expect(ledger.peer).to.equal(other.toB58String())
expect(ledger.value).to.equal(0)
expect(ledger.sent).to.equal(0)
expect(ledger.recv).to.equal(96)
expect(ledger.exchanged).to.equal(2)
done()
})
})
Expand Down Expand Up @@ -381,4 +388,16 @@ describe('bitswap with mocks', function () {
})
})
})

describe('ledgerForPeer', () => {
it('returns null for unknown peer', (done) => {
const bs = new Bitswap(mockLibp2pNode(), repo.blocks)
PeerId.create((err, id) => {
expect(err).to.not.exist()
const ledger = bs.ledgerForPeer(id)
expect(ledger).to.equal(null)
done()
})
})
})
})
2 changes: 2 additions & 0 deletions test/decision-engine/ledger.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ describe('Ledger', () => {
})

it('accounts', () => {
expect(ledger.debtRatio()).to.eql(0)

ledger.sentBytes(100)
ledger.sentBytes(12000)
ledger.receivedBytes(223432)
Expand Down

0 comments on commit 871d0d2

Please sign in to comment.