All files / src/lib fields.ts

84.21% Statements 16/19
33.33% Branches 1/3
100% Functions 4/4
82.35% Lines 14/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 301x 1x   1x 11x 11x   5193x     1x 11x   5193x 11x 11x           11x 11x 11x            
import { Field, Poseidon } from "o1js";
import { fieldToBase64, fieldFromBase64 } from "./base64";
 
export function serializeFields(fields: Field[]): string {
  const hash = Poseidon.hash(fields);
  const value = [Field(fields.length), hash, ...fields];
  //return value.map((f) => f.toBigInt().toString(36)).join(".");
  return value.map((f) => fieldToBase64(f)).join(".");
}
 
export function deserializeFields(s: string): Field[] {
  try {
    //const value = s.split(".").map((n) => Field(BigInt(convert(n, 36))));
    const value = s.split(".").map((n) => fieldFromBase64(n));
    const length = value[0];
    Iif (
      Field(value.length - 2)
        .equals(length)
        .toBoolean() === false
    )
      throw new Error("deserializeFields: invalid length");
    const hash = Poseidon.hash(value.slice(2));
    if (hash.equals(value[1]).toBoolean()) {
      return value.slice(2);
    } else Ethrow new Error("deserializeFields: invalid hash: data mismatch");
  } catch (e: any) {
    throw new Error(`deserializeFields: invalid string: ${s}: ${e}`);
  }
}