I either forgot about it or never had to do it before, but how do you validate that a Principal
created using Principal.fromUint8Array
is actually a valid Principal
?
Asking because, for example, Principal.fromUint8Array(Uint8Array.from([1, 2, 3]))
does not throw an error but, does not seem like a valid Principal
right?
I’ll might just parse it with toText()
after creation to validate it, but I’m not sure if it’s the cleanest or most performant approach.
As far as I can see in the interface spec, there’s a max length but not a minimum length: The Internet Computer Interface Specification | Internet Computer
Normally you’d use the crcr32 checksum from the textual representation to validate user input. But with raw bytes instead of textual input there’s no checksum, since the checksum is there to catch mistakes in textual input specifically.
Right thanks. Somehow, while debugging yesterday, I had the impression that toText
was throwing an error after constructing a principal from a few numbers, but it actually wasn’t, which leads me to think there was a way to distinguish between valid and invalid ones.
Besides checking the amount of bytes you can also verify the last byte is one of the allowed ones. The spec currently lists 0x01, 0x02, 0x03, 0x04, 0x07
, all others can’t be valid principals.
1 Like
Nice, and it’s relatively cheap in terms of perf. Thanks for the tips!