holepunchto / hyperswarm

A distributed networking stack for connecting peers.
https://docs.holepunch.to
MIT License
1.07k stars 86 forks source link

cannot replicate using a custom keypair #82

Closed Anyass3 closed 3 years ago

Anyass3 commented 3 years ago

hyperswarm@3.0.0-beta3

when I run it without custom a keypair it works as expected But with a custom keyPair it gives an error

It can be easily reproduced. Just copied from your docs and added a custom keyPair

const Hyperswarm = require('hyperswarm');
const HypercoreProtocol = require('hypercore-protocol');
const swarm1 = new Hyperswarm({ keyPair: HypercoreProtocol.keyPair() });
const swarm2 = new Hyperswarm();

swarm1.on('connection', (conn, info) => {
  conn.write('this is a server connection');
  conn.end();
});

swarm2.on('connection', (conn, info) => {
  conn.on('data', (data) => console.log('client got message:', data.toString()));
});
(async () => {
  const topic = Buffer.alloc(32).fill('hello world'); 
  const discovery = swarm1.join(topic, { server: true, client: false });
  await discovery.flushed(); 

  swarm2.join(topic, { server: false, client: true });
  await swarm2.flush();
})();

error

.../node_modules/@hyperswarm/dht/index.js:637
      throw new Error('Server is already listening on a keyPair')
            ^

Error: Server is already listening on a keyPair
    at KATServer.listen (.../node_modules/@hyperswarm/dht/index.js:637:13)
    at Hyperswarm.listen (.../node_modules/hyperswarm/index.js:249:57)
    at PeerDiscovery._ready (.../node_modules/hyperswarm/lib/peer-discovery.js:26:23)
    at PeerDiscovery.flushed (.../node_modules/hyperswarm/lib/peer-discovery.js:109:16)
    at .../swarm-issue.js:18:19
    at Object.<anonymous> (.../swarm-issue.js:22:3)
    at Module._compile (node:internal/modules/cjs/loader:1109:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1138:10)
    at Module.load (node:internal/modules/cjs/loader:989:32)
Anyass3 commented 3 years ago

I got my answer I should be using this instead

- const HypercoreProtocol = require('hypercore-protocol');
+ const DHT = require('@hyperswarm/dht'); 
- const swarm1 = new Hyperswarm({ keyPair: HypercoreProtocol.keyPair() });
+ const swarm1 = new Hyperswarm({ keyPair: DHT.keyPair() });

for those who need the reason, it's because HypercoreProtocol.keyPair() gives 32bits secretKey which is not compatible with the new API; DHT.keyPair() gives secretKey as 64bits

Anyass3 commented 3 years ago

Also, I guess the error above should be more informative as the main cause of the error is keyPair not because the server is already listening

If you checked properly it seems the server is not even listening on this keypair as before it calls that listen function, it first checks if it's not listening then it calls it.

mafintosh commented 3 years ago

Thanks for the feedback, we’ll try to improve the error message :)

Anyass3 commented 3 years ago

thanks