Skip to content

Commit

Permalink
Some renaming + changes to the password tree program
Browse files Browse the repository at this point in the history
  • Loading branch information
adamczykm committed Oct 2, 2023
1 parent 33b3edb commit 230514e
Show file tree
Hide file tree
Showing 5 changed files with 144 additions and 102 deletions.
22 changes: 11 additions & 11 deletions src/library/plugin/pluginType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,20 @@ import z from 'zod';

// Interfaces used on the server side.

export interface IMinAuthPlugin<PublicInputsArgs, Output> {
export interface IMinAuthPlugin<PublicInputArgs, Output> {
// Verify a proof give the arguments for fetching public inputs, and return
// the output.
verifyAndGetOutput(
publicInputArgs: PublicInputsArgs,
publicInputArgs: PublicInputArgs,
serializedProof: JsonProof): Promise<Output>;

// The schema of the arguments for fetching public inputs.
readonly publicInputArgsSchema: z.ZodType<PublicInputsArgs>;
readonly publicInputArgsSchema: z.ZodType<PublicInputArgs>;

// TODO: enable plugins to invalidate a proof.
// FIXME(Connor): I still have some questions regarding the validation functionality.
// In particular, what if a plugin want to invalidate the proof once the public inputs change?
// We have to at least pass PublicInputsArgs.
// We have to at least pass PublicInputArgs.
//
// checkOutputValidity(output: Output): Promise<boolean>;

Expand All @@ -30,8 +30,8 @@ export interface IMinAuthPlugin<PublicInputsArgs, Output> {

// TODO: generic type inference?
export interface IMinAuthPluginFactory<
T extends IMinAuthPlugin<PublicInputsArgs, Output>,
Configuration, PublicInputsArgs, Output> {
T extends IMinAuthPlugin<PublicInputArgs, Output>,
Configuration, PublicInputArgs, Output> {

// Initialize the plugin given the configuration. The underlying zk program is
// typically compiled here.
Expand All @@ -42,20 +42,20 @@ export interface IMinAuthPluginFactory<

// Interfaces used on the client side.

export interface IMinAuthProver<PublicInputsArgs, PublicInput, PrivateInput> {
export interface IMinAuthProver<PublicInputArgs, PublicInput, PrivateInput> {
prove(publicInput: PublicInput, secretInput: PrivateInput): Promise<JsonProof>;

fetchPublicInputs(args: PublicInputsArgs): Promise<PublicInput>;
fetchPublicInputs(args: PublicInputArgs): Promise<PublicInput>;
}

export interface IMinAuthProverFactory<
T extends IMinAuthProver<
PublicInputsArgs,
PublicInputArgs,
PublicInput,
PrivateInput>,
Configuration,
PublicInputsArgs,
PublicInputArgs,
PublicInput,
PrivateInput> {
initialize(cfg: Configuration): Promise<T>;
}
}
4 changes: 2 additions & 2 deletions src/library/tools/pluginServer/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import env from 'env-var';
import fs from 'fs';
import yaml from 'yaml';
import { SimplePreimagePlugin } from "./plugins/simplePreimage/server";
import { SimplePasswordTreePlugin } from "./plugins/passwordTree/server";
import { MemberSetPlugin } from "./plugins/passwordTree/server";

// TODO: make use of heterogeneous lists
/**
Expand All @@ -15,7 +15,7 @@ export const untypedPlugins:
IMinAuthPluginFactory<IMinAuthPlugin<any, any>, any, any, any>>
= {
"SimplePreimagePlugin": SimplePreimagePlugin,
"SimplePasswordTreePlugin": SimplePasswordTreePlugin
"MemberSetPlugin": MemberSetPlugin
};

const serverConfigurationsSchema = z.object({
Expand Down
91 changes: 47 additions & 44 deletions src/plugins/passwordTree/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,58 +1,61 @@
// TODO requires changes
import { Field, JsonProof } from "o1js";
import ProvePasswordInTreeProgram, { PasswordTreePublicInput, PasswordTreeWitness } from "../common/passwordTreeProgram";
import ProvePasswordInTreeProgram, { PasswordInTreeWitness } from "../common/passwordTreeProgram";
import { IMinAuthProver, IMinAuthProverFactory } from '../../../library/plugin/pluginType';

import axios from "axios";

export type SimplePasswordTreeProverConfiguration = {
apiServer: URL,
export type MemberSetProverConfiguration = {
apiServer: URL,
}

export class SimplePasswordTreeProver implements
IMinAuthProver<bigint, PasswordTreePublicInput, Field>

// Prove that you belong to a set of user without revealing which user you are.
export class MemberSetProver implements
IMinAuthProver<bigint, PasswordInTreeWitness, Field>
{
private readonly cfg: SimplePasswordTreeProverConfiguration;

async prove(publicInput: PasswordTreePublicInput, secretInput: Field)
: Promise<JsonProof> {
const proof = await ProvePasswordInTreeProgram.baseCase(
publicInput, Field.from(secretInput));
return proof.toJSON();
}

async fetchPublicInputs(uid: bigint): Promise<PasswordTreePublicInput> {
const mkUrl = (endpoint: string) => `${this.cfg.apiServer}/${endpoint}`;
const getWitness = async (): Promise<PasswordTreeWitness> => {
const resp = await axios.get(mkUrl(`/witness/${uid.toString()}`));
if (resp.status != 200) {
throw `unable to fetch witness for ${uid.toString()}, error: ${(resp.data as { error: string }).error}`;
}
return PasswordTreeWitness.fromJSON(resp.data);
};
const getRoot = async (): Promise<Field> => {
const resp = await axios.get(mkUrl('/root'));
return Field.fromJSON(resp.data);
private readonly cfg: MemberSetProverConfiguration;

async prove(publicInput: PasswordInTreeWitness, secretInput: Field)
: Promise<JsonProof> {
const proof = await ProvePasswordInTreeProgram.baseCase(
publicInput, Field.from(secretInput));
return proof.toJSON();
}
const witness = await getWitness();
const root = await getRoot();

return new PasswordTreePublicInput({ witness, root });
}
async fetchPublicInputs(uid: bigint): Promise<PasswordInTreeWitness> {
const mkUrl = (endpoint: string) => `${this.cfg.apiServer}/${endpoint}`;
const getWitness = async (): Promise<PasswordInTreeWitness> => {
const resp = await axios.get(mkUrl(`/witness/${uid.toString()}`));
if (resp.status != 200) {
throw `unable to fetch witness for ${uid.toString()}, error: ${(resp.data as { error: string }).error}`;
}
return PasswordInTreeWitness.fromJSON(resp.data);
};
const getRoot = async (): Promise<Field> => {
const resp = await axios.get(mkUrl('/root'));
return Field.fromJSON(resp.data);
}
const witness = await getWitness();
const root = await getRoot();

return new PasswordInTreeWitness({ witness, root });
}

constructor(cfg: SimplePasswordTreeProverConfiguration) {
this.cfg = cfg;
}
constructor(cfg: MemberSetProverConfiguration) {
this.cfg = cfg;
}

static async initialize(cfg: SimplePasswordTreeProverConfiguration):
Promise<SimplePasswordTreeProver> {
return new SimplePasswordTreeProver(cfg);
}
static async initialize(cfg: MemberSetProverConfiguration):
Promise<MemberSetProver> {
return new MemberSetProver(cfg);
}
}

SimplePasswordTreeProver satisfies IMinAuthProverFactory<
SimplePasswordTreeProver,
SimplePasswordTreeProverConfiguration,
bigint,
PasswordTreePublicInput,
Field
>
MemberSetProver satisfies IMinAuthProverFactory<
MemberSetProver,
MemberSetProverConfiguration,
bigint,
PasswordInTreeWitness,
Field
>
68 changes: 48 additions & 20 deletions src/plugins/passwordTree/common/passwordTreeProgram.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,57 @@
import { Experimental, Field, MerkleWitness, Poseidon, Struct } from "o1js";
import { Experimental, Field, MerkleWitness, Poseidon, SelfProof, Struct } from "o1js";

// TODO how can this be made dynamic
export const PASSWORD_TREE_HEIGHT = 10;

export class PasswordTreeWitness extends MerkleWitness(PASSWORD_TREE_HEIGHT) { }
export class PasswordTreeWitness extends MerkleWitness(PASSWORD_TREE_HEIGHT) {}

export class PasswordTreePublicInput extends Struct({
witness: PasswordTreeWitness,
root: Field
}) { };
export class PasswordInTreeWitness extends Struct({
witness: PasswordTreeWitness,
preImage: Field
}) {};

export class MerkleRoot extends Struct({
root: Field
}) {};


export class ProvePasswordInTreeOutput extends Struct({
recursiveMekleRootHash: Field,
}) {};

// Prove knowledge of a preimage of a hash in a merkle tree.
// The proof does not reveal the preimage nor the hash.
// The output contains a recursive hash of all the roots for which the preimage is known.
// output = hash(lastRoot + hash(secondLastRoot, ... hash(xLastRoot, lastRoot) ...)
// Therefore the order of the proofs matters.
export const ProvePasswordInTreeProgram = Experimental.ZkProgram({
publicInput: PasswordTreePublicInput,
publicOutput: Field,

methods: {
baseCase: {
privateInputs: [Field],
method(publicInput: PasswordTreePublicInput, privateInput: Field): Field {
publicInput.witness
.calculateRoot(Poseidon.hash([privateInput]))
.assertEquals(publicInput.root);
return publicInput.witness.calculateIndex();
}
publicInput: MerkleRoot,
publicOutput: ProvePasswordInTreeOutput,

methods: {
baseCase: {
privateInputs: [PasswordInTreeWitness],
method(publicInput: MerkleRoot, privateInput: PasswordInTreeWitness): ProvePasswordInTreeOutput {
privateInput.witness
.calculateRoot(Poseidon.hash([publicInput.root]))
.assertEquals(publicInput.root);
return new ProvePasswordInTreeOutput(
{ recursiveMekleRootHash: publicInput.root });
}
},

inductiveCase: {
privateInputs: [SelfProof, PasswordInTreeWitness],
method(publicInput: MerkleRoot, earlierProof: SelfProof<MerkleRoot, ProvePasswordInTreeOutput>, privateInput: PasswordInTreeWitness): ProvePasswordInTreeOutput {
earlierProof.verify();
privateInput.witness
.calculateRoot(Poseidon.hash([publicInput.root]))
.assertEquals(publicInput.root);
return new ProvePasswordInTreeOutput(
{ recursiveMekleRootHash: Poseidon.hash([publicInput.root, earlierProof.publicOutput.recursiveMekleRootHash]) });
}
}
}
}
});

export default ProvePasswordInTreeProgram;
export default ProvePasswordInTreeProgram;
61 changes: 36 additions & 25 deletions src/plugins/passwordTree/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,30 +184,39 @@ class MinaBlockchainStorage
}
}

export class SimplePasswordTreePlugin implements IMinAuthPlugin<bigint, string>{
const PoseidonHashSchema = z.bigint();

const publicInputArgsSchema = z.array(PoseidonHashSchema);

export class MemberSetPlugin implements IMinAuthPlugin<z.infer<typeof publicInputArgsSchema>, string>{
readonly verificationKey: string;
private readonly storage: TreeStorage

customRoutes: Record<string, RequestHandler> = {
"/witness/:uid": async (req, resp) => {
if (req.method != 'GET') {
resp.status(400);
return;
}

const uid = BigInt(req.params['uid']);
const witness = await this.storage.getWitness(uid);

if (!witness) {
resp
.status(400)
.json({ error: "requested user doesn't exist" });
return;
}

resp.status(200).json(witness);
},
"/root": async (req, resp) => {
// NOTE: witnesses are not public inputs now
// "/witness/:uid": async (req, resp) => {
// if (req.method != 'GET') {
// resp.status(400);
// return;
// }

// const uid = BigInt(req.params['uid']);
// const witness = await this.storage.getWitness(uid);

// if (!witness) {
// resp
// .status(400)
// .json({ error: "requested user doesn't exist" });
// return;
// }

// resp.status(200).json(witness);
// },

// TODO:
// input: array of merkle roots (eg. [root1, root2, root3])
// output: object of the form { root1: tree1, root2: tree2, root3: tree3 }
"/roots": async (req, resp) => {
if (req.method != 'GET') {
resp.status(400);
return;
Expand All @@ -228,10 +237,12 @@ export class SimplePasswordTreePlugin implements IMinAuthPlugin<bigint, string>{
}
};

publicInputArgsSchema: z.ZodType<bigint> = z.bigint();
publicInputArgsSchema = publicInputArgsSchema;

async verifyAndGetOutput(uid: bigint, jsonProof: JsonProof):
async verifyAndGetOutput(uid: z.infer<typeof publicInputArgsSchema>, jsonProof: JsonProof):
Promise<string> {

// build an array of merkle trees
const proof = PasswordInTreeProofClass.fromJSON(jsonProof);
const expectedWitness = await this.storage.getWitness(uid);
const expectedRoot = await this.storage.getRoot();
Expand All @@ -253,15 +264,15 @@ export class SimplePasswordTreePlugin implements IMinAuthPlugin<bigint, string>{
storageFile: string,
contractPrivateKey: string,
feePayerPrivateKey: string
}): Promise<SimplePasswordTreePlugin> {
}): Promise<MemberSetPlugin> {
const { verificationKey } = await ProvePasswordInTreeProgram.compile();
const storage = await MinaBlockchainStorage
.initialize(
configuration.storageFile,
PrivateKey.fromBase58(configuration.contractPrivateKey),
PrivateKey.fromBase58(configuration.feePayerPrivateKey)
)
return new SimplePasswordTreePlugin(verificationKey, storage);
return new MemberSetPlugin(verificationKey, storage);
}

static readonly configurationSchema:
Expand All @@ -277,7 +288,7 @@ export class SimplePasswordTreePlugin implements IMinAuthPlugin<bigint, string>{
})
}

SimplePasswordTreePlugin satisfies
MemberSetPlugin satisfies
IMinAuthPluginFactory<
IMinAuthPlugin<bigint, string>,
{
Expand Down

0 comments on commit 230514e

Please sign in to comment.