1717import { publicKeyFromMultihash } from '@libp2p/crypto/keys'
1818import { InvalidCIDError , InvalidMultihashError , InvalidParametersError , UnsupportedKeyTypeError } from '@libp2p/interface'
1919import { 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'
2122import * as Digest from 'multiformats/hashes/digest'
2223import { identity } from 'multiformats/hashes/identity'
2324import { 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
5163export function peerIdFromPublicKey ( publicKey : Ed25519PublicKey ) : Ed25519PeerId
0 commit comments