33const Connection = require ( 'interface-connection' ) . Connection
44const debug = require ( 'debug' )
55const log = debug ( 'zeronet:dial' )
6+ const crypto = require ( "crypto" )
7+
8+ const sha5 = text => crypto . createHash ( 'sha512' ) . update ( text ) . digest ( 'hex' )
9+ const multiaddr = require ( "multiaddr" )
10+ const Id = require ( "peer-id" )
11+ const Peer = require ( 'peer-info' )
12+
13+ const BASE58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
14+ const bs58 = require ( 'base-x' ) ( BASE58 )
615
716module . exports = function dial ( swarm , ZProtocol ) {
17+ function getId ( pi , cb ) {
18+ if ( multiaddr . isMultiaddr ( pi ) ) {
19+ const ad = pi . toString ( )
20+ const md = pi
21+ let pid = Id . createFromB58String ( "Q" + bs58 . encode ( sha5 ( ad ) . substr ( 0 , 34 ) ) )
22+ Peer . create ( pid , ( err , pi ) => {
23+ if ( err ) return cb ( err )
24+ pi . multiaddrs . add ( md )
25+ return cb ( null , pi )
26+ } )
27+ } else if ( Peer . isPeerInfo ( pi ) ) {
28+ return cb ( null , pi )
29+ }
30+ }
31+
832 return ( pi , protocol , callback ) => {
933 if ( typeof protocol === 'function' ) {
1034 callback = protocol
@@ -15,25 +39,33 @@ module.exports = function dial(swarm, ZProtocol) {
1539
1640 const proxyConn = new Connection ( )
1741
18- const b58Id = pi . id . toB58String ( )
19- log ( 'dialing %s' , b58Id )
20-
21- if ( ! swarm . conns [ b58Id ] ) {
22- attemptDial ( pi , ( err , conn ) => {
23- if ( err ) {
24- return callback ( err )
25- }
26- conn . setPeerInfo ( pi )
27- protocolLayer ( conn , err => {
28- if ( err ) return callback ( err )
29- swarm . conns [ b58Id ] = conn
30- return callback ( null , conn )
42+ getId ( pi , ( err , _pi ) => {
43+ if ( err ) {
44+ return callback ( err )
45+ }
46+
47+ pi = _pi
48+
49+ const b58Id = pi . id . toB58String ( )
50+ log ( 'dialing %s' , b58Id )
51+
52+ if ( ! swarm . conns [ b58Id ] ) {
53+ attemptDial ( pi , ( err , conn ) => {
54+ if ( err ) {
55+ return callback ( err )
56+ }
57+ conn . setPeerInfo ( pi )
58+ protocolLayer ( conn , err => {
59+ if ( err ) return callback ( err )
60+ swarm . conns [ b58Id ] = conn
61+ return callback ( null , conn )
62+ } )
3163 } )
32- } )
33- } else {
34- const conn = swarm . conns [ b58Id ]
35- return callback ( null , conn . client )
36- }
64+ } else {
65+ const conn = swarm . conns [ b58Id ]
66+ return callback ( null , conn . client )
67+ }
68+ } )
3769
3870 return proxyConn
3971
0 commit comments