@@ -5,6 +5,7 @@ const extend = require('xtend')
5
5
const codec = require ( './codec' )
6
6
const protocols = require ( './protocols-table' )
7
7
const varint = require ( 'varint' )
8
+ const bs58 = require ( 'bs58' )
8
9
9
10
const NotImplemented = new Error ( 'Sorry, Not Implemented Yet.' )
10
11
@@ -83,8 +84,8 @@ Multiaddr.prototype.toOptions = function toOptions () {
83
84
*/
84
85
Multiaddr . prototype . inspect = function inspect ( ) {
85
86
return '<Multiaddr ' +
86
- this . buffer . toString ( 'hex' ) + ' - ' +
87
- codec . bufferToString ( this . buffer ) + '>'
87
+ this . buffer . toString ( 'hex' ) + ' - ' +
88
+ codec . bufferToString ( this . buffer ) + '>'
88
89
}
89
90
90
91
/**
@@ -105,7 +106,7 @@ Multiaddr.prototype.inspect = function inspect () {
105
106
Multiaddr . prototype . protos = function protos ( ) {
106
107
return map ( this . protoCodes ( ) , function ( code ) {
107
108
return extend ( protocols ( code ) )
108
- // copy to prevent users from modifying the internal objs.
109
+ // copy to prevent users from modifying the internal objs.
109
110
} )
110
111
}
111
112
@@ -231,6 +232,33 @@ Multiaddr.prototype.decapsulate = function decapsulate (addr) {
231
232
return Multiaddr ( s . slice ( 0 , i ) )
232
233
}
233
234
235
+ /**
236
+ * Extract the peerId if the multiaddr contains one
237
+ *
238
+ * @return {String } peerId - The id of the peer
239
+ * @example
240
+ * const mh1 = Multiaddr('/ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string')
241
+ * // <Multiaddr 0408080808060438 - /ip4/8.8.8.8/tcp/1080/ipfs/QmValidBase58string>
242
+ *
243
+ * const peerId
244
+ *
245
+ * try {
246
+ * peerId = mh1.getPeerId()
247
+ * } catch (err) {
248
+ * // not a valid base58 address
249
+ * }
250
+ */
251
+ Multiaddr . prototype . getPeerId = function peerId ( ) {
252
+ let b58str = this . stringTuples ( ) . filter ( ( tuple ) => {
253
+ if ( tuple [ 0 ] === protocols . names [ 'ipfs' ] . code ) {
254
+ return true
255
+ }
256
+ } ) [ 0 ] [ 1 ]
257
+
258
+ bs58 . decode ( b58str )
259
+ return b58str
260
+ }
261
+
234
262
/**
235
263
* Checks if two Multiaddrs are the same
236
264
*
@@ -428,4 +456,3 @@ Multiaddr.resolve = function resolve (addr, callback) {
428
456
*/
429
457
return callback ( new Error ( 'not implemented yet' ) )
430
458
}
431
-
0 commit comments