All files / src redactedminanft.ts

79.34% Statements 73/92
50% Branches 6/12
54.54% Functions 6/11
80.23% Lines 69/86

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 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 1997x 7x 7x   7x 7x 7x           7x 7x 7x           3x 3x               4x 4x                       3x       3x   3x 3x 3x 3x 3x 4x 4x 4x 4x           4x 4x 4x     3x 3x 4x 4x         4x           4x 4x   3x 3x     3x 3x 1x 1x         1x 1x 1x 1x   3x   3x       3x           3x       3x                                                                                         2x 2x 2x 2x 2x     2x 2x   2x 2x   2x 2x               4x 4x 4x 4x     2x 2x 2x 2x 2x        
export { RedactedMinaNFT };
import { verify, Proof, PrivateKey, AccountUpdate, Mina, Account } from "o1js";
import { BaseMinaNFT } from "./baseminanft";
import { PrivateMetadata } from "./privatemetadata";
import { MinaNFT } from "./minanft";
import { Metadata, MetadataWitness } from "./contract/metadata";
import {
  RedactedMinaNFTMapCalculation,
  RedactedMinaNFTMapState,
  RedactedMinaNFTMapStateProof,
  MapElement,
} from "./plugins/redactedmap";
import { MinaNFTVerifier } from "./plugins/verifier";
import { Memory, sleep } from "./mina";
import { fetchMinaAccount } from "./fetch";
 
class RedactedMinaNFT extends BaseMinaNFT {
  nft: BaseMinaNFT;
 
  constructor(nft: BaseMinaNFT) {
    super();
    this.nft = nft;
  }
 
  /**
   * copy public attribute
   * @param key key of the attribute
   */
  public copyMetadata(key: string) {
    const value: PrivateMetadata | undefined = this.nft.getMetadata(key);
    if (value) this.metadata.set(key, value);
    else Ethrow new Error("Map error");
  }
 
  /**
   *
   * @returns proof
   */
  public async proof(
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types
    verbose: boolean = false
  ): Promise<RedactedMinaNFTMapStateProof> {
    await MinaNFT.compileRedactedMap();
 
    //console.log("Creating proof for redacted maps...");
 
    const { root, map } = this.getMetadataRootAndMap();
    const { root: originalRoot, map: originalMap } =
      this.nft.getMetadataRootAndMap();
    const elements: MapElement[] = [];
    let originalWitnesses: MetadataWitness[] = [];
    let redactedWitnesses: MetadataWitness[] = [];
    this.metadata.forEach((value: PrivateMetadata, key: string) => {
      const keyField = MinaNFT.stringToField(key);
      const redactedWitness = map.getWitness(keyField);
      const originalWitness = originalMap.getWitness(keyField);
      const element: MapElement = new MapElement({
        originalRoot: originalRoot,
        redactedRoot: root,
        key: keyField,
        value: new Metadata({ data: value.data, kind: value.kind }),
      });
      elements.push(element);
      originalWitnesses.push(originalWitness);
      redactedWitnesses.push(redactedWitness);
    });
 
    let proofs: Proof<RedactedMinaNFTMapState, void>[] = [];
    for (let i = 0; i < elements.length; i++) {
      await sleep(100); // alow GC to run
      const state = RedactedMinaNFTMapState.create(
        elements[i],
        originalWitnesses[i],
        redactedWitnesses[i]
      );
      const proof = await RedactedMinaNFTMapCalculation.create(
        state,
        elements[i],
        originalWitnesses[i],
        redactedWitnesses[i]
      );
      proofs.push(proof);
      Iif (verbose) Memory.info(`Proof ${i + 1}/${elements.length} created`);
    }
    originalWitnesses = [];
    redactedWitnesses = [];
 
    //console.log("Merging redacted proofs...");
    let proof: RedactedMinaNFTMapStateProof = proofs[0];
    for (let i = 1; i < proofs.length; i++) {
      await sleep(100); // alow GC to run
      const state = RedactedMinaNFTMapState.merge(
        proof.publicInput,
        proofs[i].publicInput
      );
      let mergedProof: RedactedMinaNFTMapStateProof | null =
        await RedactedMinaNFTMapCalculation.merge(state, proof, proofs[i]);
      proof = mergedProof;
      mergedProof = null;
      Iif (verbose) Memory.info(`Proof ${i}/${proofs.length - 1} merged`);
    }
    proofs = [];
 
    Iif (MinaNFT.redactedMapVerificationKey === undefined) {
      throw new Error("Redacted map verification key is missing");
    }
 
    const verificationResult: boolean = await verify(
      proof.toJSON(),
      MinaNFT.redactedMapVerificationKey
    );
 
    //console.log("Proof verification result:", verificationResult);
    Iif (verificationResult === false) {
      throw new Error("Proof verification error");
    }
 
    return proof;
  }
 
  /**
   *
   * @returns proof
   */
  public async prepareProofData(): Promise<string[]> {
    const { root, map } = this.getMetadataRootAndMap();
    const { root: originalRoot, map: originalMap } =
      this.nft.getMetadataRootAndMap();
    const transactions: string[] = [];
    //const elements: MapElement[] = [];
    //let originalWitnesses: MetadataWitness[] = [];
    //let redactedWitnesses: MetadataWitness[] = [];
    this.metadata.forEach((value: PrivateMetadata, key: string) => {
      const keyField = MinaNFT.stringToField(key);
      const redactedWitness = map.getWitness(keyField);
      const originalWitness = originalMap.getWitness(keyField);
      const element: MapElement = new MapElement({
        originalRoot: originalRoot,
        redactedRoot: root,
        key: keyField,
        value: new Metadata({ data: value.data, kind: value.kind }),
      });
      transactions.push(
        JSON.stringify({
          element: MapElement.toFields(element).map((f) => f.toJSON()),
          originalWitness: MetadataWitness.toFields(originalWitness).map((f) =>
            f.toJSON()
          ),
          redactedWitness: MetadataWitness.toFields(redactedWitness).map((f) =>
            f.toJSON()
          ),
        })
      );
    });
    return transactions;
  }
 
  public static async deploy(
    deployer: PrivateKey,
    privateKey: PrivateKey,
    nonce?: number
  ): Promise<Mina.PendingTransaction | undefined> {
    const sender = deployer.toPublicKey();
    const zkAppPrivateKey = privateKey;
    const zkAppPublicKey = zkAppPrivateKey.toPublicKey();
    await MinaNFT.compileVerifier();
    console.log(
      `deploying the MinaNFTVerifier 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 MinaNFTVerifier(zkAppPublicKey);
    const transaction = await Mina.transaction(
      {
        sender,
        fee: await MinaNFT.fee(),
        memo: "minanft.io",
        nonce: deployNonce,
      },
      async () => {
        if (!hasAccount) AccountUpdate.fundNewAccount(sender);
        await zkApp.deploy({});
        zkApp.account.tokenSymbol.set("VERIFY");
        zkApp.account.zkappUri.set("https://minanft.io/@verifier");
      }
    );
    transaction.sign([deployer, zkAppPrivateKey]);
    const tx = await transaction.send();
    await MinaNFT.transactionInfo(tx, "verifier deploy", false);
    if (tx.status === "pending") {
      return tx;
    } else Ereturn undefined;
  }
}