A regex / json-schema pattern for an IPFS CID?

Viewed 929

I'd like to include a pattern for an ipfs content identifier (CID) in a json schema. To do this, I need to create a regex to match them.

{
    "$schema": "http://json-schema.org/draft-07/schema#",
    "$id": "http://json-schema.org/draft-07/schema#",
    "title": "Example schema with an ipfs CID",
    { "type": "object",
      "properties": {
          "ipfs":  { "type": "string","pattern": "<CID regex here>"}
      }
}

What is a good way to do a regex for an IPFS CID?

1 Answers

For CIDv0:

the multibase of the string representation is always base58btc

E.g. QmcRD4wkPPi6dig81r5sLj9Zm1gDCL4zgpEj9CfuRrGbzF

Qm[1-9A-Za-z]{44}[^OIl]

seems to work

For CIDv1, the encoding changes conditional on the first character (below are encodings with default status):

> *encoding*             *code*                               
> identity               0x00
> base16                 f
> base16upper            F
> hexadecimal base32     b
> base32upper            B
> base58btc              z
> base64                 m   
> base64url              u
> base64urlpad           U

e.g. bafybeigrf2dwtpjkiovnigysyto3d55opf6qkdikx6d65onrqnfzwgdkfa

has hexadecimal base32 encoding after the b

This means that the regex would have to have a conditional element based on the first character.

Also, I think I'm right to say that the length of a CIDv1 changes based on the selected hash algorithm. This answer is constrained to hash algorithms with 256 bit output only.

This approach splits up the regex with OR | operators:

Qm[1-9A-HJ-NP-Za-km-z]{44,}|b[A-Za-z2-7]{58,}|B[A-Z2-7]{58,}|z[1-9A-HJ-NP-Za-km-z]{48,}|F[0-9A-F]{50,}

Perhaps there is a better way, though.

Related