Skip to content

Commit c20a91c

Browse files
committed
fix: parse cid encoded peer ids
fixes #2772
1 parent d9eb8dc commit c20a91c

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

packages/peer-id/src/index.ts

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
import { publicKeyFromMultihash } from '@libp2p/crypto/keys'
1818
import { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'
1919
import { base58btc } from 'multiformats/bases/base58'
20-
import { type CID, type MultibaseDecoder } from 'multiformats/cid'
20+
import { type MultibaseDecoder } from 'multiformats/cid'
21+
import { CID } from 'multiformats/cid'
2122
import * as Digest from 'multiformats/hashes/digest'
2223
import { identity } from 'multiformats/hashes/identity'
2324
import { sha256 } from 'multiformats/hashes/sha2'
@@ -37,15 +38,26 @@ export function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>):
3738
// identity hash ed25519/secp256k1 key or sha2-256 hash of
3839
// rsa public key - base58btc encoded either way
3940
multihash = Digest.decode(base58btc.decode(`z${str}`))
40-
} else {
41-
if (decoder == null) {
42-
throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with "1" or "Q"')
43-
}
41+
return peerIdFromMultihash(multihash)
42+
}
4443

45-
multihash = Digest.decode(decoder.decode(str))
44+
if (decoder == null) {
45+
throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with "1" or "Q"')
4646
}
4747

48-
return peerIdFromMultihash(multihash)
48+
let buf: Uint8Array
49+
try {
50+
buf = decoder.decode(str)
51+
} catch (err) {
52+
throw new InvalidParametersError('The passed PeerID string could not be decoded using the provided multibase decoder')
53+
}
54+
55+
try {
56+
multihash = Digest.decode(buf)
57+
return peerIdFromMultihash(multihash)
58+
} catch (err) {
59+
return peerIdFromCID(CID.decode(buf))
60+
}
4961
}
5062

5163
export function peerIdFromPublicKey (publicKey: Ed25519PublicKey): Ed25519PeerId

0 commit comments

Comments
 (0)