Skip to content

peerIdFromString doesn't accept CID encoded PeerIDs #2772

@2color

Description

@2color

Description

Since #2660, an undocumented breaking change was introduced, whereby the peerIdFromString function in @libp2p/peer-id throws an error when a base36 encoded PeerID CID is passed.

This can be attributed specifically to https://github.com/libp2p/js-libp2p/pull/2660/files#diff-03404c4c2b9d68fdd3cc5903cbdc0958a10b3a89c8070f1b498e60492fe6a20dL264.

There are to parts to this problem:

  1. The default composed decoders for from multiformats have been removed.
  2. Even when a base36 decoder is passed in, the function throws for base36 encoded PeerID CIDs, since it attempts to parse it as a multihash (rather than a CID)

The older version would first try to decode the binary digest as a multihash and if that fails, attempt to decode it as a CID:

export function peerIdFromString (str: string, decoder?: MultibaseDecoder<any>): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {
decoder = decoder ?? baseDecoder
if (str.charAt(0) === '1' || str.charAt(0) === 'Q') {
// identity hash ed25519/secp256k1 key or sha2-256 hash of
// rsa public key - base58btc encoded either way
const multihash = Digest.decode(base58btc.decode(`z${str}`))
if (str.startsWith('12D')) {
return new Ed25519PeerIdImpl({ multihash })
} else if (str.startsWith('16U')) {
return new Secp256k1PeerIdImpl({ multihash })
} else {
return new RSAPeerIdImpl({ multihash })
}
}
return peerIdFromBytes(baseDecoder.decode(str))
}
export function peerIdFromBytes (buf: Uint8Array): Ed25519PeerId | Secp256k1PeerId | RSAPeerId | URLPeerId {
try {
const multihash = Digest.decode(buf)
if (multihash.code === identity.code) {
if (multihash.digest.length === MARSHALLED_ED225519_PUBLIC_KEY_LENGTH) {
return new Ed25519PeerIdImpl({ multihash })
} else if (multihash.digest.length === MARSHALLED_SECP256K1_PUBLIC_KEY_LENGTH) {
return new Secp256k1PeerIdImpl({ multihash })
}
}
if (multihash.code === sha256.code) {
return new RSAPeerIdImpl({ multihash })
}
} catch {
return peerIdFromCID(CID.decode(buf))
}
throw new Error('Supplied PeerID CID is invalid')

Proposed solutions & suggestions

  1. Update the example to be working
  2. Update the function to handle CIDs

Metadata

Metadata

Assignees

No one assigned

    Labels

    need/triageNeeds initial labeling and prioritization

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions