Random Principals in Motoko - For Testing

I’m trying to decipher a Principal structure so that I can create some random principals in my tests.

import Principal "mo:base/Principal";
import Blob "mo:base/Blob";
import Debug "mo:base/Debug";

actor Echo  {

  // Say the given phase.
  public shared(msg) func test() : async ([Nat8],Text) {
    Debug.print(debug_show(Principal.fromActor(Echo)));
    return (
        Blob.toArray(
            Principal.toBlob(
                Principal.fromActor(Echo)
            )
        ), Principal.toText(Principal.fromActor(Echo)));
  };
};

This outputs something like (vec {0; 0; 0; 0; 0; 48; 0; 128; 1; 1}, “zwbmv-jyaaa-aaaab-qacaa-cai”). the last two numbers always seem to be 1 and only the 3rd to last and 5th to last seem to change much). What is the best way to be doing this? I seem to remember seeing the structure at some point. Is it 8 bytes and then two bytes of a check sum? How do I produce the check sum? I see libraries out there like motoko-crc/CRC8.mo at master · enzoh/motoko-crc · GitHub but they look old. Can I just swap out Word8 for Nat8 and spend a hash to a crc check of the hash like in Cyclic Redundancy Checks?

The principal format is speced here: The Internet Computer Interface Specification :: Internet Computer

If you need some random identities, you can use ic-repl's identity command. For example, here is the test script we use for CanCan: cancan/accessControl.test.sh at main · dfinity/cancan · GitHub

2 Likes