diff --git a/package.json b/package.json index 3a3e534a..b5fd02a9 100644 --- a/package.json +++ b/package.json @@ -46,7 +46,7 @@ "interface-datastore": "~0.6.0", "k-bucket": "^4.0.1", "libp2p-crypto": "~0.13.0", - "libp2p-record": "~0.6.0", + "libp2p-record": "~0.6.1", "multihashes": "~0.4.14", "multihashing-async": "~0.5.1", "peer-id": "~0.11.0", diff --git a/src/private.js b/src/private.js index da93ad47..7e7b348b 100644 --- a/src/private.js +++ b/src/private.js @@ -271,7 +271,17 @@ module.exports = (dht) => ({ (cb) => dht.getMany(key, 16, options.maxTimeout, cb), (vals, cb) => { const recs = vals.map((v) => v.val) - const i = libp2pRecord.selection.bestRecord(dht.selectors, key, recs) + let i = 0 + + try { + i = libp2pRecord.selection.bestRecord(dht.selectors, key, recs) + } catch (err) { + // Assume the first record if no selector available + if (err.code !== 'ERR_NO_SELECTOR_FUNCTION_FOR_RECORD_KEY') { + return cb(err) + } + } + const best = recs[i] dht._log('GetValue %b %s', key, best) diff --git a/test/kad-dht.spec.js b/test/kad-dht.spec.js index 76e7b261..d49c90d1 100644 --- a/test/kad-dht.spec.js +++ b/test/kad-dht.spec.js @@ -222,6 +222,51 @@ describe('KadDHT', () => { }) }) + it('put - get using key with no prefix (no selector available)', function (done) { + this.timeout(10 * 1000) + const tdht = new TestDHT() + + tdht.spawn(2, (err, dhts) => { + expect(err).to.not.exist() + const dhtA = dhts[0] + const dhtB = dhts[1] + + waterfall([ + (cb) => connect(dhtA, dhtB, cb), + (cb) => dhtA.put(Buffer.from('hello'), Buffer.from('world'), cb), + (cb) => dhtB.get(Buffer.from('hello'), { maxTimeout: 1000 }, cb), + (res, cb) => { + expect(res).to.eql(Buffer.from('world')) + cb() + } + ], (err) => { + expect(err).to.not.exist() + tdht.teardown(done) + }) + }) + }) + + it('put - get should fail if unrecognized key prefix in get', function (done) { + this.timeout(10 * 1000) + const tdht = new TestDHT() + + tdht.spawn(2, (err, dhts) => { + expect(err).to.not.exist() + const dhtA = dhts[0] + const dhtB = dhts[1] + + waterfall([ + (cb) => connect(dhtA, dhtB, cb), + (cb) => dhtA.put(Buffer.from('/v2/hello'), Buffer.from('world'), cb), + (cb) => dhtB.get(Buffer.from('/v2/hello'), { maxTimeout: 1000 }, cb) + ], (err) => { + expect(err).to.exist() + expect(err.code).to.eql('ERR_UNRECOGNIZED_KEY_PREFIX') + tdht.teardown(done) + }) + }) + }) + it('put - get with update', function (done) { this.timeout(20 * 1000) const tdht = new TestDHT() diff --git a/test/utils/test-dht.js b/test/utils/test-dht.js index 7c5fd42d..a9498c27 100644 --- a/test/utils/test-dht.js +++ b/test/utils/test-dht.js @@ -56,6 +56,8 @@ class TestDHT { sign: false } + dht.validators.v2 = dht.validators.v // added to simulate just validators available + dht.selectors.v = (k, records) => 0 series([