@zk-email/sdk 0.0.84 → 0.0.85-0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +5 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
@@ -24,6 +24,7 @@ type BlueprintProps = {
|
|
24
24
|
status?: Status;
|
25
25
|
verifierContract?: VerifierContract;
|
26
26
|
version?: number;
|
27
|
+
stars?: number;
|
27
28
|
};
|
28
29
|
type DecomposedRegex = {
|
29
30
|
parts: DecomposedRegexPart[];
|
@@ -116,6 +117,7 @@ type BlueprintResponse = {
|
|
116
117
|
verifier_contract_address: string;
|
117
118
|
verifier_contract_chain: number;
|
118
119
|
version: number;
|
120
|
+
stars: number;
|
119
121
|
};
|
120
122
|
type ServerDate = {
|
121
123
|
seconds: number;
|
@@ -139,6 +141,7 @@ type ListBlueprintsOptions = {
|
|
139
141
|
skip?: number;
|
140
142
|
limit?: number;
|
141
143
|
sort?: -1 | 1;
|
144
|
+
sortBy?: "updatedAt" | "stars";
|
142
145
|
status?: Status[];
|
143
146
|
isPublic?: boolean;
|
144
147
|
search?: string;
|
@@ -147,6 +150,7 @@ type ListBlueprintsOptionsRequest = {
|
|
147
150
|
skip?: number;
|
148
151
|
limit?: number;
|
149
152
|
sort?: -1 | 1;
|
153
|
+
sort_by?: "updated_at" | "stars";
|
150
154
|
status?: Status[];
|
151
155
|
is_public?: boolean;
|
152
156
|
search?: string;
|
@@ -361,7 +365,7 @@ declare class Blueprint {
|
|
361
365
|
* @param options - Options to filter the blueprints by.
|
362
366
|
* @returns A promise. Once it resolves, `getId` can be called.
|
363
367
|
*/
|
364
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth
|
368
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
365
369
|
/**
|
366
370
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
367
371
|
* and start the compilation.
|
package/dist/index.d.ts
CHANGED
@@ -24,6 +24,7 @@ type BlueprintProps = {
|
|
24
24
|
status?: Status;
|
25
25
|
verifierContract?: VerifierContract;
|
26
26
|
version?: number;
|
27
|
+
stars?: number;
|
27
28
|
};
|
28
29
|
type DecomposedRegex = {
|
29
30
|
parts: DecomposedRegexPart[];
|
@@ -116,6 +117,7 @@ type BlueprintResponse = {
|
|
116
117
|
verifier_contract_address: string;
|
117
118
|
verifier_contract_chain: number;
|
118
119
|
version: number;
|
120
|
+
stars: number;
|
119
121
|
};
|
120
122
|
type ServerDate = {
|
121
123
|
seconds: number;
|
@@ -139,6 +141,7 @@ type ListBlueprintsOptions = {
|
|
139
141
|
skip?: number;
|
140
142
|
limit?: number;
|
141
143
|
sort?: -1 | 1;
|
144
|
+
sortBy?: "updatedAt" | "stars";
|
142
145
|
status?: Status[];
|
143
146
|
isPublic?: boolean;
|
144
147
|
search?: string;
|
@@ -147,6 +150,7 @@ type ListBlueprintsOptionsRequest = {
|
|
147
150
|
skip?: number;
|
148
151
|
limit?: number;
|
149
152
|
sort?: -1 | 1;
|
153
|
+
sort_by?: "updated_at" | "stars";
|
150
154
|
status?: Status[];
|
151
155
|
is_public?: boolean;
|
152
156
|
search?: string;
|
@@ -361,7 +365,7 @@ declare class Blueprint {
|
|
361
365
|
* @param options - Options to filter the blueprints by.
|
362
366
|
* @returns A promise. Once it resolves, `getId` can be called.
|
363
367
|
*/
|
364
|
-
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth
|
368
|
+
static listBlueprints(baseUrl: string, options?: ListBlueprintsOptions, auth?: Auth): Promise<Blueprint[]>;
|
365
369
|
/**
|
366
370
|
* Submits a blueprint. This will save the blueprint if it didn't exist before
|
367
371
|
* and start the compilation.
|
package/dist/index.js
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils');function $(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function g(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:$(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var P=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(P||{});var A="Ov23li0KABFCUsxBEQkn";function U(n,e=A){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function m(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var f="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",_;new Promise(n=>{_=n;});relayerUtils.init().then(()=>{_(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function h(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function B(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([a,l])=>{l&&s.append(a,String(l));}),s.size>0&&(r+=`?${s.toString()}`);}let i=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}catch(r){throw console.error("GET Error:",r),r}}async function b(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("DELETE Error:",r),r}}function O(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var d=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await g(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await u(`${t}/proof/${e}`);}catch(s){throw console.error("Failed calling /proof/:id in getProofById: ",s),s}let r=this.responseToProofProps(o),i=await c.getBlueprintById(o.blueprint_id,t);return new n(i,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var E,w=new Promise(n=>{E=n;});relayerUtils.init().then(()=>{E(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function I(n){try{return await w,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function z(n,e,t=!1){let o=await I(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let i=o.canonicalizedHeader;return await N(i,r,e),await Promise.all(e.decomposedRegexes.map(a=>v(r,i,a,t)))}async function N(n,e,t){await w;let o=new TextEncoder,r=o.encode(n);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let s=o.encode(e),a=(e.length+63+65)/64*64,l=Math.max(a,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(s,l)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function v(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.regex_def}))},i;if(t.location==="body")i=n;else if(t.location==="header")i=e;else throw Error(`Unsupported location ${t.location}`);let s="maxLength"in t?t.maxLength:t.max_length;await w;let a=relayerUtils.extractSubstr(i,r,!1);if(a[0].length>s)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(i,r,o):a}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let i=e.map(a=>({...a,parts:a.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),s=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,r);return JSON.stringify(Object.fromEntries(s))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var y=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let a={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,t,a);}catch(a){throw console.error("Failed to generate inputs for proof"),a}console.log("got proof input");let i;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((l,p)=>({...l,[p.name]:p.value}),{})};i=await h(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let s=d.responseToProofProps(i);return new d(this.blueprint,s)}};var j=(e=>(e.Circom="circom",e))(j||{}),R=(i=>(i[i.None=0]="None",i[i.Draft=1]="Draft",i[i.InProgress=2]="InProgress",i[i.Done=3]="Done",i[i.Failed=4]="Failed",i))(R||{});var c=class n{props;auth;baseUrl;stars=0;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let i=this.responseToBlueprintProps(r);return new n(i,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!i)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s;try{let p=`${t}/blueprint/by-slug/${e}/${i}`;s=await u(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}let a=this.responseToBlueprintProps(s);return new n(a,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o,r=!0){let i={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await u(`${e}/blueprint`,i,o);}catch(l){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",l),l}if(!s.blueprints)return [];let a=s.blueprints.map(l=>{let p=n.responseToBlueprintProps(l);return new n(p,e,o)});return r&&await Promise.all(a.map(l=>l.getStars())),a}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new y(this)}async verifyProofOnChain(e){try{await g(e);}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await B(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await b(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await u(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await b(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await b(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function T(n,e){let{slugs:t}=await u(`${n}/blueprint/starred`,null,e);return t}var Je=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new c(t,e,n.auth)},async getBlueprint(t){return c.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return c.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return c.listBlueprints(e,t,n?.auth)},async getProof(t){return d.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return T(e,n.auth)}}};
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var viem=require('viem'),chains=require('viem/chains'),relayerUtils=require('@zk-email/relayer-utils');function $(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function g(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=viem.createPublicClient({chain:chains.base,transport:viem.http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:$(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var P=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(P||{});var A="Ov23li0KABFCUsxBEQkn";function U(n,e=A){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function m(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var f="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",_;new Promise(n=>{_=n;});relayerUtils.init().then(()=>{_(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function h(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("POST Error:",r),r}}async function B(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let a=new URLSearchParams;Object.entries(e).forEach(([i,l])=>{l&&a.append(i,String(l));}),a.size>0&&(r+=`?${a.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function b(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("DELETE Error:",r),r}}function O(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var d=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await g(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await u(`${t}/proof/${e}`);}catch(a){throw console.error("Failed calling /proof/:id in getProofById: ",a),a}let r=this.responseToProofProps(o),s=await c.getBlueprintById(o.blueprint_id,t);return new n(s,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var E,w=new Promise(n=>{E=n;});relayerUtils.init().then(()=>{E(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function I(n){try{return await w,await relayerUtils.parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function z(n,e,t=!1){let o=await I(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let i=r.split(e.shaPrecomputeSelector)[1];if(!i)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=i;}let s=o.canonicalizedHeader;return await N(s,r,e),await Promise.all(e.decomposedRegexes.map(i=>v(r,s,i,t)))}async function N(n,e,t){await w;let o=new TextEncoder,r=o.encode(n);if((await relayerUtils.sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=o.encode(e),i=(e.length+63+65)/64*64,l=Math.max(i,t.emailBodyMaxLength);if((await relayerUtils.sha256Pad(a,l)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function v(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let a="maxLength"in t?t.maxLength:t.max_length;await w;let i=relayerUtils.extractSubstr(s,r,!1);if(i[0].length>a)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?relayerUtils.extractSubstr(s,r,o):i}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let s=e.map(i=>({...i,parts:i.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await relayerUtils.generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(a))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var y=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,t,i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let s;try{let i={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((l,p)=>({...l,[p.name]:p.value}),{})};s=await h(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let a=d.responseToProofProps(s);return new d(this.blueprint,a)}};var j=(e=>(e.Circom="circom",e))(j||{}),R=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(R||{});var c=class n{props;auth;baseUrl;stars=0;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await u(`${t}/blueprint/${e}`);}catch(i){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",i),i}let s=this.responseToBlueprintProps(r);return new n(s,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!s)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let a;try{let p=`${t}/blueprint/by-slug/${e}/${s}`;a=await u(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}let i=this.responseToBlueprintProps(a);return new n(i,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version,stars:e.stars}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o){let r={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,sort_by:t?.sortBy==="updatedAt"?"updated_at":t?.sortBy,search:t?.search},s;try{s=await u(`${e}/blueprint`,r,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return s.blueprints?s.blueprints.map(i=>{let l=n.responseToBlueprintProps(i);return new n(l,e,o)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new y(this)}async verifyProofOnChain(e){try{await g(e);}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await B(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await b(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await u(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await b(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await b(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function T(n,e){let{slugs:t}=await u(`${n}/blueprint/starred`,null,e);return t}var Je=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new c(t,e,n.auth)},async getBlueprint(t){return c.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return c.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return c.listBlueprints(e,t,n?.auth)},async getProof(t){return d.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return T(e,n.auth)}}};
|
2
2
|
exports.Blueprint=c;exports.Proof=d;exports.ProofStatus=P;exports.Status=R;exports.ZkFramework=j;exports.default=Je;exports.generateProofInputs=x;exports.getLoginWithGithubUrl=U;exports.parseEmail=I;exports.startJsonFileDownload=O;exports.testBlueprint=z;exports.testDecomposedRegex=v;//# sourceMappingURL=index.js.map
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/chain/index.ts","../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/relayerUtils.ts","../src/prover.ts","../src/types/blueprint.ts","../src/blueprint.ts","../src/user.ts","../src/index.ts"],"names":["getVerifierContractAbi","signalLength","verifyProofOnChain","proof","client","createPublicClient","base","http","proofData","args","output","error","ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","resolve","init","post","url","data","authToken","request","response","body","patch","get","queryParams","fullUrl","searchParams","key","value","del","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","relayerUtilsInit","parseEmail","eml","parseEmailUtils","testBlueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","encoder","headerData","sha256Pad","bodyData","bodyShaLength","maxShaBytes","decomposedRegex","inputDecomposedRegex","inputStr","maxLength","privateResult","extractSubstr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","p","inputs","generateCircuitInputsWithDecomposedRegexesAndExternalInputs","Prover","options","blueprintId","input","requestData","acc","ZkFramework","Status","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","fetchStars","requestOptions","blueprints","bp","status","urls","cloned","stars","getStarredBlueprints","slugs","src_default","sdkOptions"],"mappings":"6KAKA,SAASA,CAAAA,CAAuBC,EAAsB,CACpD,OAAO,CACL,CACE,IAAM,CAAA,UAAA,CACN,KAAM,QACN,CAAA,MAAA,CAAQ,CACN,CACE,IAAM,CAAA,GAAA,CACN,KAAM,YACN,CAAA,YAAA,CAAc,YAChB,CAAA,CACA,CACE,IAAA,CAAM,IACN,IAAM,CAAA,eAAA,CACN,YAAc,CAAA,eAChB,CACA,CAAA,CACE,KAAM,GACN,CAAA,IAAA,CAAM,YACN,CAAA,YAAA,CAAc,YAChB,CAAA,CACA,CACE,IAAM,CAAA,SAAA,CACN,IAAM,CAAA,CAAA,QAAA,EAAWA,CAAY,CAAA,CAAA,CAAA,CAC7B,aAAc,CAAWA,QAAAA,EAAAA,CAAY,CACvC,CAAA,CAAA,CACF,CACA,CAAA,OAAA,CAAS,EACT,CAAA,eAAA,CAAiB,MACnB,CACF,CACF,CAEA,eAAsBC,C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,CAACA,CAAAA,CAAY,IAC9B,CAAA,MAAM,IAAI,KAAA,CAAM,yDAAyD,CAG3E,CAAA,OADkB,IAAIpE,CAAAA,CAAUD,CAAOK,CAAAA,CAAAA,CAASgE,EAAY,IAAI,CAElE,CACA,CAAA,MAAM,YAAajB,CAAAA,CAAAA,CAAkC,CACnD,OAAOnD,CAAAA,CAAU,kBAAmBmD,CAAAA,CAAAA,CAAM/C,CAASgE,CAAAA,CAAAA,EAAY,IAAI,CACrE,CAAA,CACA,MAAM,gBAAA,CAAiBjE,CAAgC,CAAA,CACrD,OAAOH,CAAU,CAAA,gBAAA,CAAiBG,CAAIC,CAAAA,CAAAA,CAASgE,CAAY,EAAA,IAAI,CACjE,CACA,CAAA,MAAM,cAAe3B,CAAAA,CAAAA,CAAuD,CAC1E,OAAOzC,EAAU,cAAeI,CAAAA,CAAAA,CAASqC,CAAS2B,CAAAA,CAAAA,EAAY,IAAI,CACpE,EACA,MAAM,QAAA,CAASjE,CAA4B,CAAA,CACzC,OAAOP,CAAAA,CAAM,aAAaO,CAAIC,CAAAA,CAAO,CACvC,CAAA,CACA,MAAM,oBAAA,EAA0C,CAC9C,GAAI,CAACgE,CAAc,EAAA,CAACA,CAAY,CAAA,IAAA,CAC9B,MAAM,IAAI,KAAA,CAAM,8DAA8D,CAAA,CAEhF,OAAOH,CAAAA,CAAqB7D,EAASgE,CAAY,CAAA,IAAK,CACxD,CACF,CACF","file":"index.js","sourcesContent":["import { createPublicClient, http, Account, PublicClient } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { Proof } from \"../proof\";\nimport { ProofData } from \"../types\";\n\nfunction getVerifierContractAbi(signalLength: number) {\n return [\n {\n type: \"function\",\n name: \"verify\",\n inputs: [\n {\n name: \"a\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"b\",\n type: \"uint256[2][2]\",\n internalType: \"uint256[2][2]\",\n },\n {\n name: \"c\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"signals\",\n type: `uint256[${signalLength}]`,\n internalType: `uint256[${signalLength}]`,\n },\n ],\n outputs: [],\n stateMutability: \"view\",\n },\n ];\n}\n\nexport async function verifyProofOnChain(proof: Proof) {\n if (\n !proof.blueprint.props.verifierContract?.chain ||\n !proof.blueprint.props.verifierContract?.address\n ) {\n throw new Error(\"No verifier contract deployed for the blueprint of this proof\");\n }\n\n if (!proof.props.proofData || !proof.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // Create public client for Base Sepolia\n const client = createPublicClient({\n chain: base,\n transport: http(\"https://sepolia.base.org\"),\n });\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = proof.props.proofData as ProofData;\n\n const args = [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n proof.props.publicOutputs.map((output) => BigInt(output)),\n ] as const;\n\n console.log(\"Call data to verify: \", args);\n console.log(\"contract address: \", proof.blueprint.props.verifierContract.address);\n\n try {\n await client.readContract({\n address: proof.blueprint.props.verifierContract.address as `0x${string}`,\n abi: getVerifierContractAbi(proof.props.publicOutputs.length),\n functionName: \"verify\",\n args,\n });\n } catch (error) {\n console.error(\"Error verifying proof on chain:\", error);\n throw error;\n }\n}\n","import { Dir } from \"fs\";\nimport { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n publicOutputs?: string[];\n externalInputs?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n external_inputs?: string;\n public_outputs?: string[];\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: any;\n external_inputs: any;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type ProofData = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\n\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function del<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"DELETE Error:\", error);\n throw error;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n /**\n * Verifies the proof on chain using the verifier contract defined in the blueprint.\n * Will throw an error if it cannot verify the proof. If the function call succeeds,\n * the proof was validated.\n */\n async verifyOnChain() {\n await verifyProofOnChain(this);\n }\n\n /**\n * Generates call data for the proof that can be used to verify the proof on chain.\n */\n async createCallData() {\n if (!this.props.proofData || !this.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = this.props.proofData as ProofData;\n\n return [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n this.props.publicOutputs.map((output) => BigInt(output)),\n ];\n }\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n publicOutputs: response.public_outputs,\n externalInputs: response.external_inputs,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): {\n proofData: string;\n publicData: string;\n publicOutputs: string[];\n externalInputs: string;\n } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return {\n proofData: this.props.proofData!,\n publicData: this.props.publicData!,\n publicOutputs: this.props.publicOutputs!,\n externalInputs: this.props.externalInputs!,\n };\n }\n}\n","import {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n await relayerUtilsInit;\n const parsedEmail = await parseEmailUtils(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.cleanedBody;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalizedHeader;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n await relayerUtilsInit;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n await relayerUtilsInit;\n const privateResult = extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInputInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n await relayerUtilsInit;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { generateProofInputs } from \"./relayerUtils\";\nimport { GenerateProofInputsParams, ProofRequest, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { ExternalInputInput, ProverOptions } from \"./types/prover\";\nimport { post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string, externalInputs: ExternalInputInput[] = []): Promise<Proof> {\n const proof = await this.generateProofRequest(eml, externalInputs);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(\n eml: string,\n externalInputs: ExternalInputInput[] = []\n ): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n if (this.blueprint.props.externalInputs?.length && !externalInputs.length) {\n throw new Error(\n `The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`\n );\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n externalInputs,\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input: JSON.parse(input),\n external_inputs: externalInputs.reduce(\n (acc, input) => ({\n ...acc,\n [input.name]: input.value,\n }),\n {}\n ),\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { del, get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\nimport { Proof } from \"./proof\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n stars = 0;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth,\n fetchStars = true\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n const blueprints = response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n\n if (fetchStars) {\n await Promise.all(blueprints.map((bp) => bp.getStars()));\n }\n\n return blueprints;\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n await verifyProofOnChain(proof);\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n\n async addStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await post(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${slug}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async removeStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await del(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async getStars(): Promise<number> {\n try {\n const { stars } = await get<{ stars: number }>(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`\n );\n this.stars = stars || 0;\n return stars || 0;\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async cancelCompilation(): Promise<void> {\n if (this.props.status !== Status.InProgress) {\n throw new Error(\"Can only cancel compilation of a blueprint that is in progress\");\n }\n try {\n await del<{ stars: number }>(\n `${this.baseUrl}/blueprint/cancel/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n\n async delete(): Promise<void> {\n // TODO: add is admin check here, currently only done in registry\n // if (this.props.status !== Status.Draft) {\n // throw new Error(\"Can only delete a blueprint that is in draft\");\n // }\n try {\n await del<{ success: boolean }>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Auth } from \"./types\";\nimport { get } from \"./utils\";\n\n/**\n * @returns An array of slugs that the user starred\n */\nexport async function getStarredBlueprints(baseUrl: string, auth: Auth): Promise<string[]> {\n const { slugs } = await get<{ slugs: string[] }>(`${baseUrl}/blueprint/starred`, null, auth);\n return slugs;\n}\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\nimport { getStarredBlueprints } from \"./user\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport * from \"./types/prover\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport { startJsonFileDownload } from \"./utils\";\nexport {\n testDecomposedRegex,\n parseEmail,\n generateProofInputs,\n testBlueprint,\n} from \"./relayerUtils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n async getStarredBlueprints(): Promise<string[]> {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use getStarredBlueprints\");\n }\n return getStarredBlueprints(baseUrl, sdkOptions!.auth!);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/chain/index.ts","../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/relayerUtils.ts","../src/prover.ts","../src/types/blueprint.ts","../src/blueprint.ts","../src/user.ts","../src/index.ts"],"names":["getVerifierContractAbi","signalLength","verifyProofOnChain","proof","client","createPublicClient","base","http","proofData","args","output","error","ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","resolve","init","post","url","data","authToken","request","response","body","patch","get","queryParams","fullUrl","searchParams","key","value","del","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","relayerUtilsInit","parseEmail","eml","parseEmailUtils","testBlueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","encoder","headerData","sha256Pad","bodyData","bodyShaLength","maxShaBytes","decomposedRegex","inputDecomposedRegex","inputStr","maxLength","privateResult","extractSubstr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","p","inputs","generateCircuitInputsWithDecomposedRegexesAndExternalInputs","Prover","options","blueprintId","input","requestData","acc","ZkFramework","Status","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","cloned","stars","getStarredBlueprints","slugs","src_default","sdkOptions"],"mappings":"6KAKA,SAASA,CAAAA,CAAuBC,EAAsB,CACpD,OAAO,CACL,CACE,IAAM,CAAA,UAAA,CACN,KAAM,QACN,CAAA,MAAA,CAAQ,CACN,CACE,IAAM,CAAA,GAAA,CACN,KAAM,YACN,CAAA,YAAA,CAAc,YAChB,CAAA,CACA,CACE,IAAA,C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,CAAA,IAAK,CACxD,CACF,CACF","file":"index.js","sourcesContent":["import { createPublicClient, http, Account, PublicClient } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { Proof } from \"../proof\";\nimport { ProofData } from \"../types\";\n\nfunction getVerifierContractAbi(signalLength: number) {\n return [\n {\n type: \"function\",\n name: \"verify\",\n inputs: [\n {\n name: \"a\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"b\",\n type: \"uint256[2][2]\",\n internalType: \"uint256[2][2]\",\n },\n {\n name: \"c\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"signals\",\n type: `uint256[${signalLength}]`,\n internalType: `uint256[${signalLength}]`,\n },\n ],\n outputs: [],\n stateMutability: \"view\",\n },\n ];\n}\n\nexport async function verifyProofOnChain(proof: Proof) {\n if (\n !proof.blueprint.props.verifierContract?.chain ||\n !proof.blueprint.props.verifierContract?.address\n ) {\n throw new Error(\"No verifier contract deployed for the blueprint of this proof\");\n }\n\n if (!proof.props.proofData || !proof.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // Create public client for Base Sepolia\n const client = createPublicClient({\n chain: base,\n transport: http(\"https://sepolia.base.org\"),\n });\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = proof.props.proofData as ProofData;\n\n const args = [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n proof.props.publicOutputs.map((output) => BigInt(output)),\n ] as const;\n\n console.log(\"Call data to verify: \", args);\n console.log(\"contract address: \", proof.blueprint.props.verifierContract.address);\n\n try {\n await client.readContract({\n address: proof.blueprint.props.verifierContract.address as `0x${string}`,\n abi: getVerifierContractAbi(proof.props.publicOutputs.length),\n functionName: \"verify\",\n args,\n });\n } catch (error) {\n console.error(\"Error verifying proof on chain:\", error);\n throw error;\n }\n}\n","import { Dir } from \"fs\";\nimport { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n publicOutputs?: string[];\n externalInputs?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n external_inputs?: string;\n public_outputs?: string[];\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: any;\n external_inputs: any;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type ProofData = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\n\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function del<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"DELETE Error:\", error);\n throw error;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n /**\n * Verifies the proof on chain using the verifier contract defined in the blueprint.\n * Will throw an error if it cannot verify the proof. If the function call succeeds,\n * the proof was validated.\n */\n async verifyOnChain() {\n await verifyProofOnChain(this);\n }\n\n /**\n * Generates call data for the proof that can be used to verify the proof on chain.\n */\n async createCallData() {\n if (!this.props.proofData || !this.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = this.props.proofData as ProofData;\n\n return [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n this.props.publicOutputs.map((output) => BigInt(output)),\n ];\n }\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n publicOutputs: response.public_outputs,\n externalInputs: response.external_inputs,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): {\n proofData: string;\n publicData: string;\n publicOutputs: string[];\n externalInputs: string;\n } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return {\n proofData: this.props.proofData!,\n publicData: this.props.publicData!,\n publicOutputs: this.props.publicOutputs!,\n externalInputs: this.props.externalInputs!,\n };\n }\n}\n","import {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n await relayerUtilsInit;\n const parsedEmail = await parseEmailUtils(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.cleanedBody;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalizedHeader;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n await relayerUtilsInit;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n await relayerUtilsInit;\n const privateResult = extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInputInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n await relayerUtilsInit;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { generateProofInputs } from \"./relayerUtils\";\nimport { GenerateProofInputsParams, ProofRequest, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { ExternalInputInput, ProverOptions } from \"./types/prover\";\nimport { post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string, externalInputs: ExternalInputInput[] = []): Promise<Proof> {\n const proof = await this.generateProofRequest(eml, externalInputs);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(\n eml: string,\n externalInputs: ExternalInputInput[] = []\n ): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n if (this.blueprint.props.externalInputs?.length && !externalInputs.length) {\n throw new Error(\n `The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`\n );\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n externalInputs,\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input: JSON.parse(input),\n external_inputs: externalInputs.reduce(\n (acc, input) => ({\n ...acc,\n [input.name]: input.value,\n }),\n {}\n ),\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n stars?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n stars: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n sortBy?: \"updatedAt\" | \"stars\";\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n sort_by?: \"updated_at\" | \"stars\";\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { del, get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\nimport { Proof } from \"./proof\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n stars = 0;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n stars: response.stars,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n sort_by: options?.sortBy === \"updatedAt\" ? \"updated_at\" : options?.sortBy,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n const blueprints = response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n\n return blueprints;\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n await verifyProofOnChain(proof);\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n\n async addStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await post(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${slug}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async removeStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await del(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async getStars(): Promise<number> {\n try {\n const { stars } = await get<{ stars: number }>(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`\n );\n this.stars = stars || 0;\n return stars || 0;\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async cancelCompilation(): Promise<void> {\n if (this.props.status !== Status.InProgress) {\n throw new Error(\"Can only cancel compilation of a blueprint that is in progress\");\n }\n try {\n await del<{ stars: number }>(\n `${this.baseUrl}/blueprint/cancel/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n\n async delete(): Promise<void> {\n // TODO: add is admin check here, currently only done in registry\n // if (this.props.status !== Status.Draft) {\n // throw new Error(\"Can only delete a blueprint that is in draft\");\n // }\n try {\n await del<{ success: boolean }>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Auth } from \"./types\";\nimport { get } from \"./utils\";\n\n/**\n * @returns An array of slugs that the user starred\n */\nexport async function getStarredBlueprints(baseUrl: string, auth: Auth): Promise<string[]> {\n const { slugs } = await get<{ slugs: string[] }>(`${baseUrl}/blueprint/starred`, null, auth);\n return slugs;\n}\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\nimport { getStarredBlueprints } from \"./user\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport * from \"./types/prover\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport { startJsonFileDownload } from \"./utils\";\nexport {\n testDecomposedRegex,\n parseEmail,\n generateProofInputs,\n testBlueprint,\n} from \"./relayerUtils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n async getStarredBlueprints(): Promise<string[]> {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use getStarredBlueprints\");\n }\n return getStarredBlueprints(baseUrl, sdkOptions!.auth!);\n },\n };\n};\n"]}
|
package/dist/index.mjs
CHANGED
@@ -1,3 +1,3 @@
|
|
1
|
-
import {createPublicClient,http}from'viem';import {base}from'viem/chains';import {init,parseEmail,sha256Pad,extractSubstr,generateCircuitInputsWithDecomposedRegexesAndExternalInputs}from'@zk-email/relayer-utils';function $(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function g(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=createPublicClient({chain:base,transport:http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:$(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var P=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(P||{});var A="Ov23li0KABFCUsxBEQkn";function U(n,e=A){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function m(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var f="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",_;new Promise(n=>{_=n;});init().then(()=>{_(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function h(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("POST Error:",r),r}}async function B(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let s=new URLSearchParams;Object.entries(e).forEach(([a,l])=>{l&&s.append(a,String(l));}),s.size>0&&(r+=`?${s.toString()}`);}let i=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);return await i.json()}catch(r){throw console.error("GET Error:",r),r}}async function b(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let i=await fetch(n,r),s=await i.json();if(!i.ok)throw new Error(`HTTP error! status: ${i.status}, message: ${s}`);return s}catch(r){throw console.error("DELETE Error:",r),r}}function O(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var d=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await g(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await u(`${t}/proof/${e}`);}catch(s){throw console.error("Failed calling /proof/:id in getProofById: ",s),s}let r=this.responseToProofProps(o),i=await c.getBlueprintById(o.blueprint_id,t);return new n(i,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var E,w=new Promise(n=>{E=n;});init().then(()=>{E(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function I(n){try{return await w,await parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function z(n,e,t=!1){let o=await I(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let a=r.split(e.shaPrecomputeSelector)[1];if(!a)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=a;}let i=o.canonicalizedHeader;return await N(i,r,e),await Promise.all(e.decomposedRegexes.map(a=>v(r,i,a,t)))}async function N(n,e,t){await w;let o=new TextEncoder,r=o.encode(n);if((await sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let s=o.encode(e),a=(e.length+63+65)/64*64,l=Math.max(a,t.emailBodyMaxLength);if((await sha256Pad(s,l)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function v(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.regex_def}))},i;if(t.location==="body")i=n;else if(t.location==="header")i=e;else throw Error(`Unsupported location ${t.location}`);let s="maxLength"in t?t.maxLength:t.max_length;await w;let a=extractSubstr(i,r,!1);if(a[0].length>s)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?extractSubstr(i,r,o):a}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let i=e.map(a=>({...a,parts:a.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),s=await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,i,t,r);return JSON.stringify(Object.fromEntries(s))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var y=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let a={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,t,a);}catch(a){throw console.error("Failed to generate inputs for proof"),a}console.log("got proof input");let i;try{let a={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((l,p)=>({...l,[p.name]:p.value}),{})};i=await h(`${this.blueprint.baseUrl}/proof`,a);}catch(a){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",a),a}let s=d.responseToProofProps(i);return new d(this.blueprint,s)}};var j=(e=>(e.Circom="circom",e))(j||{}),R=(i=>(i[i.None=0]="None",i[i.Draft=1]="Draft",i[i.InProgress=2]="InProgress",i[i.Done=3]="Done",i[i.Failed=4]="Failed",i))(R||{});var c=class n{props;auth;baseUrl;stars=0;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await u(`${t}/blueprint/${e}`);}catch(a){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",a),a}let i=this.responseToBlueprintProps(r);return new n(i,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let i=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!i)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s;try{let p=`${t}/blueprint/by-slug/${e}/${i}`;s=await u(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}let a=this.responseToBlueprintProps(s);return new n(a,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o,r=!0){let i={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,search:t?.search},s;try{s=await u(`${e}/blueprint`,i,o);}catch(l){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",l),l}if(!s.blueprints)return [];let a=s.blueprints.map(l=>{let p=n.responseToBlueprintProps(l);return new n(p,e,o)});return r&&await Promise.all(a.map(l=>l.getStars())),a}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new y(this)}async verifyProofOnChain(e){try{await g(e);}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await B(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await b(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await u(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await b(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await b(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function T(n,e){let{slugs:t}=await u(`${n}/blueprint/starred`,null,e);return t}var Je=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new c(t,e,n.auth)},async getBlueprint(t){return c.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return c.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return c.listBlueprints(e,t,n?.auth)},async getProof(t){return d.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return T(e,n.auth)}}};
|
1
|
+
import {createPublicClient,http}from'viem';import {base}from'viem/chains';import {init,parseEmail,sha256Pad,extractSubstr,generateCircuitInputsWithDecomposedRegexesAndExternalInputs}from'@zk-email/relayer-utils';function $(n){return [{type:"function",name:"verify",inputs:[{name:"a",type:"uint256[2]",internalType:"uint256[2]"},{name:"b",type:"uint256[2][2]",internalType:"uint256[2][2]"},{name:"c",type:"uint256[2]",internalType:"uint256[2]"},{name:"signals",type:`uint256[${n}]`,internalType:`uint256[${n}]`}],outputs:[],stateMutability:"view"}]}async function g(n){if(!n.blueprint.props.verifierContract?.chain||!n.blueprint.props.verifierContract?.address)throw new Error("No verifier contract deployed for the blueprint of this proof");if(!n.props.proofData||!n.props.publicOutputs)throw new Error("No proof data generated yet");let e=createPublicClient({chain:base,transport:http("https://sepolia.base.org")}),t=n.props.proofData,o=[[BigInt(t.pi_a[0]),BigInt(t.pi_a[1])],[[BigInt(t.pi_b[0][1]),BigInt(t.pi_b[0][0])],[BigInt(t.pi_b[1][1]),BigInt(t.pi_b[1][0])]],[BigInt(t.pi_c[0]),BigInt(t.pi_c[1])],n.props.publicOutputs.map(r=>BigInt(r))];console.log("Call data to verify: ",o),console.log("contract address: ",n.blueprint.props.verifierContract.address);try{await e.readContract({address:n.blueprint.props.verifierContract.address,abi:$(n.props.publicOutputs.length),functionName:"verify",args:o});}catch(r){throw console.error("Error verifying proof on chain:",r),r}}var P=(r=>(r[r.None=0]="None",r[r.InProgress=1]="InProgress",r[r.Done=2]="Done",r[r.Failed=3]="Failed",r))(P||{});var A="Ov23li0KABFCUsxBEQkn";function U(n,e=A){let t=encodeURIComponent(n);return `https://github.com/login/oauth/authorize?client_id=${e}&scope=user:email&state=${t}`}async function m(n){try{let e=await n.getToken();if(e||(await n.onTokenExpired(),e=await n.getToken()),!e)throw new Error("Failed to get new token");return `Bearer ${e}`}catch(e){throw console.error("Failed to get token from auth"),e}}var f="pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F",_;new Promise(n=>{_=n;});init().then(()=>{_(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function h(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"POST",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("POST Error:",r),r}}async function B(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r={method:"PATCH",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("PATCH Error:",r),r}}async function u(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.warn("Could not get token from auth",r);}try{let r=n;if(e){let a=new URLSearchParams;Object.entries(e).forEach(([i,l])=>{l&&a.append(i,String(l));}),a.size>0&&(r+=`?${a.toString()}`);}let s=await fetch(r,{method:"GET",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}});if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return await s.json()}catch(r){throw console.error("GET Error:",r),r}}async function b(n,e,t){let o=null;if(t)try{o=await m(t);}catch(r){console.error("Could not get token from auth",r);}try{let r={method:"DELETE",headers:{"Content-Type":"application/json","x-api-key":f,...o?{Authorization:o}:{}}};e&&(r.body=JSON.stringify(e));let s=await fetch(n,r),a=await s.json();if(!s.ok)throw new Error(`HTTP error! status: ${s.status}, message: ${a}`);return a}catch(r){throw console.error("DELETE Error:",r),r}}function O(n,e="data"){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let t=new Blob([n],{type:"application/json"}),o=URL.createObjectURL(t),r=document.createElement("a");r.href=o,r.download=`${e}.json`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(o);}var d=class n{blueprint;props;lastCheckedStatus=null;constructor(e,t){if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");if(this.blueprint=e,!t?.id)throw new Error("A proof must have an id");this.props={status:1,...t};}getId(){return this.props.id}async getProofDataDownloadLink(){if(this.props.status!==2)throw new Error("The proving is not done yet.");let e;try{e=await u(`${this.blueprint.baseUrl}/proof/files/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /proof/files/:id in getProofDataDownloadLink: ",t),t}return e.url}async startFilesDownload(){if(!window&&!document)throw Error("startFilesDownload can only be used in a browser");let e;try{e=await this.getProofDataDownloadLink();}catch(o){throw console.error("Failed to start download of ZKeys: ",o),o}let t=document.createElement("a");t.href=e,t.download="proof_files.zip",document.body.appendChild(t),t.click(),document.body.removeChild(t);}async checkStatus(){if(this.props.status===2)return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}let e;try{e=await u(`${this.blueprint.baseUrl}/proof/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}if([1,2].includes(this.props.status)&&this.props.status!==e.status){let t=await n.getProofById(this.props.id,this.blueprint.baseUrl);return this.props=t.props,this.props.status}return this.props.status=e.status,e.status}async waitForCompletion(){for(;await this.checkStatus()===1;);return this.props.status}async verifyOnChain(){await g(this);}async createCallData(){if(!this.props.proofData||!this.props.publicOutputs)throw new Error("No proof data generated yet");let e=this.props.proofData;return [[BigInt(e.pi_a[0]),BigInt(e.pi_a[1])],[[BigInt(e.pi_b[0][1]),BigInt(e.pi_b[0][0])],[BigInt(e.pi_b[1][1]),BigInt(e.pi_b[1][0])]],[BigInt(e.pi_c[0]),BigInt(e.pi_c[1])],this.props.publicOutputs.map(t=>BigInt(t))]}static async getProofById(e,t){let o;try{o=await u(`${t}/proof/${e}`);}catch(a){throw console.error("Failed calling /proof/:id in getProofById: ",a),a}let r=this.responseToProofProps(o),s=await c.getBlueprintById(o.blueprint_id,t);return new n(s,r)}static responseToProofProps(e){return {id:e.id,blueprintId:e.blueprint_id,status:e.status,input:e.input,proofData:e.proof,publicData:e.public,publicOutputs:e.public_outputs,externalInputs:e.external_inputs,startedAt:new Date(e.started_at.seconds*1e3),provedAt:e.proved_at?new Date(e.proved_at.seconds*1e3):void 0}}getProofData(){if(this.props.status!==2)throw new Error("Cannot get proof data, proof is not Done");return {proofData:this.props.proofData,publicData:this.props.publicData,publicOutputs:this.props.publicOutputs,externalInputs:this.props.externalInputs}}};var E,w=new Promise(n=>{E=n;});init().then(()=>{E(null);}).catch(n=>{console.log("Failed to initialize wasm for relayer-utils: ",n);});async function I(n){try{return await w,await parseEmail(n)}catch(e){throw console.error("Failed to parse email: ",e),e}}async function z(n,e,t=!1){let o=await I(n);if(e.emailBodyMaxLength===void 0&&!e.ignoreBodyHashCheck||e.emailHeaderMaxLength===void 0)throw new Error("emailBodyMaxLength and emailHeaderMaxLength must be provided");let r=o.cleanedBody;if(e.shaPrecomputeSelector){let i=r.split(e.shaPrecomputeSelector)[1];if(!i)throw new Error(`Precompute selector was not found in email, selector: ${e.shaPrecomputeSelector}`);r=i;}let s=o.canonicalizedHeader;return await N(s,r,e),await Promise.all(e.decomposedRegexes.map(i=>v(r,s,i,t)))}async function N(n,e,t){await w;let o=new TextEncoder,r=o.encode(n);if((await sha256Pad(r,t.emailHeaderMaxLength)).get("messageLength")>t.emailHeaderMaxLength)throw new Error(`emailHeaderMaxLength of ${t.emailHeaderMaxLength} was exceeded`);if(!t.ignoreBodyHashCheck){let a=o.encode(e),i=(e.length+63+65)/64*64,l=Math.max(i,t.emailBodyMaxLength);if((await sha256Pad(a,l)).get("messageLength")>t.emailBodyMaxLength)throw new Error(`emailBodyMaxLength of ${t.emailBodyMaxLength} was exceeded`)}}async function v(n,e,t,o=!1){let r={parts:t.parts.map(p=>({is_public:"isPublic"in p?p.isPublic:p.is_public,regex_def:"regexDef"in p?p.regexDef:p.regex_def}))},s;if(t.location==="body")s=n;else if(t.location==="header")s=e;else throw Error(`Unsupported location ${t.location}`);let a="maxLength"in t?t.maxLength:t.max_length;await w;let i=extractSubstr(s,r,!1);if(i[0].length>a)throw new Error(`Max length of extracted result was exceeded for decomposed regex ${t.name}`);return o?extractSubstr(s,r,o):i}async function x(n,e,t,o){try{let r={maxHeaderLength:o.emailHeaderMaxLength,maxBodyLength:o.emailBodyMaxLength,ignoreBodyHashCheck:o.ignoreBodyHashCheck,removeSoftLinesBreaks:o.removeSoftLinebreaks,shaPrecomputeSelector:o.shaPrecomputeSelector};await w;let s=e.map(i=>({...i,parts:i.parts.map(l=>({is_public:l.isPublic||!!l.is_public,regex_def:l.regexDef||!!l.regex_def}))})),a=await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(n,s,t,r);return JSON.stringify(Object.fromEntries(a))}catch(r){throw console.error("Failed to generate inputs for proof"),r}}var y=class{options;blueprint;constructor(e,t){if(t?.isLocal===!0)throw new Error("Local proving is not supported yet");if(!(e instanceof c))throw new Error("Invalid blueprint: must be an instance of Blueprint class");this.blueprint=e,this.options={isLocal:!1,...t||{}};}async generateProof(e,t=[]){let o=await this.generateProofRequest(e,t);for(;![2,3].includes(await o.checkStatus()););return o}async generateProofRequest(e,t=[]){let o=this.blueprint.getId();if(!o)throw new Error("Blueprint of Proover must be initialized in order to create a Proof");if(this.blueprint.props.externalInputs?.length&&!t.length)throw new Error(`The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`);let r;try{let i={emailHeaderMaxLength:this.blueprint.props.emailHeaderMaxLength||256,emailBodyMaxLength:this.blueprint.props.emailBodyMaxLength||2560,ignoreBodyHashCheck:this.blueprint.props.ignoreBodyHashCheck||!1,removeSoftLinebreaks:this.blueprint.props.removeSoftLinebreaks||!0,shaPrecomputeSelector:this.blueprint.props.shaPrecomputeSelector};console.log("generating proof inputs"),r=await x(e,this.blueprint.props.decomposedRegexes,t,i);}catch(i){throw console.error("Failed to generate inputs for proof"),i}console.log("got proof input");let s;try{let i={blueprint_id:o,input:JSON.parse(r),external_inputs:t.reduce((l,p)=>({...l,[p.name]:p.value}),{})};s=await h(`${this.blueprint.baseUrl}/proof`,i);}catch(i){throw console.error("Failed calling POST on /proof/ in generateProofRequest: ",i),i}let a=d.responseToProofProps(s);return new d(this.blueprint,a)}};var j=(e=>(e.Circom="circom",e))(j||{}),R=(s=>(s[s.None=0]="None",s[s.Draft=1]="Draft",s[s.InProgress=2]="InProgress",s[s.Done=3]="Done",s[s.Failed=4]="Failed",s))(R||{});var c=class n{props;auth;baseUrl;stars=0;lastCheckedStatus=null;constructor(e,t,o){this.props={ignoreBodyHashCheck:!1,enableHeaderMasking:!1,enableBodyMasking:!1,isPublic:!0,status:1,...e},this.baseUrl=t,this.auth=o;}addAuth(e){this.auth=e;}static async getBlueprintById(e,t,o){let r;try{r=await u(`${t}/blueprint/${e}`);}catch(i){throw console.error("Failed calling /blueprint/:id in getBlueprintById: ",i),i}let s=this.responseToBlueprintProps(r);return new n(s,t,o)}static async getBlueprintBySlug(e,t,o){let r=e.split("@");if(!r||!(r.length>1))throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let s=r.pop().replace("v","");if(e=encodeURIComponent(r.join("")),!s)throw new Error("You must provide the blueprint version, e.g. 'user/slug@v1");let a;try{let p=`${t}/blueprint/by-slug/${e}/${s}`;a=await u(p);}catch(p){throw console.error("Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: ",p),p}let i=this.responseToBlueprintProps(a);return new n(i,t,o)}static responseToBlueprintProps(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,emailQuery:e.email_query,circuitName:e.circuit_name,ignoreBodyHashCheck:e.ignore_body_hash_check,shaPrecomputeSelector:e.sha_precompute_selector,emailBodyMaxLength:e.email_body_max_length,emailHeaderMaxLength:e.email_header_max_length,removeSoftLinebreaks:e.remove_soft_linebreaks,githubUsername:e.github_username,senderDomain:e.sender_domain,enableHeaderMasking:e.enable_header_masking,enableBodyMasking:e.enable_body_masking,zkFramework:e.zk_framework,isPublic:e.is_public,createdAt:new Date(e.created_at.seconds*1e3),updatedAt:new Date(e.updated_at.seconds*1e3),externalInputs:e.external_inputs?.map(o=>({name:o.name,maxLength:o.max_length})),decomposedRegexes:e.decomposed_regexes?.map(o=>({parts:o.parts.map(r=>({isPublic:r.is_public,regexDef:r.regex_def})),name:o.name,maxLength:o.max_length,location:o.location})),status:e.status,verifierContract:{address:e.verifier_contract_address,chain:e.verifier_contract_chain},version:e.version,stars:e.stars}}static blueprintPropsToRequest(e){return {id:e.id,title:e.title,description:e.description,slug:e.slug,tags:e.tags,email_query:e.emailQuery,circuit_name:e.circuitName,ignore_body_hash_check:e.ignoreBodyHashCheck,sha_precompute_selector:e.shaPrecomputeSelector,email_body_max_length:e.emailBodyMaxLength,email_header_max_length:e.emailHeaderMaxLength,remove_soft_linebreaks:e.removeSoftLinebreaks,github_username:e.githubUsername,sender_domain:e.senderDomain,enable_header_masking:e.enableHeaderMasking,enable_body_masking:e.enableBodyMasking,zk_framework:e.zkFramework,is_public:e.isPublic,external_inputs:e.externalInputs?.map(o=>({name:o.name,max_length:o.maxLength})),decomposed_regexes:e.decomposedRegexes?.map(o=>({parts:o.parts.map(r=>({is_public:r.isPublic||r.is_public,regex_def:r.regexDef||r.regex_def})),name:o.name,max_length:o.maxLength,location:o.location})),verifier_contract_address:e.verifierContract?.address,verifier_contract_chain:e.verifierContract?.chain}}async submitDraft(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(this.props.id)throw new Error("Blueprint was already saved");let e=n.blueprintPropsToRequest(this.props),t;try{t=await h(`${this.baseUrl}/blueprint`,e,this.auth);}catch(o){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",o),o}this.props=n.responseToBlueprintProps(t);}async submitNewVersionDraft(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");let t=n.blueprintPropsToRequest(e),o;try{o=await h(`${this.baseUrl}/blueprint`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitNewVersionDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async submitNewVersion(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");await this.submitNewVersionDraft(e);try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}static async listBlueprints(e,t,o){let r={skip:t?.skip,limit:t?.limit,sort:t?.sort,status:t?.status,is_public:t?.isPublic,sort_by:t?.sortBy==="updatedAt"?"updated_at":t?.sortBy,search:t?.search},s;try{s=await u(`${e}/blueprint`,r,o);}catch(i){throw console.error("Failed calling GET on /blueprint/ in listBlueprints: ",i),i}return s.blueprints?s.blueprints.map(i=>{let l=n.responseToBlueprintProps(i);return new n(l,e,o)}):[]}async submit(){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.props.id)try{await this.submitDraft();}catch(t){throw console.error("Failed to create blueprint: ",t),t}let e=await this._checkStatus();if(3===e)throw new Error("The circuits are already compiled.");if(2===e)throw new Error("The circuits already being compiled, please wait.");try{await h(`${this.baseUrl}/blueprint/compile/${this.props.id}`,null,this.auth);}catch(t){throw console.error("Failed calling POST on /blueprint/compile in submit: ",t),t}}async _checkStatus(){let e;try{e=await u(`${this.baseUrl}/blueprint/status/${this.props.id}`);}catch(t){throw console.error("Failed calling GET /blueprint/status in getStatus(): ",t),t}return this.props.status=e.status,e.status}async checkStatus(){if(!this.props.id)return this.props.status;if([4,3].includes(this.props.status))return this.props.status;if(!this.lastCheckedStatus)this.lastCheckedStatus=new Date;else {let o=new Date().getTime()-this.lastCheckedStatus.getTime();o<500&&await new Promise(r=>setTimeout(r,500-o));}return await this._checkStatus()}getId(){return this.props.id||null}async getZKeyDownloadLink(){if(this.props.status!==3)throw new Error("The circuits are not compiled yet, nothing to download.");let e;try{e=await u(`${this.baseUrl}/blueprint/zkey/${this.props.id}`);}catch(t){throw console.error("Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: ",t),t}return e.urls}async startZKeyDownload(){if(!window&&!document)throw Error("startZKeyDownload can only be used in a browser");let e;try{e=await this.getZKeyDownloadLink();}catch(t){throw console.error("Failed to start download of ZKeys: ",t),t}for(let[t,o]of Object.entries(e)){let r=document.createElement("a");r.href=o,r.download=t,document.body.appendChild(r),r.click(),document.body.removeChild(r);}}createProver(){return new y(this)}async verifyProofOnChain(e){try{await g(e);}catch(t){return console.error("Failed to verify proof on chain: ",t),!1}return !0}getClonedProps(){let e=JSON.parse(JSON.stringify(this.props));return e.createdAt&&(e.createdAt=new Date(e.createdAt)),e.updatedAt&&(e.updatedAt=new Date(e.updatedAt)),e}canUpdate(){return !!(this.props.id&&![3,2].includes(this.props.status))}async update(e){if(!this.auth)throw new Error("auth is required, add it with Blueprint.addAuth(auth)");if(!this.canUpdate())throw new Error("Blueprint already compied, cannot update");let t=n.blueprintPropsToRequest(e),o;try{o=await B(`${this.baseUrl}/blueprint/${this.props.id}`,t,this.auth);}catch(r){throw console.error("Failed calling POST on /blueprint/ in submitDraft: ",r),r}this.props=n.responseToBlueprintProps(o);}async listAllVersions(){if(!this.props.id)throw new Error("Blueprint was not saved yet");let e;try{e=await u(`${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug)}`);}catch(t){throw console.error("Failed calling GET on /blueprint/versions/:slug in listAllVersions: ",t),t}return e.blueprints.map(t=>{let o=n.responseToBlueprintProps(t);return new n(o,this.baseUrl,this.auth)})}async addStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await h(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling POST on /blueprint/${slug}/stars in addStar: ",e),e}}async removeStar(){if(!this.auth)throw new Error("Auth is required. Please login to star a blueprint.");try{return await b(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`,null,this.auth),await this.getStars()}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id}/stars in addStar: ",e),e}}async getStars(){try{let{stars:e}=await u(`${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug)}/stars`);return this.stars=e||0,e||0}catch(e){throw console.error("Failed calling POST on /blueprint/${id}/stars in addStar: ",e),e}}async cancelCompilation(){if(this.props.status!==2)throw new Error("Can only cancel compilation of a blueprint that is in progress");try{await b(`${this.baseUrl}/blueprint/cancel/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: ",e),e}}async delete(){try{await b(`${this.baseUrl}/blueprint/${this.props.id}`,null,this.auth);}catch(e){throw console.error("Failed calling DELETE on /blueprint/${id} in cancelCompilation: ",e),e}}};async function T(n,e){let{slugs:t}=await u(`${n}/blueprint/starred`,null,e);return t}var Je=n=>{let e=n?.baseUrl||"https://conductor.zk.email";return {createBlueprint(t){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use createBlueprint");return new c(t,e,n.auth)},async getBlueprint(t){return c.getBlueprintBySlug(t,e,n?.auth)},async getBlueprintById(t){return c.getBlueprintById(t,e,n?.auth)},async listBlueprints(t){return c.listBlueprints(e,t,n?.auth)},async getProof(t){return d.getProofById(t,e)},async getStarredBlueprints(){if(!n&&!n.auth)throw new Error("You need to specify options.auth to use getStarredBlueprints");return T(e,n.auth)}}};
|
2
2
|
export{c as Blueprint,d as Proof,P as ProofStatus,R as Status,j as ZkFramework,Je as default,x as generateProofInputs,U as getLoginWithGithubUrl,I as parseEmail,O as startJsonFileDownload,z as testBlueprint,v as testDecomposedRegex};//# sourceMappingURL=index.mjs.map
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
@@ -1 +1 @@
|
|
1
|
-
{"version":3,"sources":["../src/chain/index.ts","../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/relayerUtils.ts","../src/prover.ts","../src/types/blueprint.ts","../src/blueprint.ts","../src/user.ts","../src/index.ts"],"names":["getVerifierContractAbi","signalLength","verifyProofOnChain","proof","client","createPublicClient","base","http","proofData","args","output","error","ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","resolve","init","post","url","data","authToken","request","response","body","patch","get","queryParams","fullUrl","searchParams","key","value","del","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","relayerUtilsInit","parseEmail","eml","parseEmailUtils","testBlueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","encoder","headerData","sha256Pad","bodyData","bodyShaLength","maxShaBytes","decomposedRegex","inputDecomposedRegex","inputStr","maxLength","privateResult","extractSubstr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","p","inputs","generateCircuitInputsWithDecomposedRegexesAndExternalInputs","Prover","options","blueprintId","input","requestData","acc","ZkFramework","Status","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","fetchStars","requestOptions","blueprints","bp","status","urls","cloned","stars","getStarredBlueprints","slugs","src_default","sdkOptions"],"mappings":"oNAKA,SAASA,CAAAA,CAAuBC,EAAsB,CACpD,OAAO,CACL,CACE,IAAM,CAAA,UAAA,CACN,KAAM,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CAC9B,MAAM,IAAI,KAAA,CAAM,8DAA8D,CAAA,CAEhF,OAAOH,CAAAA,CAAqB7D,EAASgE,CAAY,CAAA,IAAK,CACxD,CACF,CACF","file":"index.mjs","sourcesContent":["import { createPublicClient, http, Account, PublicClient } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { Proof } from \"../proof\";\nimport { ProofData } from \"../types\";\n\nfunction getVerifierContractAbi(signalLength: number) {\n return [\n {\n type: \"function\",\n name: \"verify\",\n inputs: [\n {\n name: \"a\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"b\",\n type: \"uint256[2][2]\",\n internalType: \"uint256[2][2]\",\n },\n {\n name: \"c\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"signals\",\n type: `uint256[${signalLength}]`,\n internalType: `uint256[${signalLength}]`,\n },\n ],\n outputs: [],\n stateMutability: \"view\",\n },\n ];\n}\n\nexport async function verifyProofOnChain(proof: Proof) {\n if (\n !proof.blueprint.props.verifierContract?.chain ||\n !proof.blueprint.props.verifierContract?.address\n ) {\n throw new Error(\"No verifier contract deployed for the blueprint of this proof\");\n }\n\n if (!proof.props.proofData || !proof.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // Create public client for Base Sepolia\n const client = createPublicClient({\n chain: base,\n transport: http(\"https://sepolia.base.org\"),\n });\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = proof.props.proofData as ProofData;\n\n const args = [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n proof.props.publicOutputs.map((output) => BigInt(output)),\n ] as const;\n\n console.log(\"Call data to verify: \", args);\n console.log(\"contract address: \", proof.blueprint.props.verifierContract.address);\n\n try {\n await client.readContract({\n address: proof.blueprint.props.verifierContract.address as `0x${string}`,\n abi: getVerifierContractAbi(proof.props.publicOutputs.length),\n functionName: \"verify\",\n args,\n });\n } catch (error) {\n console.error(\"Error verifying proof on chain:\", error);\n throw error;\n }\n}\n","import { Dir } from \"fs\";\nimport { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n publicOutputs?: string[];\n externalInputs?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n external_inputs?: string;\n public_outputs?: string[];\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: any;\n external_inputs: any;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type ProofData = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\n\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function del<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"DELETE Error:\", error);\n throw error;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n /**\n * Verifies the proof on chain using the verifier contract defined in the blueprint.\n * Will throw an error if it cannot verify the proof. If the function call succeeds,\n * the proof was validated.\n */\n async verifyOnChain() {\n await verifyProofOnChain(this);\n }\n\n /**\n * Generates call data for the proof that can be used to verify the proof on chain.\n */\n async createCallData() {\n if (!this.props.proofData || !this.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = this.props.proofData as ProofData;\n\n return [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n this.props.publicOutputs.map((output) => BigInt(output)),\n ];\n }\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n publicOutputs: response.public_outputs,\n externalInputs: response.external_inputs,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): {\n proofData: string;\n publicData: string;\n publicOutputs: string[];\n externalInputs: string;\n } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return {\n proofData: this.props.proofData!,\n publicData: this.props.publicData!,\n publicOutputs: this.props.publicOutputs!,\n externalInputs: this.props.externalInputs!,\n };\n }\n}\n","import {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n await relayerUtilsInit;\n const parsedEmail = await parseEmailUtils(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.cleanedBody;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalizedHeader;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n await relayerUtilsInit;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n await relayerUtilsInit;\n const privateResult = extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInputInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n await relayerUtilsInit;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { generateProofInputs } from \"./relayerUtils\";\nimport { GenerateProofInputsParams, ProofRequest, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { ExternalInputInput, ProverOptions } from \"./types/prover\";\nimport { post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string, externalInputs: ExternalInputInput[] = []): Promise<Proof> {\n const proof = await this.generateProofRequest(eml, externalInputs);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(\n eml: string,\n externalInputs: ExternalInputInput[] = []\n ): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n if (this.blueprint.props.externalInputs?.length && !externalInputs.length) {\n throw new Error(\n `The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`\n );\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n externalInputs,\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input: JSON.parse(input),\n external_inputs: externalInputs.reduce(\n (acc, input) => ({\n ...acc,\n [input.name]: input.value,\n }),\n {}\n ),\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { del, get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\nimport { Proof } from \"./proof\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n stars = 0;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth,\n fetchStars = true\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n const blueprints = response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n\n if (fetchStars) {\n await Promise.all(blueprints.map((bp) => bp.getStars()));\n }\n\n return blueprints;\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n await verifyProofOnChain(proof);\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n\n async addStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await post(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${slug}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async removeStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await del(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async getStars(): Promise<number> {\n try {\n const { stars } = await get<{ stars: number }>(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`\n );\n this.stars = stars || 0;\n return stars || 0;\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async cancelCompilation(): Promise<void> {\n if (this.props.status !== Status.InProgress) {\n throw new Error(\"Can only cancel compilation of a blueprint that is in progress\");\n }\n try {\n await del<{ stars: number }>(\n `${this.baseUrl}/blueprint/cancel/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n\n async delete(): Promise<void> {\n // TODO: add is admin check here, currently only done in registry\n // if (this.props.status !== Status.Draft) {\n // throw new Error(\"Can only delete a blueprint that is in draft\");\n // }\n try {\n await del<{ success: boolean }>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Auth } from \"./types\";\nimport { get } from \"./utils\";\n\n/**\n * @returns An array of slugs that the user starred\n */\nexport async function getStarredBlueprints(baseUrl: string, auth: Auth): Promise<string[]> {\n const { slugs } = await get<{ slugs: string[] }>(`${baseUrl}/blueprint/starred`, null, auth);\n return slugs;\n}\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\nimport { getStarredBlueprints } from \"./user\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport * from \"./types/prover\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport { startJsonFileDownload } from \"./utils\";\nexport {\n testDecomposedRegex,\n parseEmail,\n generateProofInputs,\n testBlueprint,\n} from \"./relayerUtils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n async getStarredBlueprints(): Promise<string[]> {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use getStarredBlueprints\");\n }\n return getStarredBlueprints(baseUrl, sdkOptions!.auth!);\n },\n };\n};\n"]}
|
1
|
+
{"version":3,"sources":["../src/chain/index.ts","../src/types/proof.ts","../src/auth.ts","../src/utils.ts","../src/proof.ts","../src/relayerUtils.ts","../src/prover.ts","../src/types/blueprint.ts","../src/blueprint.ts","../src/user.ts","../src/index.ts"],"names":["getVerifierContractAbi","signalLength","verifyProofOnChain","proof","client","createPublicClient","base","http","proofData","args","output","error","ProofStatus","GITHUB_CLIENT_ID","getLoginWithGithubUrl","callbackUrl","githubClientId","state","getTokenFromAuth","auth","token","err","PUBLIC_SDK_KEY","relayerUtilsResolver","resolve","init","post","url","data","authToken","request","response","body","patch","get","queryParams","fullUrl","searchParams","key","value","del","startJsonFileDownload","json","name","blob","link","Proof","_Proof","blueprint","props","Blueprint","sinceLastChecked","newProof","id","baseUrl","proofResponse","proofProps","relayerUtilsInit","parseEmail","eml","parseEmailUtils","testBlueprint","revealPrivate","parsedEmail","splitEmail","header","checkInputLengths","dcr","testDecomposedRegex","encoder","headerData","sha256Pad","bodyData","bodyShaLength","maxShaBytes","decomposedRegex","inputDecomposedRegex","inputStr","maxLength","privateResult","extractSubstr","generateProofInputs","decomposedRegexes","externalInputs","params","internalParams","decomposedRegexesCleaned","p","inputs","generateCircuitInputsWithDecomposedRegexesAndExternalInputs","Prover","options","blueprintId","input","requestData","acc","ZkFramework","Status","_Blueprint","blueprintResponse","blueprintProps","slug","parts","version","regex","part","newProps","requestOptions","status","urls","cloned","stars","getStarredBlueprints","slugs","src_default","sdkOptions"],"mappings":"oNAKA,SAASA,CAAAA,CAAuBC,EAAsB,CACpD,OAAO,CACL,CACE,IAAM,CAAA,UAAA,CACN,KAAM,QACN,CAAA,MAAA,CAAQ,CACN,CACE,IAAM,CAAA,GAAA,CACN,KAAM,YACN,CAAA,YAAA,CAAc,YAChB,CAAA,CACA,CACE,IAAA,CAAM,IACN,IAAM,CAAA,eAAA,CACN,YAAc,CAAA,eAChB,CACA,CAAA,CACE,KAAM,GACN,CAAA,IAAA,CAAM,YACN,CAAA,YAAA,CAAc,YAChB,CAAA,CACA,CACE,IAAM,CAAA,SAAA,CACN,IAAM,CAAA,CAAA,QAAA,EAAWA,CAAY,CAAA,CAAA,CAAA,CAC7B,aAAc,CAAWA,QAAAA,EAAAA,CAAY,CACvC,CAAA,CAAA,CACF,CACA,CAAA,OAAA,CAAS,EACT,CAAA,eAAA,CAAiB,MACnB,CACF,CACF,CAEA,eAAsBC,CAAmBC,CAAAA,CAAAA,CAAc,CACrD,GACE,CAACA,CAAAA,CAAM,UAAU,KAAM,CAAA,gBAAA,EAAkB,KACzC,EAAA,CAACA,CAAM,CAAA,SAAA,CAAU,MAAM,gBAAkB,EAAA,OAAA,CAEzC,MAAM,IAAI,KAAM,CAAA,+DAA+D,EAGjF,GAAI,CAACA,CAAM,CAAA,KAAA,CAAM,SAAa,EAAA,CAACA,EAAM,KAAM,CAAA,aAAA,CACzC,MAAM,IAAI,KAAM,CAAA,6BAA6B,EAI/C,IAAMC,CAAAA,CAASC,kBAAmB,CAAA,CAChC,KAAOC,CAAAA,IAAAA,CACP,UAAWC,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AAAA,CAAAA,CAAS6D,CAAY,EAAA,IAAI,CACjE,CACA,CAAA,MAAM,cAAexB,CAAAA,CAAAA,CAAuD,CAC1E,OAAOzC,EAAU,cAAeI,CAAAA,CAAAA,CAASqC,CAASwB,CAAAA,CAAAA,EAAY,IAAI,CACpE,EACA,MAAM,QAAA,CAAS9D,CAA4B,CAAA,CACzC,OAAOP,CAAAA,CAAM,aAAaO,CAAIC,CAAAA,CAAO,CACvC,CAAA,CACA,MAAM,oBAAA,EAA0C,CAC9C,GAAI,CAAC6D,CAAc,EAAA,CAACA,CAAY,CAAA,IAAA,CAC9B,MAAM,IAAI,KAAA,CAAM,8DAA8D,CAAA,CAEhF,OAAOH,CAAAA,CAAqB1D,EAAS6D,CAAY,CAAA,IAAK,CACxD,CACF,CACF","file":"index.mjs","sourcesContent":["import { createPublicClient, http, Account, PublicClient } from \"viem\";\nimport { base } from \"viem/chains\";\nimport { Proof } from \"../proof\";\nimport { ProofData } from \"../types\";\n\nfunction getVerifierContractAbi(signalLength: number) {\n return [\n {\n type: \"function\",\n name: \"verify\",\n inputs: [\n {\n name: \"a\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"b\",\n type: \"uint256[2][2]\",\n internalType: \"uint256[2][2]\",\n },\n {\n name: \"c\",\n type: \"uint256[2]\",\n internalType: \"uint256[2]\",\n },\n {\n name: \"signals\",\n type: `uint256[${signalLength}]`,\n internalType: `uint256[${signalLength}]`,\n },\n ],\n outputs: [],\n stateMutability: \"view\",\n },\n ];\n}\n\nexport async function verifyProofOnChain(proof: Proof) {\n if (\n !proof.blueprint.props.verifierContract?.chain ||\n !proof.blueprint.props.verifierContract?.address\n ) {\n throw new Error(\"No verifier contract deployed for the blueprint of this proof\");\n }\n\n if (!proof.props.proofData || !proof.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // Create public client for Base Sepolia\n const client = createPublicClient({\n chain: base,\n transport: http(\"https://sepolia.base.org\"),\n });\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = proof.props.proofData as ProofData;\n\n const args = [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n proof.props.publicOutputs.map((output) => BigInt(output)),\n ] as const;\n\n console.log(\"Call data to verify: \", args);\n console.log(\"contract address: \", proof.blueprint.props.verifierContract.address);\n\n try {\n await client.readContract({\n address: proof.blueprint.props.verifierContract.address as `0x${string}`,\n abi: getVerifierContractAbi(proof.props.publicOutputs.length),\n functionName: \"verify\",\n args,\n });\n } catch (error) {\n console.error(\"Error verifying proof on chain:\", error);\n throw error;\n }\n}\n","import { Dir } from \"fs\";\nimport { ServerDate } from \"./blueprint\";\n\n// According to protobufs\nexport enum ProofStatus {\n None,\n InProgress,\n Done,\n Failed,\n}\n\nexport type ProofProps = {\n id: string;\n blueprintId: string;\n input: string;\n proofData?: string;\n publicData?: string;\n publicOutputs?: string[];\n externalInputs?: string;\n status?: ProofStatus;\n startedAt?: Date;\n provedAt?: Date;\n};\n\nexport type ProofResponse = {\n id: string;\n blueprint_id: string;\n input: string;\n proof?: string;\n public?: string;\n external_inputs?: string;\n public_outputs?: string[];\n started_at: ServerDate;\n proved_at?: ServerDate;\n status: number;\n};\n\nexport type ProofRequest = {\n blueprint_id: string;\n input: any;\n external_inputs: any;\n};\n\nexport type GenerateProofInputsParams = {\n emailHeaderMaxLength: number;\n emailBodyMaxLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinebreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type GenerateProofInputsParamsInternal = {\n maxHeaderLength: number;\n maxBodyLength: number;\n ignoreBodyHashCheck: boolean;\n removeSoftLinesBreaks: boolean;\n shaPrecomputeSelector?: string;\n};\n\nexport type ProofData = {\n pi_a: [string, string, string];\n pi_b: [[string, string], [string, string], [string, string]];\n pi_c: [string, string, string];\n protocol: string;\n};\n","import { Auth } from \"./types/auth\";\n\n// prod\nconst GITHUB_CLIENT_ID = \"Ov23li0KABFCUsxBEQkn\";\n\n// const GITHUB_CLIENT_ID = \"Ov23liUVyAeZK1bxoAkh\";\n\nexport function getLoginWithGithubUrl(\n callbackUrl: string,\n githubClientId = GITHUB_CLIENT_ID\n): string {\n const state = encodeURIComponent(callbackUrl);\n return `https://github.com/login/oauth/authorize?client_id=${githubClientId}&scope=user:email&state=${state}`;\n}\n\nexport async function getTokenFromAuth(auth: Auth): Promise<string> {\n try {\n let token = await auth.getToken();\n\n if (!token) {\n await auth.onTokenExpired();\n token = await auth.getToken();\n }\n\n if (!token) {\n throw new Error(\"Failed to get new token\");\n }\n\n return `Bearer ${token}`;\n } catch (err) {\n console.error(\"Failed to get token from auth\");\n throw err;\n }\n}\n","const PUBLIC_SDK_KEY = \"pk_live_51NXwT8cHf0vYAjQK9LzB3pM6R8gWx2F\";\n\nimport {\n Blueprint,\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport { Auth } from \"./types/auth\";\nimport { getTokenFromAuth } from \"./auth\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\n\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function post<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"POST Error:\", error);\n throw error;\n }\n}\n\nexport async function patch<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"PATCH\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n console.error(\"PATCH Error:\", error);\n throw error;\n }\n}\n\nexport async function get<T>(url: string, queryParams?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.warn(\"Could not get token from auth\", err);\n }\n }\n\n try {\n let fullUrl = url;\n if (queryParams) {\n const searchParams = new URLSearchParams();\n Object.entries(queryParams).forEach(([key, value]) => {\n if (value) {\n searchParams.append(key, String(value));\n }\n });\n if (searchParams.size > 0) {\n fullUrl += `?${searchParams.toString()}`;\n }\n }\n\n const response = await fetch(fullUrl, {\n method: \"GET\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n });\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`);\n }\n\n return await response.json();\n } catch (error) {\n console.error(\"GET Error:\", error);\n throw error;\n }\n}\n\nexport async function del<T>(url: string, data?: object | null, auth?: Auth): Promise<T> {\n let authToken: string | null = null;\n if (auth) {\n try {\n authToken = await getTokenFromAuth(auth);\n } catch (err) {\n console.error(\"Could not get token from auth\", err);\n }\n }\n\n try {\n const request: RequestInit = {\n method: \"DELETE\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": PUBLIC_SDK_KEY,\n ...(!authToken ? {} : { Authorization: authToken }),\n },\n };\n\n if (data) {\n request.body = JSON.stringify(data);\n }\n\n const response = await fetch(url, request);\n\n const body = await response.json();\n\n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}, message: ${body}`);\n }\n\n return body;\n } catch (error) {\n // TODO: Handle token expired\n console.error(\"DELETE Error:\", error);\n throw error;\n }\n}\n\nexport function startJsonFileDownload(json: string, name = \"data\") {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n const blob = new Blob([json], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = `${name}.json`;\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n URL.revokeObjectURL(url);\n}\n","import { Blueprint, Status } from \"./blueprint\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { ProofProps, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { get } from \"./utils\";\n\n/**\n * A generated proof. You get get proof data and verify proofs on chain.\n */\nexport class Proof {\n blueprint: Blueprint;\n props: ProofProps;\n private lastCheckedStatus: Date | null = null;\n\n constructor(blueprint: Blueprint, props: ProofProps) {\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n this.blueprint = blueprint;\n\n if (!props?.id) {\n throw new Error(\"A proof must have an id\");\n }\n\n this.props = {\n status: ProofStatus.InProgress,\n ...props,\n };\n }\n\n getId(): string {\n return this.props.id;\n }\n\n /**\n * Returns a download link for the files of the proof.\n * @returns The the url to download a zip of the proof files.\n */\n async getProofDataDownloadLink(): Promise<string> {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"The proving is not done yet.\");\n }\n\n let response: { url: string };\n try {\n response = await get<{ url: string }>(\n `${this.blueprint.baseUrl}/proof/files/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /proof/files/:id in getProofDataDownloadLink: \", err);\n throw err;\n }\n\n return response.url;\n }\n\n async startFilesDownload() {\n if (!window && !document) {\n throw Error(\"startFilesDownload can only be used in a browser\");\n }\n\n let url: string;\n try {\n url = await this.getProofDataDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = \"proof_files.zip\"; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n\n /**\n * Checks the status of proof.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time before the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<ProofStatus> {\n if (this.props.status === ProofStatus.Done) {\n return this.props.status;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatu()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n const waitTime = 500;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n // Check status\n let response: { status: ProofStatus };\n try {\n response = await get<{ status: ProofStatus }>(\n `${this.blueprint.baseUrl}/proof/status/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n // Update the proof to its new data\n if (\n [ProofStatus.InProgress, ProofStatus.Done].includes(this.props.status!) &&\n this.props.status !== response.status\n ) {\n const newProof = await Proof.getProofById(this.props.id, this.blueprint.baseUrl);\n this.props = newProof.props;\n return this.props.status!;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n async waitForCompletion(): Promise<ProofStatus> {\n while ((await this.checkStatus()) === ProofStatus.InProgress) {}\n return this.props.status!;\n }\n\n /**\n * Verifies the proof on chain using the verifier contract defined in the blueprint.\n * Will throw an error if it cannot verify the proof. If the function call succeeds,\n * the proof was validated.\n */\n async verifyOnChain() {\n await verifyProofOnChain(this);\n }\n\n /**\n * Generates call data for the proof that can be used to verify the proof on chain.\n */\n async createCallData() {\n if (!this.props.proofData || !this.props.publicOutputs) {\n throw new Error(\"No proof data generated yet\");\n }\n\n // TODO: this is parsed when getting the data from the backend,\n // add propper typing from the start\n // @ts-ignore\n const proofData = this.props.proofData as ProofData;\n\n return [\n [BigInt(proofData.pi_a[0]), BigInt(proofData.pi_a[1])],\n [\n [\n BigInt(proofData.pi_b[0][1]), // swap coordinates\n BigInt(proofData.pi_b[0][0]),\n ],\n [\n BigInt(proofData.pi_b[1][1]), // swap coordinates\n BigInt(proofData.pi_b[1][0]),\n ],\n ],\n [BigInt(proofData.pi_c[0]), BigInt(proofData.pi_c[1])],\n this.props.publicOutputs.map((output) => BigInt(output)),\n ];\n }\n\n /**\n * Fetches an existing Proof from the database.\n * @param id - Id of the Proof.\n * @returns A promise that resolves to a new instance of Proof.\n */\n public static async getProofById(id: string, baseUrl: string): Promise<Proof> {\n let proofResponse: ProofResponse;\n try {\n proofResponse = await get<ProofResponse>(`${baseUrl}/proof/${id}`);\n } catch (err) {\n console.error(\"Failed calling /proof/:id in getProofById: \", err);\n throw err;\n }\n\n const proofProps = this.responseToProofProps(proofResponse);\n const blueprint = await Blueprint.getBlueprintById(proofResponse.blueprint_id, baseUrl);\n\n return new Proof(blueprint, proofProps);\n }\n\n public static responseToProofProps(response: ProofResponse): ProofProps {\n const props: ProofProps = {\n id: response.id,\n blueprintId: response.blueprint_id,\n status: response.status as ProofStatus,\n input: response.input,\n proofData: response.proof,\n publicData: response.public,\n publicOutputs: response.public_outputs,\n externalInputs: response.external_inputs,\n startedAt: new Date(response.started_at.seconds * 1000),\n provedAt: response.proved_at ? new Date(response.proved_at.seconds * 1000) : undefined,\n };\n return props;\n }\n\n /**\n * @returns The public data and proof data.\n */\n getProofData(): {\n proofData: string;\n publicData: string;\n publicOutputs: string[];\n externalInputs: string;\n } {\n if (this.props.status !== ProofStatus.Done) {\n throw new Error(\"Cannot get proof data, proof is not Done\");\n }\n return {\n proofData: this.props.proofData!,\n publicData: this.props.publicData!,\n publicOutputs: this.props.publicOutputs!,\n externalInputs: this.props.externalInputs!,\n };\n }\n}\n","import {\n DecomposedRegex,\n DecomposedRegexJson,\n DecomposedRegexPart,\n DecomposedRegexPartJson,\n} from \"./blueprint\";\nimport {\n BlueprintProps,\n GenerateProofInputsParams,\n GenerateProofInputsParamsInternal,\n ParsedEmail,\n ExternalInputInput,\n} from \"./types\";\nimport {\n init,\n parseEmail as parseEmailUtils,\n sha256Pad,\n extractSubstr,\n generateCircuitInputsWithDecomposedRegexesAndExternalInputs,\n} from \"@zk-email/relayer-utils\";\n\nlet relayerUtilsResolver: (value: any) => void;\nconst relayerUtilsInit: Promise<void> = new Promise((resolve) => {\n relayerUtilsResolver = resolve;\n});\n\ninit()\n .then(() => {\n relayerUtilsResolver(null);\n })\n .catch((err) => {\n console.log(\"Failed to initialize wasm for relayer-utils: \", err);\n });\n\nexport async function parseEmail(eml: string): Promise<ParsedEmail> {\n try {\n await relayerUtilsInit;\n const parsedEmail = await parseEmailUtils(eml);\n return parsedEmail as ParsedEmail;\n } catch (err) {\n console.error(\"Failed to parse email: \", err);\n throw err;\n }\n}\n\n// TODO: move out functionality to testDecomposedRegex so it can used seperately\nexport async function testBlueprint(\n eml: string,\n blueprint: BlueprintProps,\n revealPrivate = false\n): Promise<string[][]> {\n const parsedEmail = await parseEmail(eml);\n\n if (\n (blueprint.emailBodyMaxLength === undefined && !blueprint.ignoreBodyHashCheck) ||\n blueprint.emailHeaderMaxLength === undefined\n ) {\n throw new Error(\"emailBodyMaxLength and emailHeaderMaxLength must be provided\");\n }\n\n let body = parsedEmail.cleanedBody;\n if (blueprint.shaPrecomputeSelector) {\n const splitEmail = body.split(blueprint.shaPrecomputeSelector)[1];\n if (!splitEmail) {\n throw new Error(\n `Precompute selector was not found in email, selector: ${blueprint.shaPrecomputeSelector}`\n );\n }\n body = splitEmail;\n }\n\n const header = parsedEmail.canonicalizedHeader;\n\n await checkInputLengths(header, body, blueprint);\n\n const output = await Promise.all(\n blueprint.decomposedRegexes.map((dcr: DecomposedRegex) =>\n testDecomposedRegex(body, header, dcr, revealPrivate)\n )\n );\n\n return output;\n}\n\nasync function checkInputLengths(header: string, body: string, blueprint: BlueprintProps) {\n await relayerUtilsInit;\n const encoder = new TextEncoder();\n const headerData = encoder.encode(header);\n const headerLength = (await sha256Pad(headerData, blueprint.emailHeaderMaxLength!)).get(\n \"messageLength\"\n );\n if (headerLength > blueprint.emailHeaderMaxLength!) {\n throw new Error(`emailHeaderMaxLength of ${blueprint.emailHeaderMaxLength} was exceeded`);\n }\n\n if (!blueprint.ignoreBodyHashCheck) {\n const bodyData = encoder.encode(body);\n\n const bodyShaLength = ((body.length + 63 + 65) / 64) * 64;\n\n const maxShaBytes = Math.max(bodyShaLength, blueprint.emailBodyMaxLength!);\n\n const bodyLength = (await sha256Pad(bodyData, maxShaBytes)).get(\"messageLength\");\n\n if (bodyLength > blueprint.emailBodyMaxLength!) {\n throw new Error(`emailBodyMaxLength of ${blueprint.emailBodyMaxLength} was exceeded`);\n }\n }\n}\n\nexport async function testDecomposedRegex(\n body: string,\n header: string,\n decomposedRegex: DecomposedRegex | DecomposedRegexJson,\n revealPrivate = false\n): Promise<string[]> {\n const inputDecomposedRegex = {\n parts: decomposedRegex.parts.map((p: DecomposedRegexPart | DecomposedRegexPartJson) => ({\n is_public: \"isPublic\" in p ? p.isPublic : p.is_public,\n regex_def: \"regexDef\" in p ? p.regexDef : p.regex_def,\n })),\n };\n\n let inputStr: string;\n if (decomposedRegex.location === \"body\") {\n inputStr = body;\n } else if (decomposedRegex.location === \"header\") {\n inputStr = header;\n } else {\n throw Error(`Unsupported location ${decomposedRegex.location}`);\n }\n\n const maxLength =\n \"maxLength\" in decomposedRegex ? decomposedRegex.maxLength : decomposedRegex.max_length;\n\n await relayerUtilsInit;\n const privateResult = extractSubstr(inputStr, inputDecomposedRegex, false);\n\n if (privateResult[0].length > maxLength) {\n throw new Error(\n `Max length of extracted result was exceeded for decomposed regex ${decomposedRegex.name}`\n );\n }\n\n if (!revealPrivate) {\n return privateResult;\n }\n\n const result = extractSubstr(inputStr, inputDecomposedRegex, revealPrivate);\n return result;\n}\n\nexport async function generateProofInputs(\n eml: string,\n decomposedRegexes: DecomposedRegex[],\n externalInputs: ExternalInputInput[],\n params: GenerateProofInputsParams\n): Promise<string> {\n try {\n const internalParams: GenerateProofInputsParamsInternal = {\n maxHeaderLength: params.emailHeaderMaxLength,\n maxBodyLength: params.emailBodyMaxLength,\n ignoreBodyHashCheck: params.ignoreBodyHashCheck,\n removeSoftLinesBreaks: params.removeSoftLinebreaks,\n shaPrecomputeSelector: params.shaPrecomputeSelector,\n };\n\n await relayerUtilsInit;\n\n const decomposedRegexesCleaned = decomposedRegexes.map((dcr) => {\n return {\n ...dcr,\n parts: dcr.parts.map((p) => ({\n // @ts-ignore\n is_public: p.isPublic || !!p.is_public,\n // @ts-ignore\n regex_def: p.regexDef || !!p.regex_def,\n })),\n };\n });\n\n const inputs = await generateCircuitInputsWithDecomposedRegexesAndExternalInputs(\n eml,\n decomposedRegexesCleaned,\n externalInputs,\n internalParams\n );\n\n return JSON.stringify(Object.fromEntries(inputs));\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n}\n","import { Blueprint } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { generateProofInputs } from \"./relayerUtils\";\nimport { GenerateProofInputsParams, ProofRequest, ProofResponse, ProofStatus } from \"./types/proof\";\nimport { ExternalInputInput, ProverOptions } from \"./types/prover\";\nimport { post } from \"./utils\";\n\n/**\n * Represents a Prover generated from a blueprint that can generate Proofs\n */\nexport class Prover {\n options: ProverOptions;\n blueprint: Blueprint;\n\n constructor(blueprint: Blueprint, options?: ProverOptions) {\n if (options?.isLocal === true) {\n throw new Error(\"Local proving is not supported yet\");\n }\n\n if (!(blueprint instanceof Blueprint)) {\n throw new Error(\"Invalid blueprint: must be an instance of Blueprint class\");\n }\n\n this.blueprint = blueprint;\n\n // Use defaults for unset fields\n this.options = {\n isLocal: false,\n ...(!!options ? options : {}),\n };\n }\n\n // TODO: Add parsed email input\n /**\n * Generates a proof for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * Done or Failed.\n */\n async generateProof(eml: string, externalInputs: ExternalInputInput[] = []): Promise<Proof> {\n const proof = await this.generateProofRequest(eml, externalInputs);\n\n // Wait for proof to finish\n while (![ProofStatus.Done, ProofStatus.Failed].includes(await proof.checkStatus())) {}\n return proof;\n }\n\n // TODO: Add parsed email input\n /**\n * Starts proving for a given email.\n * @param eml - Email to prove agains the blueprint of this Prover.\n * @returns A promise that resolves to a new instance of Proof. The Proof will have the status\n * InProgress.\n */\n async generateProofRequest(\n eml: string,\n externalInputs: ExternalInputInput[] = []\n ): Promise<Proof> {\n const blueprintId = this.blueprint.getId();\n if (!blueprintId) {\n throw new Error(\"Blueprint of Proover must be initialized in order to create a Proof\");\n }\n\n if (this.blueprint.props.externalInputs?.length && !externalInputs.length) {\n throw new Error(\n `The ${this.blueprint.props.slug} blueprint requires external inputs: ${this.blueprint.props.externalInputs}`\n );\n }\n\n let input: string;\n try {\n // TODO: Do we use defaults?\n const params: GenerateProofInputsParams = {\n emailHeaderMaxLength: this.blueprint.props.emailHeaderMaxLength || 256,\n emailBodyMaxLength: this.blueprint.props.emailBodyMaxLength || 2560,\n ignoreBodyHashCheck: this.blueprint.props.ignoreBodyHashCheck || false,\n removeSoftLinebreaks: this.blueprint.props.removeSoftLinebreaks || true,\n shaPrecomputeSelector: this.blueprint.props.shaPrecomputeSelector,\n };\n console.log(\"generating proof inputs\");\n input = await generateProofInputs(\n eml,\n this.blueprint.props.decomposedRegexes,\n externalInputs,\n params\n );\n } catch (err) {\n console.error(\"Failed to generate inputs for proof\");\n throw err;\n }\n\n console.log(\"got proof input\");\n let response: ProofResponse;\n try {\n const requestData: ProofRequest = {\n blueprint_id: blueprintId,\n input: JSON.parse(input),\n external_inputs: externalInputs.reduce(\n (acc, input) => ({\n ...acc,\n [input.name]: input.value,\n }),\n {}\n ),\n };\n\n response = await post<ProofResponse>(`${this.blueprint.baseUrl}/proof`, requestData);\n } catch (err) {\n console.error(\"Failed calling POST on /proof/ in generateProofRequest: \", err);\n throw err;\n }\n\n const proofProps = Proof.responseToProofProps(response);\n return new Proof(this.blueprint, proofProps);\n }\n}\n","export type BlueprintProps = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n emailQuery?: string;\n circuitName: string;\n ignoreBodyHashCheck?: boolean;\n shaPrecomputeSelector?: string;\n emailBodyMaxLength?: number;\n emailHeaderMaxLength?: number;\n removeSoftLinebreaks?: boolean;\n githubUsername?: string;\n senderDomain?: string;\n enableHeaderMasking?: boolean;\n enableBodyMasking?: boolean;\n zkFramework?: ZkFramework;\n isPublic?: boolean;\n createdAt?: Date;\n updatedAt?: Date;\n externalInputs?: ExternalInput[];\n decomposedRegexes: DecomposedRegex[];\n status?: Status;\n verifierContract?: VerifierContract;\n version?: number;\n stars?: number;\n};\n\nexport type DecomposedRegex = {\n parts: DecomposedRegexPart[];\n name: string;\n maxLength: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPart = {\n isPublic: boolean;\n regexDef: string;\n};\n\nexport type DecomposedRegexJson = {\n parts: DecomposedRegexPartJson[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartJson = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ExternalInput = {\n name: string;\n maxLength: number;\n};\n\nexport enum ZkFramework {\n Circom = \"circom\",\n}\n\n// According to protobufs\nexport enum Status {\n None,\n Draft,\n InProgress,\n Done,\n Failed,\n}\n\nexport type VerifierContract = {\n address?: string;\n chain: number;\n};\n\nexport type BlueprintRequest = {\n id?: string;\n title: string;\n description?: string;\n slug?: string;\n tags?: string[];\n email_query?: string;\n circuit_name?: string;\n ignore_body_hash_check?: boolean;\n sha_precompute_selector?: string;\n email_body_max_length?: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n // TODO: Make non ? after login with github\n github_username?: string;\n sender_domain?: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework?: string;\n is_public?: boolean;\n external_inputs?: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status?: string;\n verifier_contract_address?: string;\n verifier_contract_chain?: number;\n version?: number;\n};\n\nexport type BlueprintResponse = {\n id: string;\n title: string;\n description: string;\n slug: string;\n tags: string[];\n email_query: string;\n circuit_name: string;\n ignore_body_hash_check: boolean;\n sha_precompute_selector: string;\n email_body_max_length: number;\n email_header_max_length?: number;\n remove_soft_linebreaks?: boolean;\n github_username?: string;\n sender_domain: string;\n enable_header_masking?: boolean;\n enable_body_masking?: boolean;\n zk_framework: string;\n is_public: boolean;\n created_at: ServerDate;\n updated_at: ServerDate;\n external_inputs: ExternalInputResponse[];\n decomposed_regexes: DecomposedRegexResponse[];\n status: number;\n verifier_contract_address: string;\n verifier_contract_chain: number;\n version: number;\n stars: number;\n};\n\nexport type ServerDate = {\n seconds: number;\n nanos: number;\n};\n\nexport type ExternalInputResponse = {\n name: string;\n max_length: number;\n};\n\nexport type DecomposedRegexResponse = {\n parts: DecomposedRegexPartResponse[];\n name: string;\n max_length: number;\n location: \"body\" | \"header\";\n};\n\nexport type DecomposedRegexPartResponse = {\n is_public: boolean;\n regex_def: string;\n};\n\nexport type ListBlueprintsOptions = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n sortBy?: \"updatedAt\" | \"stars\";\n status?: Status[];\n isPublic?: boolean;\n search?: string;\n};\n\nexport type ListBlueprintsOptionsRequest = {\n skip?: number;\n limit?: number;\n sort?: -1 | 1;\n sort_by?: \"updated_at\" | \"stars\";\n status?: Status[];\n is_public?: boolean;\n search?: string;\n};\n\nexport type DownloadUrls = Record<string, string>;\n","import { Prover } from \"./prover\";\nimport {\n BlueprintProps,\n BlueprintRequest,\n BlueprintResponse,\n DownloadUrls,\n ListBlueprintsOptions,\n ListBlueprintsOptionsRequest,\n Status,\n ZkFramework,\n} from \"./types/blueprint\";\nimport { del, get, patch, post } from \"./utils\";\nimport { verifyProofOnChain } from \"./chain\";\nimport { Auth } from \"./types/auth\";\nimport { Proof } from \"./proof\";\n\n/**\n * Represents a Regex Blueprint including the decomposed regex access to the circuit.\n */\nexport class Blueprint {\n // TODO: Implement getter and setter pattern\n props: BlueprintProps;\n auth?: Auth;\n baseUrl: string;\n stars = 0;\n\n private lastCheckedStatus: Date | null = null;\n\n constructor(props: BlueprintProps, baseUrl: string, auth?: Auth) {\n // Use defaults for unset fields\n this.props = {\n ignoreBodyHashCheck: false,\n enableHeaderMasking: false,\n enableBodyMasking: false,\n isPublic: true,\n status: Status.Draft,\n ...props,\n };\n\n this.baseUrl = baseUrl;\n this.auth = auth;\n }\n\n addAuth(auth: Auth) {\n this.auth = auth;\n }\n\n /**\n * Fetches an existing RegexBlueprint from the database.\n * @param {string} id - Id of the RegexBlueprint.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintById(\n id: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n let blueprintResponse: BlueprintResponse;\n try {\n blueprintResponse = await get<BlueprintResponse>(`${baseUrl}/blueprint/${id}`);\n } catch (err) {\n console.error(\"Failed calling /blueprint/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n /**\n * Fetches an existing RegexBlueprint by slug from the database.\n * @param slug - Slug of the blueprint. Must include version, e.g. \"slug:v1\"\n * @param version - Version of the slug.\n * @returns A promise that resolves to a new instance of RegexBlueprint.\n */\n public static async getBlueprintBySlug(\n slug: string,\n baseUrl: string,\n auth?: Auth\n ): Promise<Blueprint> {\n const parts = slug.split(\"@\");\n\n if (!parts || !(parts.length > 1)) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n const version = parts.pop()!.replace(\"v\", \"\");\n\n slug = encodeURIComponent(parts.join(\"\"));\n\n if (!version) {\n throw new Error(\"You must provide the blueprint version, e.g. 'user/slug@v1\");\n }\n\n let blueprintResponse: BlueprintResponse;\n try {\n const url = `${baseUrl}/blueprint/by-slug/${slug}/${version}`;\n blueprintResponse = await get<BlueprintResponse>(url);\n } catch (err) {\n console.error(\"Failed calling /blueprint/by-slug/:slug/:id in getBlueprintById: \", err);\n throw err;\n }\n\n const blueprintProps = this.responseToBlueprintProps(blueprintResponse);\n\n const blueprint = new Blueprint(blueprintProps, baseUrl, auth);\n\n return blueprint;\n }\n\n // Maps the blueprint API response to the BlueprintProps\n private static responseToBlueprintProps(response: BlueprintResponse): BlueprintProps {\n const props: BlueprintProps = {\n id: response.id,\n title: response.title,\n description: response.description,\n slug: response.slug,\n tags: response.tags,\n emailQuery: response.email_query,\n circuitName: response.circuit_name,\n ignoreBodyHashCheck: response.ignore_body_hash_check,\n shaPrecomputeSelector: response.sha_precompute_selector,\n emailBodyMaxLength: response.email_body_max_length,\n emailHeaderMaxLength: response.email_header_max_length,\n removeSoftLinebreaks: response.remove_soft_linebreaks,\n githubUsername: response.github_username,\n senderDomain: response.sender_domain,\n enableHeaderMasking: response.enable_header_masking,\n enableBodyMasking: response.enable_body_masking,\n zkFramework: response.zk_framework as ZkFramework,\n isPublic: response.is_public,\n createdAt: new Date(response.created_at.seconds * 1000),\n updatedAt: new Date(response.updated_at.seconds * 1000),\n externalInputs: response.external_inputs?.map((input) => ({\n name: input.name,\n maxLength: input.max_length,\n })),\n decomposedRegexes: response.decomposed_regexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n isPublic: part.is_public,\n regexDef: part.regex_def,\n })),\n name: regex.name,\n maxLength: regex.max_length,\n location: regex.location,\n })),\n status: response.status as Status,\n verifierContract: {\n address: response.verifier_contract_address,\n chain: response.verifier_contract_chain,\n },\n version: response.version,\n stars: response.stars,\n };\n\n return props;\n }\n\n // Maps the BlueprintProps to the BlueprintResponse\n private static blueprintPropsToRequest(props: BlueprintProps): BlueprintRequest {\n const response: BlueprintRequest = {\n id: props.id,\n title: props.title,\n description: props.description,\n slug: props.slug,\n tags: props.tags,\n email_query: props.emailQuery,\n circuit_name: props.circuitName,\n ignore_body_hash_check: props.ignoreBodyHashCheck,\n sha_precompute_selector: props.shaPrecomputeSelector,\n email_body_max_length: props.emailBodyMaxLength,\n email_header_max_length: props.emailHeaderMaxLength,\n remove_soft_linebreaks: props.removeSoftLinebreaks,\n github_username: props.githubUsername,\n sender_domain: props.senderDomain,\n enable_header_masking: props.enableHeaderMasking,\n enable_body_masking: props.enableBodyMasking,\n zk_framework: props.zkFramework,\n is_public: props.isPublic,\n external_inputs: props.externalInputs?.map((input) => ({\n name: input.name,\n max_length: input.maxLength,\n })),\n decomposed_regexes: props.decomposedRegexes?.map((regex) => ({\n parts: regex.parts.map((part) => ({\n // @ts-ignore\n is_public: part.isPublic || part.is_public,\n // @ts-ignore\n regex_def: part.regexDef || part.regex_def,\n })),\n name: regex.name,\n max_length: regex.maxLength,\n location: regex.location,\n })),\n verifier_contract_address: props.verifierContract?.address,\n verifier_contract_chain: props.verifierContract?.chain,\n };\n\n return response;\n }\n\n /**\n * Submits a new RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public async submitDraft() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (this.props.id) {\n throw new Error(\"Blueprint was already saved\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(this.props);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the RegexBlueprint to the registry as draft.\n * This does not compile the circuits yet and you will still be able to make changes.\n * @param newProps - The updated blueprint props.\n * @returns A promise. Once it resolves, the current Blueprint will be replaced with the new one.\n */\n public async submitNewVersionDraft(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await post<BlueprintResponse>(`${this.baseUrl}/blueprint`, requestData, this.auth);\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitNewVersionDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n /**\n * Submits a new version of the blueprint. This will save the new blueprint version\n * and start the compilation.\n * This will also overwrite the current Blueprint with its new version, even if the last\n * version was not compiled yet.\n * @param newProps - The updated blueprint props.\n */\n async submitNewVersion(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n await this.submitNewVersionDraft(newProps);\n\n // We don't check the status here, since we are compiling directly after submiting the draft.\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n /**\n * Lists blueblueprints, only including the latest version per unique slug.\n * @param options - Options to filter the blueprints by.\n * @returns A promise. Once it resolves, `getId` can be called.\n */\n public static async listBlueprints(\n baseUrl: string,\n options?: ListBlueprintsOptions,\n auth?: Auth\n ): Promise<Blueprint[]> {\n const requestOptions: ListBlueprintsOptionsRequest = {\n skip: options?.skip,\n limit: options?.limit,\n sort: options?.sort,\n status: options?.status,\n is_public: options?.isPublic,\n sort_by: options?.sortBy === \"updatedAt\" ? \"updated_at\" : options?.sortBy,\n search: options?.search,\n };\n\n let response: { blueprints?: BlueprintResponse[] };\n try {\n response = await get<{ blueprints?: BlueprintResponse[] }>(\n `${baseUrl}/blueprint`,\n requestOptions,\n auth\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/ in listBlueprints: \", err);\n throw err;\n }\n\n if (!response.blueprints) {\n return [];\n }\n\n const blueprints = response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, baseUrl, auth);\n });\n\n return blueprints;\n }\n\n /**\n * Submits a blueprint. This will save the blueprint if it didn't exist before\n * and start the compilation.\n */\n async submit() {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n // If the blueprint wasn't save yet, we save it first to db\n if (!this.props.id) {\n try {\n await this.submitDraft();\n } catch (err) {\n console.error(\"Failed to create blueprint: \", err);\n throw err;\n }\n }\n\n const status = await this._checkStatus();\n\n // TODO: Should we allow retry on failed?\n if (Status.Done === status) {\n throw new Error(\"The circuits are already compiled.\");\n }\n if (Status.InProgress === status) {\n throw new Error(\"The circuits already being compiled, please wait.\");\n }\n\n // Submit compile request\n try {\n await post<{ status: Status }>(\n `${this.baseUrl}/blueprint/compile/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n // We don't set the status here, since the api call can't fail due to the actual job failing\n // It can only due to connectivity issues or the job runner not being available\n console.error(\"Failed calling POST on /blueprint/compile in submit: \", err);\n throw err;\n }\n }\n\n // Request status from server and updates props.status\n private async _checkStatus(): Promise<Status> {\n let response: { status: Status };\n try {\n response = await get<{ status: Status }>(`${this.baseUrl}/blueprint/status/${this.props.id}`);\n } catch (err) {\n console.error(\"Failed calling GET /blueprint/status in getStatus(): \", err);\n throw err;\n }\n\n this.props.status = response.status;\n return response.status;\n }\n\n /**\n * Checks the status of blueprint.\n * checkStatus can be used in a while(await checkStatus()) loop, since it will wait a fixed\n * amount of time the second time you call it.\n * @returns A promise with the Status.\n */\n async checkStatus(): Promise<Status> {\n // Blueprint wasn't saved yet, return default status\n if (!this.props.id) {\n return this.props.status!;\n }\n\n if ([Status.Failed, Status.Done].includes(this.props.status!)) {\n return this.props.status!;\n }\n\n // Waits for a fixed period of time before you can call checkStatus again\n // This enables you to put checkStatus in a while(await checkStatus()) loop\n if (!this.lastCheckedStatus) {\n this.lastCheckedStatus = new Date();\n } else {\n // TODO: change for prod to one minute\n const waitTime = 0.5 * 1_000; // TODO: should be one minute;\n const sinceLastChecked = new Date().getTime() - this.lastCheckedStatus.getTime();\n if (sinceLastChecked < waitTime) {\n await new Promise((r) => setTimeout(r, waitTime - sinceLastChecked));\n }\n }\n\n const status = await this._checkStatus();\n\n return status;\n }\n\n /**\n * Get the id of the blueprint.\n * @returns The id of the blueprint. If it was not saved yet, return null.\n */\n getId(): string | null {\n return this.props.id || null;\n }\n\n /**\n * Returns a download link for the ZKeys of the blueprint.\n * @returns The the url to download the ZKeys.\n */\n async getZKeyDownloadLink(): Promise<DownloadUrls> {\n if (this.props.status !== Status.Done) {\n throw new Error(\"The circuits are not compiled yet, nothing to download.\");\n }\n\n let response: { urls: DownloadUrls };\n try {\n response = await get<{ urls: DownloadUrls }>(\n `${this.baseUrl}/blueprint/zkey/${this.props.id}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/zkey/:id in getZKeyDownloadLink: \", err);\n throw err;\n }\n\n return response.urls;\n }\n\n /**\n * Directly starts a download of the ZKeys in the browser.\n * Must be called within a user action, like a button click.\n */\n async startZKeyDownload() {\n if (!window && !document) {\n throw Error(\"startZKeyDownload can only be used in a browser\");\n }\n\n let urls: DownloadUrls;\n try {\n urls = await this.getZKeyDownloadLink();\n } catch (err) {\n console.error(\"Failed to start download of ZKeys: \", err);\n throw err;\n }\n\n for (const [name, url] of Object.entries(urls)) {\n const link = document.createElement(\"a\");\n link.href = url;\n link.download = name; // Set the desired filename\n document.body.appendChild(link);\n link.click();\n document.body.removeChild(link);\n }\n }\n\n /**\n * Creates an instance of Prover with which you can create proofs.\n * @returns An instance of Prover.\n */\n createProver() {\n return new Prover(this);\n }\n\n /**\n * Verifies a proof on chain.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n async verifyProofOnChain(proof: Proof): Promise<boolean> {\n try {\n await verifyProofOnChain(proof);\n } catch (err) {\n console.error(\"Failed to verify proof on chain: \", err);\n return false;\n }\n return true;\n }\n\n /**\n * Returns a deep cloned version of the Blueprints props.\n * This can be used to update properties and then to use them with createNewVersion.\n * @param proof - The generated proof you want to verify.\n * @returns A true if the verification was successfull, false if it failed.\n */\n getClonedProps(): BlueprintProps {\n const cloned = JSON.parse(JSON.stringify(this.props));\n\n // Conver date strings\n if (cloned.createdAt) {\n cloned.createdAt = new Date(cloned.createdAt);\n }\n if (cloned.updatedAt) {\n cloned.updatedAt = new Date(cloned.updatedAt);\n }\n\n return cloned;\n }\n\n /**\n * Returns true if the blueprint can be updated. A blueprint can be updated if the circuits\n * haven't beed compiled yet, i.e. the status is not Done. The blueprint also must be saved\n * already before it can be updated.\n * @returns true if it can be updated\n */\n canUpdate(): boolean {\n return !!(this.props.id && ![Status.Done, Status.InProgress].includes(this.props.status!));\n }\n\n /**\n * Updates an existing blueprint that is not compiled yet.\n * @param newProps - The props the blueprint should be updated to.\n * @returns a promise.\n */\n async update(newProps: BlueprintProps) {\n if (!this.auth) {\n throw new Error(\"auth is required, add it with Blueprint.addAuth(auth)\");\n }\n\n if (!this.canUpdate()) {\n throw new Error(\"Blueprint already compied, cannot update\");\n }\n\n const requestData = Blueprint.blueprintPropsToRequest(newProps);\n\n let response: BlueprintResponse;\n try {\n response = await patch<BlueprintResponse>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n requestData,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/ in submitDraft: \", err);\n throw err;\n }\n\n this.props = Blueprint.responseToBlueprintProps(response);\n }\n\n async listAllVersions(): Promise<Blueprint[]> {\n if (!this.props.id) {\n throw new Error(\"Blueprint was not saved yet\");\n }\n let response: { blueprints: BlueprintResponse[] };\n try {\n response = await get<{ blueprints: BlueprintResponse[] }>(\n `${this.baseUrl}/blueprint/versions/${encodeURIComponent(this.props.slug!)}`\n );\n } catch (err) {\n console.error(\"Failed calling GET on /blueprint/versions/:slug in listAllVersions: \", err);\n throw err;\n }\n\n return response.blueprints.map((blueprintResponse) => {\n const blueprintProps = Blueprint.responseToBlueprintProps(blueprintResponse);\n return new Blueprint(blueprintProps, this.baseUrl, this.auth);\n });\n }\n\n async addStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await post(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${slug}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async removeStar(): Promise<number> {\n if (!this.auth) {\n throw new Error(\"Auth is required. Please login to star a blueprint.\");\n }\n\n try {\n await del(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`,\n null,\n this.auth\n );\n return await this.getStars();\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async getStars(): Promise<number> {\n try {\n const { stars } = await get<{ stars: number }>(\n `${this.baseUrl}/blueprint/${encodeURIComponent(this.props.slug!)}/stars`\n );\n this.stars = stars || 0;\n return stars || 0;\n } catch (err) {\n console.error(\"Failed calling POST on /blueprint/${id}/stars in addStar: \", err);\n throw err;\n }\n }\n\n async cancelCompilation(): Promise<void> {\n if (this.props.status !== Status.InProgress) {\n throw new Error(\"Can only cancel compilation of a blueprint that is in progress\");\n }\n try {\n await del<{ stars: number }>(\n `${this.baseUrl}/blueprint/cancel/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/cancel/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n\n async delete(): Promise<void> {\n // TODO: add is admin check here, currently only done in registry\n // if (this.props.status !== Status.Draft) {\n // throw new Error(\"Can only delete a blueprint that is in draft\");\n // }\n try {\n await del<{ success: boolean }>(\n `${this.baseUrl}/blueprint/${this.props.id}`,\n null,\n this.auth\n );\n } catch (err) {\n console.error(\"Failed calling DELETE on /blueprint/${id} in cancelCompilation: \", err);\n throw err;\n }\n }\n}\n\n// export {\n// BlueprintProps,\n// DecomposedRegex,\n// DecomposedRegexPart,\n// ExternalInput,\n// ZkFramework,\n// Status,\n// VerifierContract,\n// RevealHeaderFields,\n// } from \"./types/blueprint\";\n\nexport * from \"./types/blueprint\";\n","import { Auth } from \"./types\";\nimport { get } from \"./utils\";\n\n/**\n * @returns An array of slugs that the user starred\n */\nexport async function getStarredBlueprints(baseUrl: string, auth: Auth): Promise<string[]> {\n const { slugs } = await get<{ slugs: string[] }>(`${baseUrl}/blueprint/starred`, null, auth);\n return slugs;\n}\n","import { Blueprint, BlueprintProps, ListBlueprintsOptions } from \"./blueprint\";\nimport { Proof } from \"./proof\";\nimport { SdkOptions } from \"./types/sdk\";\nimport { getStarredBlueprints } from \"./user\";\n\n// Export Types\nexport * from \"./types/blueprint\";\nexport { Blueprint } from \"./blueprint\";\nexport * from \"./types/proof\";\nexport { Proof } from \"./proof\";\nexport * from \"./types/prover\";\nexport type { Auth } from \"./types/auth\";\nexport type { ParsedEmail } from \"./types/utils\";\n\n// Exports that don't need initialization or options\nexport { startJsonFileDownload } from \"./utils\";\nexport {\n testDecomposedRegex,\n parseEmail,\n generateProofInputs,\n testBlueprint,\n} from \"./relayerUtils\";\nexport { getLoginWithGithubUrl } from \"./auth\";\n\n// Exported sdk, functions that need initialization\nexport default (sdkOptions?: SdkOptions) => {\n const baseUrl = sdkOptions?.baseUrl || \"https://conductor.zk.email\";\n return {\n createBlueprint(props: BlueprintProps) {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use createBlueprint\");\n }\n const blueprint = new Blueprint(props, baseUrl, sdkOptions!.auth);\n return blueprint;\n },\n async getBlueprint(slug: string): Promise<Blueprint> {\n return Blueprint.getBlueprintBySlug(slug, baseUrl, sdkOptions?.auth);\n },\n async getBlueprintById(id: string): Promise<Blueprint> {\n return Blueprint.getBlueprintById(id, baseUrl, sdkOptions?.auth);\n },\n async listBlueprints(options?: ListBlueprintsOptions): Promise<Blueprint[]> {\n return Blueprint.listBlueprints(baseUrl, options, sdkOptions?.auth);\n },\n async getProof(id: string): Promise<Proof> {\n return Proof.getProofById(id, baseUrl);\n },\n async getStarredBlueprints(): Promise<string[]> {\n if (!sdkOptions && !sdkOptions!.auth) {\n throw new Error(\"You need to specify options.auth to use getStarredBlueprints\");\n }\n return getStarredBlueprints(baseUrl, sdkOptions!.auth!);\n },\n };\n};\n"]}
|