All files / src redactedtree.ts

67.08% Statements 53/79
10% Branches 1/10
66.66% Functions 4/6
69.86% Lines 51/73

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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 17527x 27x                   27x 27x       27x 27x           1x                   1x     1x 1x 1x 1x               14x 14x       1x 1x 1x 1x     1x 1x 1x                   1x 1x 1x 1x 1x 1x 1x 14x 14x     14x     14x           14x         14x           14x 14x   1x 1x   1x 1x 1x 13x 13x         13x         13x 13x   1x 1x 1x 1x     1x                                                                                        
export { RedactedTree };
import {
  verify,
  PrivateKey,
  AccountUpdate,
  Mina,
  Account,
  MerkleTree,
  Field,
  VerificationKey,
} from "o1js";
import { MinaNFT } from "./minanft";
import {
  MinaNFTTreeVerifierFunction,
  TreeElement,
} from "./plugins/redactedtree";
import { Memory, sleep } from "./mina";
import { fetchMinaAccount } from "./fetch";
 
class RedactedTree {
  height: number;
  originalTree: MerkleTree;
  redactedTree: MerkleTree;
  leafs: { key: number; value: Field }[] = [];
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  contracts: any;
  /*
      RedactedMinaNFTTreeState,
      RedactedMinaNFTTreeCalculation,
      MinaNFTTreeVerifier,
      MerkleTreeWitness,
      RedactedMinaNFTTreeStateProof,
  */
  verificationKey: VerificationKey | undefined = undefined;
 
  constructor(height: number, originalTree: MerkleTree) {
    this.height = height;
    this.originalTree = originalTree;
    this.redactedTree = new MerkleTree(height);
    this.contracts = MinaNFTTreeVerifierFunction(height);
  }
 
  /**
   * copy public attribute
   * @param key key of the attribute
   */
  public set(key: number, value: Field): void {
    this.redactedTree.setLeaf(BigInt(key), value);
    this.leafs.push({ key, value });
  }
 
  public async compile(): Promise<VerificationKey> {
    Iif (this.verificationKey !== undefined) return this.verificationKey;
    console.time(`compiled RedactedTreeCalculation`);
    await sleep(100); // alow GC to run
    const verificationKey = (
      await this.contracts.RedactedMinaNFTTreeCalculation.compile()
    ).verificationKey;
    console.timeEnd(`compiled RedactedTreeCalculation`);
    this.verificationKey = verificationKey;
    return verificationKey;
  }
 
  /**
   *
   * @returns proof
   */
  // eslint-disable-next-line @typescript-eslint/no-inferrable-types
  public async proof(verbose: boolean = false) {
    class TreeStateProof extends this.contracts.RedactedMinaNFTTreeStateProof {}
    const verificationKey = await this.compile();
    console.time(`calculated proofs`);
    console.log(`calculating ${this.leafs.length} proofs...`);
    const originalRoot = this.originalTree.getRoot();
    const redactedRoot = this.redactedTree.getRoot();
    const proofs: TreeStateProof[] = [];
    for (let i = 0; i < this.leafs.length; i++) {
      await sleep(100); // alow GC to run
      const originalWitness = new this.contracts.MerkleTreeWitness(
        this.originalTree.getWitness(BigInt(this.leafs[i].key))
      );
      const redactedWitness = new this.contracts.MerkleTreeWitness(
        this.redactedTree.getWitness(BigInt(this.leafs[i].key))
      );
      const element = new TreeElement({
        originalRoot,
        redactedRoot,
        index: Field(this.leafs[i].key),
        value: this.leafs[i].value,
      });
      const state = this.contracts.RedactedMinaNFTTreeState.create(
        element,
        originalWitness,
        redactedWitness
      );
      const proof = await this.contracts.RedactedMinaNFTTreeCalculation.create(
        state,
        element,
        originalWitness,
        redactedWitness
      );
      proofs.push(proof);
      Iif (verbose) Memory.info(`proof ${i} calculated`);
    }
    console.timeEnd(`calculated proofs`);
    Memory.info(`calculated proofs`);
 
    console.time(`merged proofs`);
    let proof: TreeStateProof = proofs[0];
    for (let i = 1; i < proofs.length; i++) {
      await sleep(100); // alow GC to run
      const state = this.contracts.RedactedMinaNFTTreeState.merge(
        proof.publicInput,
        proofs[i].publicInput
      );
      const mergedProof =
        await this.contracts.RedactedMinaNFTTreeCalculation.merge(
          state,
          proof,
          proofs[i]
        );
      proof = mergedProof;
      Iif (verbose) Memory.info(`proof ${i} merged`);
    }
    console.timeEnd(`merged proofs`);
    Memory.info(`merged proofs`);
    const ok = verify(proof, verificationKey);
    Iif (!ok) {
      throw new Error("proof verification failed");
    }
    return proof;
  }
 
  public async deploy(
    deployer: PrivateKey,
    privateKey: PrivateKey,
    nonce?: number
  ): Promise<Mina.PendingTransaction | undefined> {
    const sender = deployer.toPublicKey();
    const zkAppPrivateKey = privateKey;
    const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
    await this.contracts.MinaNFTTreeVerifier.compile();
    console.log(
      `deploying the MinaNFTTreeVerifier contract to an address ${zkAppPublicKey.toBase58()} using the deployer with public key ${sender.toBase58()}...`
    );
    await fetchMinaAccount({ publicKey: sender });
    await fetchMinaAccount({ publicKey: zkAppPublicKey });
    const deployNonce =
      nonce ?? Number(Mina.getAccount(sender).nonce.toBigint());
    const hasAccount = Mina.hasAccount(zkAppPublicKey);
 
    const zkApp = new this.contracts.MinaNFTTreeVerifier(zkAppPublicKey);
    const transaction = await Mina.transaction(
      {
        sender,
        fee: await MinaNFT.fee(),
        memo: "minanft.io",
        nonce: deployNonce,
      },
      async () => {
        Iif (!hasAccount) AccountUpdate.fundNewAccount(sender);
        await zkApp.deploy({});
        zkApp.account.tokenSymbol.set("VERIFY");
        zkApp.account.zkappUri.set("https://minanft.io/@treeverifier");
      }
    );
    transaction.sign([deployer, zkAppPrivateKey]);
    const tx = await transaction.send();
    await MinaNFT.transactionInfo(tx, "verifier deploy", false);
    if (tx.status === "pending") {
      return tx;
    } else return undefined;
  }
}