Skip to content

Commit

Permalink
fix: update interfaces (#59)
Browse files Browse the repository at this point in the history
Updates to latest code from libp2p/js-libp2p-interfaces#180
  • Loading branch information
achingbrain authored Mar 16, 2022
1 parent 87f0b78 commit 67e8ae3
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 72 deletions.
13 changes: 8 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -130,19 +130,22 @@
"release": "semantic-release"
},
"dependencies": {
"@libp2p/interfaces": "^1.3.11",
"@libp2p/logger": "^1.0.4",
"multiformats": "^9.0.2",
"@libp2p/interfaces": "^1.3.14",
"@libp2p/logger": "^1.1.2",
"@multiformats/multiaddr": "^10.1.7",
"err-code": "^3.0.1",
"multiformats": "^9.6.3",
"p-defer": "^4.0.0",
"p-queue": "^7.2.0"
},
"devDependencies": {
"@libp2p/peer-id": "^1.1.5",
"@libp2p/peer-id-factory": "^1.0.5",
"@libp2p/peer-id": "^1.1.8",
"@libp2p/peer-id-factory": "^1.0.8",
"aegir": "^36.1.3",
"go-ipfs": "^0.12.0",
"ipfs-http-client": "^56.0.1",
"ipfsd-ctl": "^10.0.6",
"it-all": "^1.0.6",
"wherearewe": "^1.0.0"
},
"browser": {
Expand Down
43 changes: 33 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,22 @@ import { logger } from '@libp2p/logger'
import { base58btc } from 'multiformats/bases/base58'
import PQueue from 'p-queue'
import defer from 'p-defer'
import errCode from 'err-code'
import { Multiaddr } from '@multiformats/multiaddr'
import { peerIdFromString } from '@libp2p/peer-id'
import type { PeerId } from '@libp2p/interfaces/peer-id'
import type { IPFSHTTPClient } from 'ipfs-http-client'
import type { HTTPClientExtraOptions } from 'ipfs-http-client/types/src/types'
import type { AbortOptions } from 'ipfs-core-types/src/utils'
import type { PeerRouting } from '@libp2p/interfaces/peer-routing'
import type { PeerData } from '@libp2p/interfaces/peer-data'

const log = logger('libp2p-delegated-peer-routing')

const DEFAULT_TIMEOUT = 30e3 // 30 second default
const CONCURRENT_HTTP_REQUESTS = 4

export class DelegatedPeerRouting {
export class DelegatedPeerRouting implements PeerRouting {
private readonly client: IPFSHTTPClient
private readonly httpQueue: PQueue

Expand Down Expand Up @@ -44,7 +49,7 @@ export class DelegatedPeerRouting {
/**
* Attempts to find the given peer
*/
async * findPeer (id: PeerId, options: HTTPClientExtraOptions & AbortOptions = {}) {
async findPeer (id: PeerId, options: HTTPClientExtraOptions & AbortOptions = {}) {
log('findPeer starts: %p', id)
options.timeout = options.timeout ?? DEFAULT_TIMEOUT

Expand All @@ -57,21 +62,31 @@ export class DelegatedPeerRouting {
})

try {
yield * this.client.dht.findPeer(id.toString(), {
await onStart.promise

for await (const event of this.client.dht.findPeer(id.toString(), {
timeout: options.timeout
})
})) {
if (event.name === 'FINAL_PEER') {
const peerData: PeerData = {
id: peerIdFromString(event.peer.id),
multiaddrs: event.peer.multiaddrs.map(ma => new Multiaddr(ma.toString())),
protocols: []
}

return peerData
}
}
} catch (err: any) {
log.error('findPeer errored: %o', err)

if (err.message.includes('not found')) { // eslint-disable-line @typescript-eslint/strict-boolean-expressions
return
}

throw err
} finally {
onFinish.resolve()
log('findPeer finished: %p', id)
}

throw errCode(new Error('Not found'), 'ERR_NOT_FOUND')
}

/**
Expand All @@ -94,9 +109,17 @@ export class DelegatedPeerRouting {
try {
await onStart.promise

yield * this.client.dht.query(keyStr, {
for await (const event of this.client.dht.query(keyStr, {
timeout: options.timeout
})
})) {
if (event.name === 'PEER_RESPONSE') {
yield * event.closer.map(closer => ({
id: peerIdFromString(closer.id),
multiaddrs: closer.multiaddrs.map(ma => new Multiaddr(ma.toString())),
protocols: []
}))
}
}
} catch (err) {
log.error('getClosestPeers errored:', err)
throw err
Expand Down
69 changes: 12 additions & 57 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ import { DelegatedPeerRouting } from '../src/index.js'
import goIpfs from 'go-ipfs'
import { peerIdFromString } from '@libp2p/peer-id'
import { createEd25519PeerId } from '@libp2p/peer-id-factory'
import all from 'it-all'
import type { IDResult } from 'ipfs-core-types/src/root'
import type { PeerData } from 'ipfs-core-types/src/dht'

const factory = createFactory({
type: 'go',
Expand Down Expand Up @@ -107,22 +107,12 @@ describe('DelegatedPeerRouting', function () {
host: opts.host
}))

let peer: PeerData | undefined

for await (const event of router.findPeer(peerIdFromString(peerIdToFind.id))) {
if (event.name === 'FINAL_PEER') {
peer = event.peer
}
}

if (peer == null) {
throw new Error('Did not find peer')
}
const peer = await router.findPeer(peerIdFromString(peerIdToFind.id))

const { id, multiaddrs } = peer
expect(id).to.exist()
expect(multiaddrs).to.exist()
expect(id).to.eql(peerIdToFind.id)
expect(id.equals(peerIdToFind.id)).to.be.true()
})

it('should be able to find peers via the delegate with a peerid', async () => {
Expand All @@ -133,17 +123,7 @@ describe('DelegatedPeerRouting', function () {
host: opts.host
}))

let peer: PeerData | undefined

for await (const event of router.findPeer(peerIdFromString(peerIdToFind.id))) {
if (event.name === 'FINAL_PEER') {
peer = event.peer
}
}

if (peer == null) {
throw new Error('Did not find peer')
}
const peer = await router.findPeer(peerIdFromString(peerIdToFind.id))

const { id, multiaddrs } = peer
expect(id).to.exist()
Expand All @@ -160,17 +140,7 @@ describe('DelegatedPeerRouting', function () {
host: opts.host
}))

let peer: PeerData | undefined

for await (const event of router.findPeer(peerIdFromString(peerIdToFind.id), { timeout: 2000 })) {
if (event.name === 'FINAL_PEER') {
peer = event.peer
}
}

if (peer == null) {
throw new Error('Did not find peer')
}
const peer = await router.findPeer(peerIdFromString(peerIdToFind.id), { timeout: 2000 })

const { id, multiaddrs } = peer
expect(id).to.exist()
Expand All @@ -189,11 +159,8 @@ describe('DelegatedPeerRouting', function () {

// This is one of the default Bootstrap nodes, but we're not connected to it
// so we'll test with it.
for await (const event of router.findPeer(peerIdFromString('QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64'))) {
if (event.name === 'FINAL_PEER') {
throw new Error('Should not have found peer')
}
}
await expect(router.findPeer(peerIdFromString('QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64')))
.to.eventually.be.rejected.with.property('code', 'ERR_NOT_FOUND')
})
})

Expand All @@ -212,19 +179,13 @@ describe('DelegatedPeerRouting', function () {

const key = peerIdFromString(peerIdToFind.id).toBytes()

const closerPeers: PeerData[] = []

for await (const event of router.getClosestPeers(key)) {
if (event.name === 'PEER_RESPONSE') {
closerPeers.push(...event.closer)
}
}
const closerPeers = await all(router.getClosestPeers(key))

// we should be closest to the 2 other peers
expect(closerPeers.length).to.equal(2)
closerPeers.forEach(result => {
// shouldnt be the delegate
expect(delegatePeerId.equals(peerIdFromString(result.id))).to.equal(false)
// shouldn't be the delegate
expect(delegatePeerId.equals(result.id)).to.equal(false)
expect(result.multiaddrs).to.be.an('array')
})
})
Expand All @@ -242,19 +203,13 @@ describe('DelegatedPeerRouting', function () {
const delegatePeerId = peerIdFromString(nodeId.id)

const peerId = await createEd25519PeerId()
const closerPeers: PeerData[] = []

for await (const event of router.getClosestPeers(peerId.toBytes())) {
if (event.name === 'PEER_RESPONSE') {
closerPeers.push(...event.closer)
}
}
const closerPeers = await all(router.getClosestPeers(peerId.toBytes()))

// we should be closest to the 2 other peers
expect(closerPeers.length).to.equal(2)
closerPeers.forEach(result => {
// shouldnt be the delegate
expect(delegatePeerId.equals(peerIdFromString(result.id))).to.equal(false)
expect(delegatePeerId.equals(result.id)).to.equal(false)
expect(result.multiaddrs).to.be.an('array')
})
})
Expand Down

0 comments on commit 67e8ae3

Please sign in to comment.