Skip to content

Commit

Permalink
fix: parse cid encoded peer ids
Browse files Browse the repository at this point in the history
fixes #2772
  • Loading branch information
2color committed Oct 17, 2024
1 parent d9eb8dc commit c20a91c
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions packages/peer-id/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@
import { publicKeyFromMultihash } from '@libp2p/crypto/keys'
import { InvalidCIDError, InvalidMultihashError, InvalidParametersError, UnsupportedKeyTypeError } from '@libp2p/interface'
import { base58btc } from 'multiformats/bases/base58'
import { type CID, type MultibaseDecoder } from 'multiformats/cid'
import { type MultibaseDecoder } from 'multiformats/cid'
import { CID } from 'multiformats/cid'
import * as Digest from 'multiformats/hashes/digest'
import { identity } from 'multiformats/hashes/identity'
import { sha256 } from 'multiformats/hashes/sha2'
Expand All @@ -37,15 +38,26 @@ export function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>):
// identity hash ed25519/secp256k1 key or sha2-256 hash of
// rsa public key - base58btc encoded either way
multihash = Digest.decode(base58btc.decode(`z${str}`))
} else {
if (decoder == null) {
throw new InvalidParametersError('Please pass a multibase decoder for strings that do not start with "1" or "Q"')
}
return peerIdFromMultihash(multihash)
}

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

return peerIdFromMultihash(multihash)
let buf: Uint8Array
try {
buf = decoder.decode(str)
} catch (err) {
throw new InvalidParametersError('The passed PeerID string could not be decoded using the provided multibase decoder')
}

try {
multihash = Digest.decode(buf)
return peerIdFromMultihash(multihash)
} catch (err) {
return peerIdFromCID(CID.decode(buf))
}
}

export function peerIdFromPublicKey (publicKey: Ed25519PublicKey): Ed25519PeerId
Expand Down

0 comments on commit c20a91c

Please sign in to comment.