Skip to content
This repository has been archived by the owner on Jul 21, 2023. It is now read-only.

feat: remove dht.getPublicKey #258

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
"err-code": "^3.0.0",
"hashlru": "^2.3.0",
"interface-datastore": "^6.0.2",
"iso-random-stream": "^2.0.1",
"it-all": "^1.0.5",
"it-drain": "^1.0.4",
"it-first": "^1.0.4",
Expand All @@ -65,7 +66,6 @@
"it-pipe": "^1.1.0",
"it-take": "^1.0.2",
"k-bucket": "^5.1.0",
"libp2p-crypto": "^0.21.0",
"libp2p-interfaces": "^2.0.1",
"libp2p-record": "^0.10.4",
"multiaddr": "^10.0.0",
Expand Down
44 changes: 1 addition & 43 deletions src/dual-kad-dht.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict'

const { EventEmitter } = require('events')
const PeerId = require('peer-id')
const utils = require('./utils')
const errCode = require('err-code')
const merge = require('it-merge')
Expand All @@ -17,6 +16,7 @@ const log = utils.logger('libp2p:kad-dht')
* @typedef {import('libp2p/src/registrar')} Registrar
* @typedef {import('multiformats/cid').CID} CID
* @typedef {import('multiaddr').Multiaddr} Multiaddr
* @typedef {import('peer-id')} PeerId
* @typedef {import('./kad-dht').KadDHT} KadDHT
* @typedef {import('./types').DHT} DHT
* @typedef {import('./types').QueryEvent} QueryEvent
Expand Down Expand Up @@ -299,48 +299,6 @@ class DualKadDHT extends EventEmitter {
)
}

/**
* Get the public key for the given peer id
*
* @param {PeerId} peer
* @param {object} [options]
* @param {AbortSignal} [options.signal]
*/
async getPublicKey (peer, options = {}) {
log('getPublicKey %p', peer)

// local check
const peerData = this._libp2p.peerStore.get(peer)

if (peerData && peerData.id.pubKey) {
log('getPublicKey: found local copy')
return peerData.id.pubKey
}

// try the node directly
const pks = await Promise.all([
this._lan.getPublicKey(peer, options),
this._wan.getPublicKey(peer, options)
])

if (pks[0] && pks[1] && !pks[0].equals(pks[1])) {
throw errCode(new Error('Inconsistent public key loaded from wan and lan DHTs'), 'ERR_FAILED_TO_LOAD_KEY')
}

const pk = pks[0] || pks[1]

if (!pk) {
throw errCode(new Error('Failed to load public key'), 'ERR_FAILED_TO_LOAD_KEY')
}

const peerId = new PeerId(peer.id, undefined, pk)
const addrs = ((peerData && peerData.addresses) || []).map((address) => address.multiaddr)
this._libp2p.peerStore.addressBook.add(peerId, addrs)
this._libp2p.peerStore.keyBook.set(peerId, pk)

return pk
}

async refreshRoutingTable () {
await Promise.all([
this._lan.refreshRoutingTable(),
Expand Down
34 changes: 0 additions & 34 deletions src/kad-dht.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
'use strict'

const { EventEmitter } = require('events')
const crypto = require('libp2p-crypto')
const libp2pRecord = require('libp2p-record')
const { MemoryDatastore } = require('datastore-core/memory')
const { RoutingTable } = require('./routing-table')
Expand Down Expand Up @@ -463,39 +462,6 @@ class KadDHT extends EventEmitter {
yield * this._peerRouting.getClosestPeers(key, options)
}

/**
* Get the public key for the given peer id
*
* @param {PeerId} peer
* @param {object} [options]
* @param {AbortSignal} [options.signal]
*/
async getPublicKey (peer, options = {}) {
this._log('getPublicKey %p', peer)

// try the node directly
let pk

for await (const event of this._peerRouting.getPublicKeyFromNode(peer, options)) {
if (event.name === 'VALUE') {
pk = crypto.keys.unmarshalPublicKey(event.value)
}
}

if (!pk) {
// try dht directly
const pkKey = utils.keyForPublicKey(peer)

for await (const event of this.get(pkKey, options)) {
if (event.name === 'VALUE') {
pk = crypto.keys.unmarshalPublicKey(event.value)
}
}
}

return pk
}

async refreshRoutingTable () {
await this._routingTableRefresh.refreshTable(true)
}
Expand Down
35 changes: 3 additions & 32 deletions src/peer-routing/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,26 @@

const errcode = require('err-code')
const { validator } = require('libp2p-record')
const PeerId = require('peer-id')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const { Message } = require('../message')
const utils = require('../utils')
const {
queryErrorEvent,
finalPeerEvent,
valueEvent
finalPeerEvent
} = require('../query/events')
const PeerDistanceList = require('../peer-list/peer-distance-list')
const { Record } = require('libp2p-record')

/**
* @typedef {import('multiaddr').Multiaddr} Multiaddr
* @typedef {import('../types').PeerData} PeerData
* @typedef {import('peer-id')} PeerId
*/

class PeerRouting {
/**
* @param {object} params
* @param {import('peer-id')} params.peerId
* @param {PeerId} params.peerId
* @param {import('../routing-table').RoutingTable} params.routingTable
* @param {import('../types').PeerStore} params.peerStore
* @param {import('../network').Network} params.network
Expand Down Expand Up @@ -82,34 +81,6 @@ class PeerRouting {
yield * this._network.sendRequest(peer, msg, options)
}

/**
* Get the public key directly from a node.
*
* @param {PeerId} peer
* @param {object} [options]
* @param {AbortSignal} [options.signal]
*/
async * getPublicKeyFromNode (peer, options) {
const pkKey = utils.keyForPublicKey(peer)

for await (const event of this._getValueSingle(peer, pkKey, options)) {
yield event

if (event.name === 'PEER_RESPONSE' && event.record) {
const recPeer = await PeerId.createFromPubKey(event.record.value)

// compare hashes of the pub key
if (!recPeer.equals(peer)) {
throw errcode(new Error('public key does not match id'), 'ERR_PUBLIC_KEY_DOES_NOT_MATCH_ID')
}

yield valueEvent({ from: peer, value: recPeer.pubKey.bytes })
}
}

throw errcode(new Error(`Node not responding with its public key: ${peer.toB58String()}`), 'ERR_INVALID_RECORD')
}

/**
* Search for a peer with the given ID.
*
Expand Down
6 changes: 3 additions & 3 deletions src/routing-table/refresh.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
const { xor: uint8ArrayXor } = require('uint8arrays/xor')
const GENERATED_PREFIXES = require('./generated-prefix-list.json')
const { sha256 } = require('multiformats/hashes/sha2')
const crypto = require('libp2p-crypto')
const randomBytes = require('iso-random-stream/src/random')
const PeerId = require('peer-id')
const utils = require('../utils')
const length = require('it-length')
Expand Down Expand Up @@ -170,8 +170,8 @@ class RoutingTableRefresh {
* @param {number} targetCommonPrefixLength
*/
async _generateRandomPeerId (targetCommonPrefixLength) {
const randomBytes = crypto.randomBytes(2)
const randomUint16 = (randomBytes[1] << 8) + randomBytes[0]
const bytes = randomBytes(2)
const randomUint16 = (bytes[1] << 8) + bytes[0]

const key = await this._makePeerId(this._routingTable.kb.localNodeId, randomUint16, targetCommonPrefixLength)

Expand Down
2 changes: 0 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import type { Multiaddr } from 'multiaddr'
import type { CID } from 'multiformats/cid'
import type { MuxedStream } from 'libp2p/src/upgrader'
import type Topology from 'libp2p-interfaces/src/topology'
import type { PublicKey } from 'libp2p-crypto'
import type { Message } from './message/dht'

export enum EventTypes {
Expand Down Expand Up @@ -134,7 +133,6 @@ export interface DHT {
findProviders: (key: CID, options?: QueryOptions) => AsyncIterable<QueryEvent>
findPeer: (id: PeerId, options?: QueryOptions) => AsyncIterable<QueryEvent>
getClosestPeers: (key: Uint8Array, options?: QueryOptions) => AsyncIterable<QueryEvent>
getPublicKey: (peer: PeerId, options?: QueryOptions) => Promise<PublicKey>

// publish/server methods
provide: (key: CID, options?: QueryOptions) => AsyncIterable<QueryEvent>
Expand Down
19 changes: 0 additions & 19 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,9 @@ const { base32 } = require('multiformats/bases/base32')
const { Key } = require('interface-datastore/key')
const { Record } = require('libp2p-record')
const PeerId = require('peer-id')
const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const { concat: uint8ArrayConcat } = require('uint8arrays/concat')
const isPrivateIp = require('private-ip')

// const IPNS_PREFIX = uint8ArrayFromString('/ipns/')
const PK_PREFIX = uint8ArrayFromString('/pk/')

/**
* @param {import('./types').PeerData} peer
*/
Expand Down Expand Up @@ -83,19 +78,6 @@ const bufferToKey = (buf) => {
return new Key('/' + uint8ArrayToString(buf, 'base32'), false)
}

/**
* Generate the key for a public key.
*
* @param {PeerId} peer
* @returns {Uint8Array}
*/
const keyForPublicKey = (peer) => {
return uint8ArrayConcat([
PK_PREFIX,
peer.id
])
}

/**
* @param {Uint8Array} key
*/
Expand Down Expand Up @@ -165,7 +147,6 @@ module.exports = {
convertBuffer,
convertPeerId,
bufferToKey,
keyForPublicKey,
isPublicKeyKey,
isIPNSKey,
fromPublicKeyKey,
Expand Down
33 changes: 0 additions & 33 deletions test/kad-dht.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@

const { expect } = require('aegir/utils/chai')
const sinon = require('sinon')
const { Multiaddr } = require('multiaddr')
const { Record } = require('libp2p-record')
const errcode = require('err-code')
const { equals: uint8ArrayEquals } = require('uint8arrays/equals')
Expand Down Expand Up @@ -82,7 +81,6 @@ describe('KadDHT', () => {
expect(dht).to.have.property('findProviders')
expect(dht).to.have.property('findPeer')
expect(dht).to.have.property('getClosestPeers')
expect(dht).to.have.property('getPublicKey')
expect(dht).to.have.property('enableServerMode')
expect(dht).to.have.property('enableClientMode')
})
Expand Down Expand Up @@ -689,37 +687,6 @@ describe('KadDHT', () => {
})
})

describe('getPublicKey', () => {
it('already known', async function () {
this.timeout(20 * 1000)

const dhts = await tdht.spawn(2)

const ids = dhts.map((d) => d._libp2p.peerId)
dhts[0]._libp2p.peerStore.addressBook.add(dhts[1]._libp2p.peerId, [new Multiaddr('/ip4/160.1.1.1/tcp/80')])

const key = await dhts[0].getPublicKey(ids[1])
expect(key).to.eql(dhts[1]._libp2p.peerId.pubKey)

await delay(100)
})

it('connected node', async function () {
this.timeout(30 * 1000)

const dhts = await tdht.spawn(2)

const ids = dhts.map((d) => d._libp2p.peerId)

await tdht.connect(dhts[0], dhts[1])

dhts[0]._libp2p.peerStore.addressBook.add(dhts[1]._libp2p.peerId, [new Multiaddr('/ip4/160.1.1.1/tcp/80')])

const key = await dhts[0].getPublicKey(ids[1])
expect(uint8ArrayEquals(key, dhts[1]._libp2p.peerId.pubKey)).to.eql(true)
})
})

describe('errors', () => {
it('get should fail if only has one peer', async function () {
this.timeout(20 * 1000)
Expand Down
14 changes: 3 additions & 11 deletions test/kad-utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
'use strict'

const { expect } = require('aegir/utils/chai')
const { concat: uint8ArrayConcat } = require('uint8arrays/concat')
const { fromString: uint8ArrayFromString } = require('uint8arrays/from-string')
const { toString: uint8ArrayToString } = require('uint8arrays/to-string')
const keyForPublicKey = require('./utils/key-for-public-key')

const utils = require('../src/utils')
const createPeerId = require('./utils/create-peer-id')
Expand All @@ -31,22 +31,14 @@ describe('kad utils', () => {
})
})

describe('keyForPublicKey', () => {
it('works', async () => {
const peers = await createPeerId(1)
expect(utils.keyForPublicKey(peers[0]))
.to.eql(uint8ArrayConcat([uint8ArrayFromString('/pk/'), peers[0].id]))
})
})

describe('fromPublicKeyKey', () => {
it('round trips', async function () {
this.timeout(40 * 1000)

const peers = await createPeerId(50)
peers.forEach((id, i) => {
expect(utils.isPublicKeyKey(utils.keyForPublicKey(id))).to.eql(true)
expect(utils.fromPublicKeyKey(utils.keyForPublicKey(id)).id)
expect(utils.isPublicKeyKey(keyForPublicKey(id))).to.eql(true)
expect(utils.fromPublicKeyKey(keyForPublicKey(id)).id)
.to.eql(id.id)
})
})
Expand Down
Loading