1

I am wondering if someone can help me with regex for validating all types xpubs like:

  • xpub (mainnet P2PKH or P2SH)
  • ypub (mainnet P2WPKH in P2SH)
  • Ypub (mainnet P2WSH in P2SH)
  • zpub (mainnet P2WPKH)
  • Zpub (mainnet P2WSH)
  • tpub (testnet P2PKH or P2SH)
  • upub (testnet P2WPKH in P2SH)
  • Upub (testnet P2WSH in P2SH)
  • vpub (testnet P2WPKH)
  • Vpub (testnet P2WSH)

Thank you.

1 Answer 1

2

The following regex should work for validating that a string starts with one of xpub, ypub, Ypub, zpub, Zpub, tpub, upub, Upub, vpub or Vpub and is followed by 79-108 characters that are one of 123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz (the Base58 alphabet) which is as close as you can get to validating BIP32 keys with regex:

^([xyYzZtuUvV]pub[1-9A-HJ-NP-Za-km-z]{79,108})$

(try at: https://regexr.com/6cn9a)

If you want to accept BIP32 keys that optionally include the ?c={timestamp}&h={bip} arguments, then add (?:(?:$|\?)((?!.*&c=)c=\d{10}|(?!.*&h=)h=bip\d{2,3})(?:(?=(?:&c=|&h=))&(c=\d{10}|h=bip\d{2,3}))?)? at the end, like this:

^([xyYzZtuUvV]pub[1-9A-HJ-NP-Za-km-z]{79,108})(?:(?:$|\?)((?!.*&c=)c=\d{10}|(?!.*&h=)h=bip\d{2,3})(?:(?=(?:&c=|&h=))&(c=\d{10}|h=bip\d{2,3}))?)?$

(try at: https://regexr.com/6cn9s - this will check that c is a valid 10-digit UNIX timestamp, h is bip{2-3 digit number}, that there is at most one of each parameter, and allow parameters to be in either order.)

However, a more accurate way to test that a BIP32 key is valid is to simply decode it with Base58Check (similar to how regular Bitcoin addresses are encoded), verify that the checksum is valid, and check that the length of the decoded data is exactly 78 bytes.

1
  • You could factor pub out of the brackets btw :)
    – meshcollider
    Jan 4, 2022 at 3:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.