From 7fdba6dbbc3918d1d2a8fda13837d0868ae67f0f Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 4 Jul 2023 09:50:45 +0100 Subject: [PATCH 01/19] fix: fixed circuit for nullifier Root --- .../sparse-merkle-tree/checkproof.zok | 15 +-- .../zokrates/raw/BoilerplateGenerator.ts | 41 +++---- .../javascript/raw/boilerplate-generator.ts | 115 +++++++++--------- .../javascript/raw/toOrchestration.ts | 93 +++++++------- .../circuit/zokrates/toCircuit.ts | 9 +- .../circuitInternalFunctionCallVisitor.ts | 2 - 6 files changed, 140 insertions(+), 135 deletions(-) diff --git a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok index 73989f1a4..b740d3fc2 100644 --- a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok +++ b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok @@ -2,7 +2,7 @@ from "hashes/poseidon/poseidon.zok" import main as poseidon from "../../concatenate/order-left-right-1x1.zok" import main as orderLeftRight from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256 -def main(field[32] siblingPath, field value) -> (field): +def main(field[32] siblingPath, field value, field root, bool isAccessed) -> (field): field accValue = 0 // checking against zero element @@ -20,16 +20,12 @@ for u32 i in 0..32 do ]) endfor -return accValue +assert(root == accValue) +// Calculate the new Root -def checkUpdatedPath(field[32] siblingPath, field value) -> (field): - - -field accValue = value // checking against zero element -field[2] preimage = [0, 0] -bool[32] valueIndex = field_to_bool_256(value)[2..34] - +accValue = value // checking against zero element +preimage = [0, 0] for u32 i in 0..32 do u32 j = i // iterator for the siblingPath @@ -41,5 +37,6 @@ for u32 i in 0..32 do ]) endfor +accValue = if isAccessed == true root else accValue return accValue \ No newline at end of file diff --git a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts index 40f5d02ed..08c630fef 100644 --- a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts +++ b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts @@ -61,10 +61,8 @@ class BoilerplateGenerator { let para = [ `private field ${x}_oldCommitment_owner_secretKey`, `public field nullifierRoot`, - `public field newNullifierRoot`, `public field ${x}_oldCommitment_nullifier`, `private field[32] ${x}_nullifier_nonmembershipWitness_siblingPath`, - `private field[32] ${x}_nullifier_nonmembershipWitness_newsiblingPath`, ] if(isAccessed && !isNullified) @@ -104,24 +102,10 @@ class BoilerplateGenerator { ) // ${x}_oldCommitment_nullifier : non-existence check - assert(\\ - nullifierRoot == checkproof(\\ - ${x}_nullifier_nonmembershipWitness_siblingPath,\\ - ${x}_oldCommitment_nullifier\\ - )\ - ) - - assert(\\ - newNullifierRoot == checkUpdatedPath(\\ - ${x}_nullifier_nonmembershipWitness_newsiblingPath,\\ - ${x}_oldCommitment_nullifier\\ - )\ - ) - `, ]; - if(isAccessed && !isNullified) + (isAccessed && !isNullified) ? lines = [ ` // Create the Nullifier for ${x} and no need to nnullify it as its accessed only: @@ -134,14 +118,23 @@ class BoilerplateGenerator { // ${x}_oldCommitment_nullifier : non-existence check - assert(\\ - nullifierRoot == checkproof(\\ - ${x}_nullifier_nonmembershipWitness_siblingPath,\\ - ${x}_oldCommitment_nullifier\\ - )\ - ) + + nullifierRoot == checkproof(\\ + ${x}_nullifier_nonmembershipWitness_siblingPath,\\ + ${x}_oldCommitment_nullifier,\\ + nullifierRoot,\\ + true\\ + )\ // true for isAccessed `, - ]; + ] : lines.push( + `nullifierRoot == checkproof(\\ + ${x}_nullifier_nonmembershipWitness_siblingPath,\\ + ${x}_oldCommitment_nullifier,\\ + nullifierRoot,\\ + false\\ // false for isAccessed + )\ + ` + ); if (this.initialisationRequired && this.isWhole) { diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index 4bcf7f1ad..38295e2e3 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -270,12 +270,15 @@ class BoilerplateGenerator { ${stateName}_0_nullifier = generalise(${stateName}_0_nullifier.hex(32)); // truncate ${stateName}_1_nullifier = generalise(${stateName}_1_nullifier.hex(32)); // truncate // Non-membership witness for Nullifier + const ${stateName}_0_nullifier_NonMembership_witness = getnullifierMembershipWitness(${stateName}_0_nullifier); - const ${stateName}_1_nullifier_NonMembership_witness = getnullifierMembershipWitness(${stateName}_1_nullifier); - const ${stateName}_nullifierRoot = generalise(${stateName}_0_nullifier_NonMembership_witness.root); const ${stateName}_0_nullifier_path = generalise(${stateName}_0_nullifier_NonMembership_witness.path).all; + + await temporaryUpdateNullifier(${stateName}_0_nullifier); + const ${stateName}_1_nullifier_NonMembership_witness = getnullifierMembershipWitness(${stateName}_1_nullifier); const ${stateName}_1_nullifier_path = generalise(${stateName}_1_nullifier_NonMembership_witness.path).all; + await temporaryUpdateNullifier(${stateName}_1_nullifier); `]; case 'whole': if(accessedOnly) @@ -284,6 +287,7 @@ class BoilerplateGenerator { \n${stateName}_nullifier = generalise(${stateName}_nullifier.hex(32)); // truncate // Non-membership witness for Nullifier + const ${stateName}_nullifier_NonMembership_witness = getnullifierMembershipWitness(${stateName}_nullifier); const ${stateName}_nullifierRoot = generalise(${stateName}_nullifier_NonMembership_witness.root); @@ -294,10 +298,12 @@ class BoilerplateGenerator { \n${stateName}_nullifier = generalise(${stateName}_nullifier.hex(32)); // truncate // Non-membership witness for Nullifier + const ${stateName}_nullifier_NonMembership_witness = getnullifierMembershipWitness(${stateName}_nullifier); const ${stateName}_nullifierRoot = generalise(${stateName}_nullifier_NonMembership_witness.root); const ${stateName}_nullifier_path = generalise(${stateName}_nullifier_NonMembership_witness.path).all; + await temporaryUpdateNullifier(${stateName}_nullifier); `]; default: throw new TypeError(stateType); @@ -305,60 +311,60 @@ class BoilerplateGenerator { }, }; - temporaryUpdatedNullifier = { - postStatements({ stateName, accessedOnly, stateType }): string[] { - // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); - switch (stateType) { + // temporaryUpdatedNullifier = { + // postStatements({ stateName, accessedOnly, stateType }): string[] { + // // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); + // switch (stateType) { - case 'partitioned': - return [` + // case 'partitioned': + // return [` - await temporaryUpdateNullifier(${stateName}_0_nullifier); - await temporaryUpdateNullifier(${stateName}_1_nullifier); - `]; - case 'whole': - if(!accessedOnly) - return [` - await temporaryUpdateNullifier(${stateName}_nullifier); - `]; - return [` `]; - default: - throw new TypeError(stateType); - } - }, - - }; - - calculateUpdateNullifierPath = { - postStatements({ stateName, accessedOnly, stateType }): string[] { - // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); - switch (stateType) { + // await temporaryUpdateNullifier(${stateName}_0_nullifier); + // await temporaryUpdateNullifier(${stateName}_1_nullifier); + // `]; + // case 'whole': + // if(!accessedOnly) + // return [` + // await temporaryUpdateNullifier(${stateName}_nullifier); + // `]; + // return [` `]; + // default: + // throw new TypeError(stateType); + // } + // }, + + // }; + + // calculateUpdateNullifierPath = { + // postStatements({ stateName, accessedOnly, stateType }): string[] { + // // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); + // switch (stateType) { - case 'partitioned': - return [` - // Get the new updated nullifier Paths - const ${stateName}_0_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_0_nullifier); - const ${stateName}_1_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_1_nullifier); + // case 'partitioned': + // return [` + // // Get the new updated nullifier Paths + // const ${stateName}_0_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_0_nullifier); + // const ${stateName}_1_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_1_nullifier); - const ${stateName}_newNullifierRoot = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.root); - const ${stateName}_0_nullifier_updatedpath = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.path).all; - const ${stateName}_1_nullifier_updatedpath = generalise(${stateName}_1_updated_nullifier_NonMembership_witness.path).all; - `]; - case 'whole': - if(!accessedOnly) - return [` - // Get the new updated nullifier Paths - const ${stateName}_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_nullifier); - const ${stateName}_nullifier_updatedpath = generalise(${stateName}_updated_nullifier_NonMembership_witness.path).all; - const ${stateName}_newNullifierRoot = generalise(${stateName}_updated_nullifier_NonMembership_witness.root); - `]; - return [` `]; - default: - throw new TypeError(stateType); - } - }, - }; + // const ${stateName}_newNullifierRoot = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.root); + // const ${stateName}_0_nullifier_updatedpath = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.path).all; + // const ${stateName}_1_nullifier_updatedpath = generalise(${stateName}_1_updated_nullifier_NonMembership_witness.path).all; + // `]; + // case 'whole': + // if(!accessedOnly) + // return [` + // // Get the new updated nullifier Paths + // const ${stateName}_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_nullifier); + // const ${stateName}_nullifier_updatedpath = generalise(${stateName}_updated_nullifier_NonMembership_witness.path).all; + // const ${stateName}_newNullifierRoot = generalise(${stateName}_updated_nullifier_NonMembership_witness.root); + // `]; + // return [` `]; + // default: + // throw new TypeError(stateType); + // } + // }, + // }; calculateCommitment = { @@ -454,13 +460,10 @@ class BoilerplateGenerator { \tsecretKey.integer, \tsecretKey.integer, ${nullifierRootRequired ? `\t${stateName}_nullifierRoot.integer,` : ``} - ${nullifierRootRequired ? `\t${stateName}_newNullifierRoot.integer,` : ``} \t${stateName}_0_nullifier.integer, \t${stateName}_0_nullifier_path.integer, - \t${stateName}_0_nullifier_updatedpath.integer, \t${stateName}_1_nullifier.integer, \t${stateName}_1_nullifier_path.integer, - \t${stateName}_1_nullifier_updatedpath.integer, ${prev(0)}, \t${stateName}_0_prevSalt.integer, ${prev(1)}, @@ -489,10 +492,8 @@ class BoilerplateGenerator { ${parameters.join('\n')}${stateVarIds.join('\n')} \tsecretKey.integer, ${nullifierRootRequired ? `\t${stateName}_nullifierRoot.integer,` : ``} - ${nullifierRootRequired ? `\t${stateName}_newNullifierRoot.integer,` : ``} \t${stateName}_nullifier.integer, \t${stateName}_nullifier_path.integer, - \t${stateName}_nullifier_updatedpath.integer, ${prev}, \t${stateName}_prevSalt.integer, ${initialisationRequired ? `\t${stateName}_commitmentExists ? 0 : 1,` : ``} @@ -517,10 +518,8 @@ class BoilerplateGenerator { ${parameters.join('\n')}${stateVarIds.join('\n')} \t${stateName}_commitmentExists ? secretKey.integer: generalise(0).integer, ${nullifierRootRequired ? `\t${stateName}_nullifierRoot.integer,` : ``} - ${nullifierRootRequired ? `\t${stateName}_newNullifierRoot.integer,` : ``} \t${stateName}_nullifier.integer, \t${stateName}_nullifier_path.integer, - \t${stateName}_nullifier_updatedpath.integer, ${prev}, \t${stateName}_prevSalt.integer, ${initialisationRequired ? `\t${stateName}_commitmentExists ? 0 : 1,` : ``} diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index c85f3cc20..bf2c53e15 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -78,7 +78,7 @@ export const sendTransactionBoilerplate = (node: any) => { case true: // decrement output[2].push(`${privateStateName}_root.integer`); - output[0].push(`${privateStateName}_nullifierRoot.integer`, `${privateStateName}_newNullifierRoot.integer`); + output[0].push(`${privateStateName}_nullifierRoot.integer`, `newNullifierRoot.integer`); output[1].push( `${privateStateName}_0_nullifier.integer, ${privateStateName}_1_nullifier.integer`, ); @@ -102,7 +102,7 @@ export const sendTransactionBoilerplate = (node: any) => { output[2].push(`${privateStateName}_root.integer`); if (!stateNode.accessedOnly && !stateNode.reinitialisedOnly) { output[1].push(`${privateStateName}_nullifier.integer`); - output[0].push(`${privateStateName}_nullifierRoot.integer`,`${privateStateName}_newNullifierRoot.integer`); + output[0].push(`${privateStateName}_nullifierRoot.integer`,`newNullifierRoot.integer`); } if (!stateNode.accessedOnly && !stateNode.burnedOnly) output[3].push(`${privateStateName}_newCommitment.integer`); @@ -120,6 +120,7 @@ export const sendTransactionBoilerplate = (node: any) => { export const generateProofBoilerplate = (node: any) => { const output: (string[] | string)[] = []; const enc: any[][] = []; + const latestNullifierRoot: any[] = []; const cipherTextLength: number[] = []; let containsRoot = false; let containsNullifierRoot = false; @@ -135,6 +136,13 @@ export const generateProofBoilerplate = (node: any) => { enc[1] ??= []; enc[1].push(`const ${stateName}_encKey = res.inputs.slice(START_SLICE END_SLICE).map(e => generalise(e).integer);`); } + // We read the latestNullifierRoot + + if(stateNode.nullifierRequired) { + latestNullifierRoot.push(`const newNullifierRoot = res.input.slice(-1).map(e => generalised(e).integer)`) + + } + const parameters: string[] = []; // we include the state variable key (mapping key) if its not a param (we include params separately) const msgSenderParamAndMappingKey = stateNode.isMapping && (node.parameters.includes('msgSender') || output.join().includes('_msg_stateVarId_key.integer')) && stateNode.stateVarId[1] === 'msg'; @@ -269,7 +277,7 @@ export const generateProofBoilerplate = (node: any) => { // extract the nullifier Root output.push(`\n].flat(Infinity);`); - return [output, [enc]]; + return [output, [enc], latestNullifierRoot]; }; export const preimageBoilerPlate = (node: any) => { @@ -423,6 +431,7 @@ export const preimageBoilerPlate = (node: any) => { export const OrchestrationCodeBoilerPlate: any = (node: any) => { const lines: any[] = []; const params:any[] = []; + const latestNullifierRoot:any[] = []; const states: string[] = []; const rtnparams: string[] = []; let stateName: string; @@ -692,43 +701,43 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { } } - for ([stateName, stateNode] of Object.entries(node.privateStates)) { - if (stateNode.isPartitioned) { - lines.push( - Orchestrationbp.temporaryUpdatedNullifier.postStatements({ - stateName, - accessedOnly: stateNode.accessedOnly, - stateType: 'partitioned', - })); - - } else { - lines.push( - Orchestrationbp.temporaryUpdatedNullifier.postStatements({ - stateName, - accessedOnly: stateNode.accessedOnly, - stateType: 'whole', - })); - } - } - - for ([stateName, stateNode] of Object.entries(node.privateStates)) { - if (stateNode.isPartitioned) { - lines.push( - Orchestrationbp.calculateUpdateNullifierPath.postStatements({ - stateName, - accessedOnly: stateNode.accessedOnly, - stateType: 'partitioned', - })); - - } else { - lines.push( - Orchestrationbp.calculateUpdateNullifierPath.postStatements({ - stateName, - accessedOnly: stateNode.accessedOnly, - stateType: 'whole', - })); - } - } + // for ([stateName, stateNode] of Object.entries(node.privateStates)) { + // if (stateNode.isPartitioned) { + // lines.push( + // Orchestrationbp.temporaryUpdatedNullifier.postStatements({ + // stateName, + // accessedOnly: stateNode.accessedOnly, + // stateType: 'partitioned', + // })); + + // } else { + // lines.push( + // Orchestrationbp.temporaryUpdatedNullifier.postStatements({ + // stateName, + // accessedOnly: stateNode.accessedOnly, + // stateType: 'whole', + // })); + // } + // } + + // for ([stateName, stateNode] of Object.entries(node.privateStates)) { + // if (stateNode.isPartitioned) { + // lines.push( + // Orchestrationbp.calculateUpdateNullifierPath.postStatements({ + // stateName, + // accessedOnly: stateNode.accessedOnly, + // stateType: 'partitioned', + // })); + + // } else { + // lines.push( + // Orchestrationbp.calculateUpdateNullifierPath.postStatements({ + // stateName, + // accessedOnly: stateNode.accessedOnly, + // stateType: 'whole', + // })); + // } + // } return { statements: [`\n// Calculate nullifier(s): \n`, ...lines], @@ -778,7 +787,8 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { }; case 'GenerateProof': - [ lines[0], params[0] ] = generateProofBoilerplate(node); + [ lines[0], params[0], latestNullifierRoot[0] ] = generateProofBoilerplate(node); + return { statements: [ `\n\n// Call Zokrates to generate the proof: @@ -788,6 +798,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { `\nconst proof = generalise(Object.values(res.proof).flat(Infinity)) .map(coeff => coeff.integer) .flat(Infinity);`, + `${latestNullifierRoot[0]}`, `${params[0].flat(Infinity).join('\n')}` ], }; diff --git a/src/codeGenerators/circuit/zokrates/toCircuit.ts b/src/codeGenerators/circuit/zokrates/toCircuit.ts index d34859b78..64c36d508 100644 --- a/src/codeGenerators/circuit/zokrates/toCircuit.ts +++ b/src/codeGenerators/circuit/zokrates/toCircuit.ts @@ -95,11 +95,18 @@ function codeGenerator(node: any) { returnType.push(node.typeName.name); }); + if(codeGenerator(node.parameters).includes('nullifierRoot')){ + returnStatement.push('nullifierRoot'); + returnType.push('field') ; + } + if(returnStatement.length === 0){ returnStatement.push('true'); returnType.push('bool') ; } + + return `${functionSignature}(${returnType}): ${body} @@ -189,7 +196,7 @@ function codeGenerator(node: any) { return `${returnPara} ${node.name}(${(node.CircuitArguments).join(',\\\n \t')})` } else if(node.CircuitArguments.length) - return `assert(${node.name}(${(node.CircuitArguments).join(',\\\n \t')})) ` ; + return ` nullifierRoot = (${(node.CircuitArguments).join(',\\\n \t')}) ` ; else return ``; } diff --git a/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts b/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts index 0cf0ef080..8d8fb9d24 100644 --- a/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts +++ b/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts @@ -83,10 +83,8 @@ const internalCallVisitor = { case 'nullification' : { internalFncParameters.push(`${node.name}_oldCommitment_owner_secretKey`) ; internalFncParameters.push(`nullifierRoot`); - internalFncParameters.push(`newNullifierRoot`); internalFncParameters.push(`${node.name}_oldCommitment_nullifier`); internalFncParameters.push(`${node.name}_nullifier_nonmembershipWitness_siblingPath`); - internalFncParameters.push(`${node.name}_nullifier_nonmembershipWitness_newsiblingPath`); break; }; case 'oldCommitmentPreimage' : { From 7b573888a7b42ef8e40a33576a495c0d4d44a632 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 4 Jul 2023 15:34:19 +0100 Subject: [PATCH 02/19] chore: added a fix for nullifiers --- circuits/common/joinCommitments.zok | 41 ++++++------- .../sparse-merkle-tree/checkproof.zok | 2 +- .../zokrates/raw/BoilerplateGenerator.ts | 17 +++--- src/boilerplate/common/commitment-storage.mjs | 20 +------ src/boilerplate/common/generic-test.mjs | 2 +- .../nodes/FunctionBoilerplateGenerator.ts | 3 +- .../raw/ContractBoilerplateGenerator.ts | 20 +++---- .../javascript/raw/boilerplate-generator.ts | 57 +------------------ .../javascript/raw/toOrchestration.ts | 45 ++------------- .../circuit/zokrates/toCircuit.ts | 3 +- 10 files changed, 49 insertions(+), 161 deletions(-) diff --git a/circuits/common/joinCommitments.zok b/circuits/common/joinCommitments.zok index 555079f73..1fd1afb58 100644 --- a/circuits/common/joinCommitments.zok +++ b/circuits/common/joinCommitments.zok @@ -10,7 +10,6 @@ from "./common/hashes/poseidon/poseidon.zok" import main as poseidon from "./common/casts/u32_array_to_field.zok" import main as u32_array_to_field from "utils/pack/bool/pack256.zok" import main as bool_256_to_field from "./common/merkle-tree/mimc/altbn254/verify-membership/height32.zok" import main as checkRoot -from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import checkUpdatedPath as checkUpdatedPath from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as checkproof def main(\ @@ -20,13 +19,10 @@ def main(\ private field oldCommitment_0_owner_secretKey_field,\ private field oldCommitment_1_owner_secretKey_field,\ public field nullifierRoot,\ - public field newNullifierRoot,\ public field oldCommitment_0_nullifier,\ public field[32] oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ - private field[32] oldCommitment_0_nullifier_nonmembershipWitness_newsiblingPath,\ public field oldCommitment_1_nullifier,\ private field[32] oldCommitment_1_nullifier_nonmembershipWitness_siblingPath,\ - private field[32] oldCommitment_1_nullifier_nonmembershipWitness_newsiblingPath,\ private field oldCommitment_0_value,\ private field oldCommitment_0_salt_field,\ private field oldCommitment_1_value,\ @@ -39,7 +35,7 @@ def main(\ private field newCommitment_owner_publicKey_field,\ private field newCommitment_salt_field,\ public field newCommitment_commitment\ -) -> (bool) : +) -> (field) : // check if state is mapping or not @@ -57,6 +53,8 @@ def main(\ field oldCommitment_1 = oldCommitment_1_value + bool isAccessed = false + // oldCommitment_0 - PoKoSK: // The correctness of this secret key will be constrained within the oldCommitment existence check. @@ -94,18 +92,15 @@ def main(\ field_to_bool_256(oldCommitment_0_nullifier)[8..256] == field_to_bool_256(oldCommitment_0_nullifier_check_field)[8..256]\ ) - assert(\ - nullifierRoot == checkproof(\ - oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ - oldCommitment_0_nullifier\ - ) ) - - assert( newNullifierRoot == checkUpdatedPath(oldCommitment_0_nullifier_nonmembershipWitness_newsiblingPath,\ - oldCommitment_0_nullifier) ) - - + nullifierRoot = checkproof(\ + oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ + oldCommitment_0_nullifier,\ + nullifierRoot,\ + isAccessed\ + ) + // Nullify oldCommitment_1: field oldCommitment_1_nullifier_check_field = poseidon([\ @@ -118,15 +113,15 @@ def main(\ field_to_bool_256(oldCommitment_1_nullifier)[8..256] == field_to_bool_256(oldCommitment_1_nullifier_check_field)[8..256]\ ) - assert(\ - nullifierRoot == checkproof(\ + + nullifierRoot = checkproof(\ oldCommitment_1_nullifier_nonmembershipWitness_siblingPath,\ - oldCommitment_1_nullifier\ - ) ) + oldCommitment_1_nullifier,\ + nullifierRoot,\ + isAccessed\ + ) + - assert( newNullifierRoot == checkUpdatedPath(oldCommitment_1_nullifier_nonmembershipWitness_newsiblingPath,\ - oldCommitment_1_nullifier) ) - // oldCommitment_0_commitment: preimage check field oldCommitment_0_commitment_field = poseidon([\ @@ -190,4 +185,4 @@ def main(\ field_to_bool_256(newCommitment_commitment)[8..256] == field_to_bool_256(newCommitment_commitment_check_field)[8..256]\ ) - return true + return nullifierRoot diff --git a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok index b740d3fc2..c34f8988c 100644 --- a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok +++ b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok @@ -37,6 +37,6 @@ for u32 i in 0..32 do ]) endfor -accValue = if isAccessed == true root else accValue +accValue = if isAccessed == true then root else accValue fi return accValue \ No newline at end of file diff --git a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts index 08c630fef..62a569f14 100644 --- a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts +++ b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts @@ -53,7 +53,6 @@ class BoilerplateGenerator { `from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256`, `from "./common/hashes/poseidon/poseidon.zok" import main as poseidon`, `from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as checkproof`, - `from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import checkUpdatedPath as checkUpdatedPath`, ]; }, @@ -117,21 +116,25 @@ class BoilerplateGenerator { ]) // ${x}_oldCommitment_nullifier : non-existence check - + + isAccessed = true \\ - nullifierRoot == checkproof(\\ + nullifierRoot = checkproof(\\ ${x}_nullifier_nonmembershipWitness_siblingPath,\\ ${x}_oldCommitment_nullifier,\\ nullifierRoot,\\ - true\\ - )\ // true for isAccessed + isAccessed\\ + )\ `, ] : lines.push( - `nullifierRoot == checkproof(\\ + ` + isAccessed = false \\ + + nullifierRoot = checkproof(\\ ${x}_nullifier_nonmembershipWitness_siblingPath,\\ ${x}_oldCommitment_nullifier,\\ nullifierRoot,\\ - false\\ // false for isAccessed + isAccessed\\ )\ ` ); diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 469e3630c..31a52026d 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -519,8 +519,8 @@ export function getnullifierMembershipWitness(nullifier) { const padBinArr = Array(254 - binArr.length) .fill("0") .concat(...binArr).slice(0, TRUNC_LENGTH); - const membershipPath = _getnullifierMembershipWitness(padBinArr, nullifier, smt_tree, []); - const root = getHash(smt_tree); + const membershipPath = _getnullifierMembershipWitness(padBinArr, nullifier, temp_smt_tree, []); + const root = getHash(temp_smt_tree); const witness = {path : membershipPath.path, root: root} return witness; @@ -532,20 +532,4 @@ export async function temporaryUpdateNullifier(nullifier){ } -export function getupdatedNullifierPaths(nullifier){ - const binArr = toBinArray(generalise(nullifier)); - const padBinArr = Array(254 - binArr.length) - .fill("0") - .concat(...binArr) - .slice(0, TRUNC_LENGTH); - const membershipPath = _getnullifierMembershipWitness( - padBinArr, - nullifier, - temp_smt_tree, - [] - ); - const root = getHash(temp_smt_tree); - const witness = { path: membershipPath.path, root: root }; - return witness; -} diff --git a/src/boilerplate/common/generic-test.mjs b/src/boilerplate/common/generic-test.mjs index 57bd6875c..c5bc88552 100644 --- a/src/boilerplate/common/generic-test.mjs +++ b/src/boilerplate/common/generic-test.mjs @@ -46,7 +46,7 @@ describe('FUNCTION_NAME', async function () { console.log(`Merkle tree event returnValues:`); console.log(tx.returnValues[0]); } - if (encEvent[0].event) { + if (encEvent && encEvent[0]?.event) { encryption.msgs = encEvent[0].returnValues[0]; encryption.key = encEvent[0].returnValues[1]; console.log("EncryptedMsgs:"); diff --git a/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts b/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts index 0d6dbae8d..db32868cf 100644 --- a/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts +++ b/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts @@ -119,8 +119,7 @@ class FunctionBoilerplateGenerator { internalFunctionEncryptionRequired = true }) - - if(path.node.returnParameters.parameters.length === 0 && !indicators.encryptionRequired && !internalFunctionEncryptionRequired) { + if(path.node.returnParameters.parameters.length === 0 && !indicators.encryptionRequired && !internalFunctionEncryptionRequired && !indicators.nullifiersRequired) { publicParams?.push({ name: 1, type: 'uint256', dummy: true }); } return { diff --git a/src/boilerplate/contract/solidity/raw/ContractBoilerplateGenerator.ts b/src/boilerplate/contract/solidity/raw/ContractBoilerplateGenerator.ts index 5ba86aea0..2a6623794 100644 --- a/src/boilerplate/contract/solidity/raw/ContractBoilerplateGenerator.ts +++ b/src/boilerplate/contract/solidity/raw/ContractBoilerplateGenerator.ts @@ -127,8 +127,6 @@ class ContractBoilerplateGenerator { case 'nullifierRoot': verifyInput.push( ` inputs[k++] = _inputs.nullifierRoot;`); - verifyInput.push( ` - inputs[k++] = _inputs.latestNullifierRoot;`); break; case 'nullifier': verifyInput.push( ` @@ -221,13 +219,15 @@ class ContractBoilerplateGenerator { }; _inputs.map(i => verifyInputsMap(type, i, counter)); - - - + } - - if(_params && !(Object.keys(_params).includes('returnParameters'))) verifyInput.push(` + + if(_params && (Object.values(_params)[0].includes('nullifierRoot'))) verifyInput.push(` + inputs[k++] = _inputs.latestNullifierRoot;`) + + if(_params && !(Object.values(_params)[0].includes('nullifierRoot')) && !(Object.keys(_params).includes('returnParameters'))) verifyInput.push(` inputs[k++] = 1;`) + verifyInputs.push(` if (functionId == uint(FunctionNames.${name})) { @@ -270,9 +270,6 @@ class ContractBoilerplateGenerator { Inputs memory inputs; - inputs.customInputs = new uint[](1); - inputs.customInputs[0] = 1; - inputs.nullifierRoot = nullifierRoot; inputs.latestNullifierRoot = latestNullifierRoot; @@ -295,12 +292,11 @@ class ContractBoilerplateGenerator { uint k = 0; inputs[k++] = _inputs.nullifierRoot; - inputs[k++] = _inputs.latestNullifierRoot; inputs[k++] = newNullifiers[0]; inputs[k++] = newNullifiers[1]; inputs[k++] = _inputs.commitmentRoot; inputs[k++] = newCommitments[0]; - inputs[k++] = 1; + inputs[k++] = _inputs.latestNullifierRoot; }`) diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index 38295e2e3..a3cbc6261 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -311,60 +311,7 @@ class BoilerplateGenerator { }, }; - // temporaryUpdatedNullifier = { - // postStatements({ stateName, accessedOnly, stateType }): string[] { - // // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); - // switch (stateType) { - - // case 'partitioned': - // return [` - - - // await temporaryUpdateNullifier(${stateName}_0_nullifier); - // await temporaryUpdateNullifier(${stateName}_1_nullifier); - // `]; - // case 'whole': - // if(!accessedOnly) - // return [` - // await temporaryUpdateNullifier(${stateName}_nullifier); - // `]; - // return [` `]; - // default: - // throw new TypeError(stateType); - // } - // }, - - // }; - - // calculateUpdateNullifierPath = { - // postStatements({ stateName, accessedOnly, stateType }): string[] { - // // if (!isWhole && !newCommitmentValue) throw new Error('PATH'); - // switch (stateType) { - - // case 'partitioned': - // return [` - // // Get the new updated nullifier Paths - // const ${stateName}_0_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_0_nullifier); - // const ${stateName}_1_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_1_nullifier); - - // const ${stateName}_newNullifierRoot = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.root); - // const ${stateName}_0_nullifier_updatedpath = generalise(${stateName}_0_updated_nullifier_NonMembership_witness.path).all; - // const ${stateName}_1_nullifier_updatedpath = generalise(${stateName}_1_updated_nullifier_NonMembership_witness.path).all; - // `]; - // case 'whole': - // if(!accessedOnly) - // return [` - // // Get the new updated nullifier Paths - // const ${stateName}_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths(${stateName}_nullifier); - // const ${stateName}_nullifier_updatedpath = generalise(${stateName}_updated_nullifier_NonMembership_witness.path).all; - // const ${stateName}_newNullifierRoot = generalise(${stateName}_updated_nullifier_NonMembership_witness.root); - // `]; - // return [` `]; - // default: - // throw new TypeError(stateType); - // } - // }, - // }; + calculateCommitment = { @@ -411,7 +358,7 @@ class BoilerplateGenerator { `\nimport fs from 'fs'; \n`, `\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`, - `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,getupdatedNullifierPaths,temporaryUpdateNullifier,updateNullifierTree } from './common/commitment-storage.mjs';`, + `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,updateNullifierTree} from './common/commitment-storage.mjs';`, `\nimport { generateProof } from './common/zokrates.mjs';`, `\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`, `\nimport Web3 from './common/web3.mjs';`, diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index bf2c53e15..43980a873 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -78,7 +78,7 @@ export const sendTransactionBoilerplate = (node: any) => { case true: // decrement output[2].push(`${privateStateName}_root.integer`); - output[0].push(`${privateStateName}_nullifierRoot.integer`, `newNullifierRoot.integer`); + output[0].push(`${privateStateName}_nullifierRoot.integer`, `newNullifierRoot`); output[1].push( `${privateStateName}_0_nullifier.integer, ${privateStateName}_1_nullifier.integer`, ); @@ -102,7 +102,7 @@ export const sendTransactionBoilerplate = (node: any) => { output[2].push(`${privateStateName}_root.integer`); if (!stateNode.accessedOnly && !stateNode.reinitialisedOnly) { output[1].push(`${privateStateName}_nullifier.integer`); - output[0].push(`${privateStateName}_nullifierRoot.integer`,`newNullifierRoot.integer`); + output[0].push(`${privateStateName}_nullifierRoot.integer`,`newNullifierRoot`); } if (!stateNode.accessedOnly && !stateNode.burnedOnly) output[3].push(`${privateStateName}_newCommitment.integer`); @@ -138,8 +138,8 @@ export const generateProofBoilerplate = (node: any) => { } // We read the latestNullifierRoot - if(stateNode.nullifierRequired) { - latestNullifierRoot.push(`const newNullifierRoot = res.input.slice(-1).map(e => generalised(e).integer)`) + if(stateNode.nullifierRequired && latestNullifierRoot.length === 0) { + latestNullifierRoot.push(`const newNullifierRoot = res.inputs.slice(-1).map(e => generalise(e).integer)[0];`) } @@ -701,43 +701,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { } } - // for ([stateName, stateNode] of Object.entries(node.privateStates)) { - // if (stateNode.isPartitioned) { - // lines.push( - // Orchestrationbp.temporaryUpdatedNullifier.postStatements({ - // stateName, - // accessedOnly: stateNode.accessedOnly, - // stateType: 'partitioned', - // })); - - // } else { - // lines.push( - // Orchestrationbp.temporaryUpdatedNullifier.postStatements({ - // stateName, - // accessedOnly: stateNode.accessedOnly, - // stateType: 'whole', - // })); - // } - // } - - // for ([stateName, stateNode] of Object.entries(node.privateStates)) { - // if (stateNode.isPartitioned) { - // lines.push( - // Orchestrationbp.calculateUpdateNullifierPath.postStatements({ - // stateName, - // accessedOnly: stateNode.accessedOnly, - // stateType: 'partitioned', - // })); - - // } else { - // lines.push( - // Orchestrationbp.calculateUpdateNullifierPath.postStatements({ - // stateName, - // accessedOnly: stateNode.accessedOnly, - // stateType: 'whole', - // })); - // } - // } return { statements: [`\n// Calculate nullifier(s): \n`, ...lines], diff --git a/src/codeGenerators/circuit/zokrates/toCircuit.ts b/src/codeGenerators/circuit/zokrates/toCircuit.ts index 64c36d508..88c17c8b0 100644 --- a/src/codeGenerators/circuit/zokrates/toCircuit.ts +++ b/src/codeGenerators/circuit/zokrates/toCircuit.ts @@ -98,6 +98,7 @@ function codeGenerator(node: any) { if(codeGenerator(node.parameters).includes('nullifierRoot')){ returnStatement.push('nullifierRoot'); returnType.push('field') ; + body = ('bool isAccessed = false \n').concat(body) } if(returnStatement.length === 0){ @@ -196,7 +197,7 @@ function codeGenerator(node: any) { return `${returnPara} ${node.name}(${(node.CircuitArguments).join(',\\\n \t')})` } else if(node.CircuitArguments.length) - return ` nullifierRoot = (${(node.CircuitArguments).join(',\\\n \t')}) ` ; + return ` nullifierRoot = ${node.name} (${(node.CircuitArguments).join(',\\\n \t')}) ` ; else return ``; } From 6b7e8fd9f3dac4c5094cd8d8f787b874264d2812 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 4 Jul 2023 17:01:16 +0100 Subject: [PATCH 03/19] chore: internal function call fix --- src/codeGenerators/circuit/zokrates/toCircuit.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/codeGenerators/circuit/zokrates/toCircuit.ts b/src/codeGenerators/circuit/zokrates/toCircuit.ts index 88c17c8b0..19b1d80bc 100644 --- a/src/codeGenerators/circuit/zokrates/toCircuit.ts +++ b/src/codeGenerators/circuit/zokrates/toCircuit.ts @@ -196,8 +196,10 @@ function codeGenerator(node: any) { }) return `${returnPara} ${node.name}(${(node.CircuitArguments).join(',\\\n \t')})` } - else if(node.CircuitArguments.length) + else if(node.CircuitArguments.length && node.CircuitArguments.includes('nullifierRoot')) return ` nullifierRoot = ${node.name} (${(node.CircuitArguments).join(',\\\n \t')}) ` ; + else if(node.CircuitArguments.length && !node.CircuitArguments.includes('nullifierRoot')) + return ` assert( ${node.name} (${(node.CircuitArguments).join(',\\\n \t')}) )` ; else return ``; } From a3b96102c0e05599685e58813ece37e98978c0d6 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 11 Jul 2023 10:02:52 +0100 Subject: [PATCH 04/19] chore: merged master --- .../solidity/nodes/FunctionBoilerplateGenerator.ts | 9 +++------ .../solidity/raw/FunctionBoilerplateGenerator.ts | 6 ++++-- .../visitors/circuitInternalFunctionCallVisitor.ts | 1 + 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts b/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts index b5c01e606..7c2e61c9d 100644 --- a/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts +++ b/src/boilerplate/contract/solidity/nodes/FunctionBoilerplateGenerator.ts @@ -71,7 +71,7 @@ class FunctionBoilerplateGenerator { }, getIndicators() { - const { indicators, msgSigRequired } = this.scope; + const { indicators } = this.scope; const isConstructor = this.scope.path.node.kind === 'constructor' ? true : false; const { nullifiersRequired, oldCommitmentAccessRequired, msgSenderParam, msgValueParam, containsAccessedOnlyState, encryptionRequired } = indicators; @@ -119,13 +119,10 @@ class FunctionBoilerplateGenerator { if(node.expression?.nodeType === 'InternalFunctionCall'){ if(node.expression.parameters.includes('cipherText') ) internalFunctionEncryptionRequired = true - - } - + } }) - - if(path.node.returnParameters.parameters.length === 0 && !indicators.encryptionRequired && !internalFunctionEncryptionRequired) { + if(path.node.returnParameters.parameters.length === 0 && !indicators.encryptionRequired && !internalFunctionEncryptionRequired ) { publicParams?.push({ name: 1, type: 'uint256', dummy: true , inCircuit: true }); } diff --git a/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts b/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts index 11fe1c50d..41db59dcf 100644 --- a/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts +++ b/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts @@ -35,7 +35,6 @@ class FunctionBoilerplateGenerator { nullifiersRequired: newNullifiers, oldCommitmentAccessRequired: commitmentRoot, newCommitmentsRequired: newCommitments, - containsAccessedOnlyState: checkNullifiers, encryptionRequired, isConstructor }): string[] { @@ -62,7 +61,6 @@ class FunctionBoilerplateGenerator { encryptionRequired }): string[] { // prettier-ignore - let parameter = [ ...(customInputs ? customInputs.filter(input => !input.dummy && input.isParam).map(input => input.structName ? `(${input.properties.map(p => p.type)})` : input.type) : []), ...(newNullifiers ? [`uint256`] : []), @@ -84,6 +82,10 @@ class FunctionBoilerplateGenerator { let msgSigCheck = ([...(isConstructor ? [] : [`bytes4 sig = bytes4(keccak256("${functionName}(${parameter})")) ; \n \t \t \t if (sig == msg.sig)`])]); customInputs = customInputs?.filter(p => p.inCircuit); + + customInputs?.forEach((input, i) => { + if(input.name === 1 && input.type === 'uint256' && newNullifiers) customInputs.splice(i,1); + }); return [ ` diff --git a/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts b/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts index b9c88d1e2..367fe561a 100644 --- a/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts +++ b/src/transformers/visitors/circuitInternalFunctionCallVisitor.ts @@ -57,6 +57,7 @@ const internalCallVisitor = { } }) + // Collect the internal call ParameterList let internalFncParameters: string[] = []; state.newParameterList.forEach(node => { From 66c1502d1bac1b71707ac32146efc4a86e930d2d Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 08:43:04 +0100 Subject: [PATCH 05/19] chore: added code for reset temp updates --- circuits/common/joinCommitments.zok | 2 +- src/boilerplate/common/commitment-storage.mjs | 42 ++++++------------- .../javascript/raw/boilerplate-generator.ts | 2 +- .../javascript/raw/toOrchestration.ts | 12 +++++- 4 files changed, 25 insertions(+), 33 deletions(-) diff --git a/circuits/common/joinCommitments.zok b/circuits/common/joinCommitments.zok index 1fd1afb58..104f3a5b3 100644 --- a/circuits/common/joinCommitments.zok +++ b/circuits/common/joinCommitments.zok @@ -20,7 +20,7 @@ def main(\ private field oldCommitment_1_owner_secretKey_field,\ public field nullifierRoot,\ public field oldCommitment_0_nullifier,\ - public field[32] oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ + private field[32] oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ public field oldCommitment_1_nullifier,\ private field[32] oldCommitment_1_nullifier_nonmembershipWitness_siblingPath,\ private field oldCommitment_0_value,\ diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 31a52026d..6feedad42 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -173,7 +173,7 @@ export async function markNullified(commitmentHash, secretKey = null) { }, }; // updating the original tree - smt_tree = temp_smt_tree; + await updateNullifierTree(nullifier); return db.collection(COMMITMENTS_COLLECTION).updateOne(query, update); } @@ -328,36 +328,19 @@ export async function joinCommitments( const oldCommitment_0_nullifier_NonMembership_witness = getnullifierMembershipWitness( oldCommitment_0_nullifier ); - const oldCommitment_1_nullifier_NonMembership_witness = getnullifierMembershipWitness( - oldCommitment_1_nullifier - ); - const oldCommitment_nullifierRoot = generalise(oldCommitment_0_nullifier_NonMembership_witness.root); const oldCommitment_0_nullifier_path = generalise( oldCommitment_0_nullifier_NonMembership_witness.path ).all; - const oldCommitment_1_nullifier_path = generalise( - oldCommitment_1_nullifier_NonMembership_witness.path - ).all; - - await temporaryUpdateNullifier(a_0_nullifier); - await temporaryUpdateNullifier(a_1_nullifier); - - const oldCommitment_0_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths( - oldCommitment_0_nullifier - ); - const oldCommitment_1_updated_nullifier_NonMembership_witness = getupdatedNullifierPaths( + await temporaryUpdateNullifier(oldCommitment_0_nullifier); + const oldCommitment_1_nullifier_NonMembership_witness = getnullifierMembershipWitness( oldCommitment_1_nullifier ); - - const oldCommitment_0_nullifier_newpath = generalise( - oldCommitment_0_updated_nullifier_NonMembership_witness.path - ).all; - const oldCommitment_1_nullifier_newpath = generalise( - oldCommitment_1_updated_nullifier_NonMembership_witness.path + const oldCommitment_1_nullifier_path = generalise( + oldCommitment_1_nullifier_NonMembership_witness.path ).all; - const oldCommitment_newNullifierRoot = generalise(oldCommitment_0_updated_nullifier_NonMembership_witness.root); + await temporaryUpdateNullifier(oldCommitment_1_nullifier); // Calculate commitment(s): const newCommitment_newSalt = generalise(utils.randomHex(31)); @@ -395,13 +378,10 @@ export async function joinCommitments( secretKey.integer, oldCommitment_nullifierRoot.integer, - oldCommitment_newNullifierRoot.integer, oldCommitment_0_nullifier.integer, oldCommitment_0_nullifier_path.integer, - oldCommitment_0_nullifier_newpath.integer, oldCommitment_1_nullifier.integer, oldCommitment_1_nullifier_path.integer, - oldCommitment_1_nullifier_newpath.integer, oldCommitment_0_prev.integer, oldCommitment_0_prevSalt.integer, oldCommitment_1_prev.integer, @@ -420,12 +400,15 @@ export async function joinCommitments( const proof = generalise(Object.values(res.proof).flat(Infinity)) .map((coeff) => coeff.integer) .flat(Infinity); + const oldCommitment_newNullifierRoot = res.inputs + .slice(-1) + .map((e) => generalise(e).integer)[0]; // Send transaction to the blockchain: const txData = await instance.methods .joinCommitments( oldCommitment_nullifierRoot.integer, - oldCommitment_newNullifierRoot.integer, + oldCommitment_newNullifierRoot, [oldCommitment_0_nullifier.integer, oldCommitment_1_nullifier.integer], oldCommitment_root.integer, [newCommitment.integer], @@ -508,8 +491,9 @@ const _getnullifierMembershipWitness = (binArr, element, tree, acc) => { } }; -export async function updateNullifierTree() { - smt_tree = temp_smt_tree; +export async function updateNullifierTree(nullifier) { + smt_tree = insertLeaf(generalise(nullifier).hex(32), smt_tree); + temp_smt_tree = smt_tree; } diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index a3cbc6261..f15ded32f 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -358,7 +358,7 @@ class BoilerplateGenerator { `\nimport fs from 'fs'; \n`, `\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`, - `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,updateNullifierTree} from './common/commitment-storage.mjs';`, + `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,resetTemproraryNullifierTree} from './common/commitment-storage.mjs';`, `\nimport { generateProof } from './common/zokrates.mjs';`, `\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`, `\nimport Web3 from './common/web3.mjs';`, diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index 43980a873..cd585875b 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -750,12 +750,20 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { }; case 'GenerateProof': + let resetNullifierNode = []; + for ([stateName, stateNode] of Object.entries(node.privateStates)) { + if(stateNode.isPartitioned && !stateNode.accessedOnly && (resetNullifierNode.length === 0)) + resetNullifierNode.push(' await resetTemproraryNullifierTree();') + + } [ lines[0], params[0], latestNullifierRoot[0] ] = generateProofBoilerplate(node); return { statements: [ - `\n\n// Call Zokrates to generate the proof: - \nconst allInputs = [`, + `\n\n// Reset the temproary updates to the nullifier Tree`, + `\n ${resetNullifierNode[0]}`, + `\n\n// Call Zokrates to generate the proof:`, + ` \nconst allInputs = [`, `${lines[0]}`, `\nconst res = await generateProof('${node.circuitName}', allInputs);`, `\nconst proof = generalise(Object.values(res.proof).flat(Infinity)) From 7bef56c9b1d8cc565f71e4ddff0ecbc11ddec48c Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 08:51:03 +0100 Subject: [PATCH 06/19] chore: bug fixed --- src/boilerplate/common/commitment-storage.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 6feedad42..a48e24b1d 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -491,11 +491,15 @@ const _getnullifierMembershipWitness = (binArr, element, tree, acc) => { } }; -export async function updateNullifierTree(nullifier) { +async function updateNullifierTree(nullifier) { smt_tree = insertLeaf(generalise(nullifier).hex(32), smt_tree); temp_smt_tree = smt_tree; } +export async function resetTemproraryNullifierTree() { + temp_smt_tree = smt_tree; +} + export function getnullifierMembershipWitness(nullifier) { From 9a77770ca891dad108c4e951e3b0d6cb7333e175 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 08:59:26 +0100 Subject: [PATCH 07/19] chore: bug fixed --- src/boilerplate/common/commitment-storage.mjs | 4 +++- .../orchestration/javascript/raw/boilerplate-generator.ts | 2 +- .../orchestration/javascript/raw/toOrchestration.ts | 2 +- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index a48e24b1d..1f4827c64 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -370,6 +370,8 @@ export async function joinCommitments( } // Call Zokrates to generate the proof: +await resetTemporaryNullifierTree(); + const allInputs = [ fromID, stateVarID, @@ -496,7 +498,7 @@ async function updateNullifierTree(nullifier) { temp_smt_tree = smt_tree; } -export async function resetTemproraryNullifierTree() { +export async function resetTemporaryNullifierTree() { temp_smt_tree = smt_tree; } diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index f15ded32f..3dca33ea2 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -358,7 +358,7 @@ class BoilerplateGenerator { `\nimport fs from 'fs'; \n`, `\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`, - `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,resetTemproraryNullifierTree} from './common/commitment-storage.mjs';`, + `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,resetTemporaryNullifierTree} from './common/commitment-storage.mjs';`, `\nimport { generateProof } from './common/zokrates.mjs';`, `\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`, `\nimport Web3 from './common/web3.mjs';`, diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index cd585875b..7124564ca 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -753,7 +753,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { let resetNullifierNode = []; for ([stateName, stateNode] of Object.entries(node.privateStates)) { if(stateNode.isPartitioned && !stateNode.accessedOnly && (resetNullifierNode.length === 0)) - resetNullifierNode.push(' await resetTemproraryNullifierTree();') + resetNullifierNode.push(' await resetTemporaryNullifierTree();') } [ lines[0], params[0], latestNullifierRoot[0] ] = generateProofBoilerplate(node); From 582f1c92885d4c425a9a13cc0b15163af785e501 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 10:18:26 +0100 Subject: [PATCH 08/19] chore: bug resolved --- src/boilerplate/orchestration/javascript/raw/toOrchestration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index 7124564ca..a9aed9326 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -752,7 +752,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { case 'GenerateProof': let resetNullifierNode = []; for ([stateName, stateNode] of Object.entries(node.privateStates)) { - if(stateNode.isPartitioned && !stateNode.accessedOnly && (resetNullifierNode.length === 0)) + if(stateNode.nullifierRequired && !stateNode.accessedOnly && (resetNullifierNode.length === 0)) resetNullifierNode.push(' await resetTemporaryNullifierTree();') } From 2468180475ad518ece3f2b151857de1bcc7975a8 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 11:23:52 +0100 Subject: [PATCH 09/19] chore: added fix for internal function call --- src/boilerplate/common/commitment-storage.mjs | 2 +- .../orchestration/javascript/raw/boilerplate-generator.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 1f4827c64..5409eebd6 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -493,7 +493,7 @@ const _getnullifierMembershipWitness = (binArr, element, tree, acc) => { } }; -async function updateNullifierTree(nullifier) { +export async function updateNullifierTree(nullifier) { smt_tree = insertLeaf(generalise(nullifier).hex(32), smt_tree); temp_smt_tree = smt_tree; } diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index 3dca33ea2..bf5590238 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -358,7 +358,7 @@ class BoilerplateGenerator { `\nimport fs from 'fs'; \n`, `\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`, - `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,resetTemporaryNullifierTree} from './common/commitment-storage.mjs';`, + `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,updateNullifierTree,resetTemporaryNullifierTree} from './common/commitment-storage.mjs';`, `\nimport { generateProof } from './common/zokrates.mjs';`, `\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`, `\nimport Web3 from './common/web3.mjs';`, From f76bbe075b985da8bfc3c0d79e80d506dc4c731d Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 12:44:11 +0100 Subject: [PATCH 10/19] chore: added code for temp restore updates --- src/boilerplate/common/generic-test.mjs | 3 +++ .../javascript/raw/boilerplate-generator.ts | 2 +- .../orchestration/javascript/raw/toOrchestration.ts | 12 ++---------- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/boilerplate/common/generic-test.mjs b/src/boilerplate/common/generic-test.mjs index c5bc88552..397959489 100644 --- a/src/boilerplate/common/generic-test.mjs +++ b/src/boilerplate/common/generic-test.mjs @@ -2,6 +2,7 @@ import FUNCTION_NAME from './FUNCTION_NAME.mjs'; import { startEventFilter, getSiblingPath } from './common/timber.mjs'; import logger from './common/logger.mjs'; import web3 from './common/web3.mjs'; +import { resetTemporaryNullifierTree } from './common/commitment-storage.mjs'; // 'sleep' just creates a delay, ensuring the tests don't overlap @@ -54,6 +55,7 @@ describe('FUNCTION_NAME', async function () { } await sleep(10); } catch (err) { + await resetTemporaryNullifierTree(); logger.error(err); process.exit(1); } @@ -82,6 +84,7 @@ describe('FUNCTION_NAME', async function () { console.log(tx.returnValues[0]); } } catch (err) { + await resetTemporaryNullifierTree(); logger.error(err); process.exit(1); } diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index bf5590238..a3cbc6261 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -358,7 +358,7 @@ class BoilerplateGenerator { `\nimport fs from 'fs'; \n`, `\nimport { getContractInstance, getContractAddress, registerKey } from './common/contract.mjs';`, - `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,updateNullifierTree,resetTemporaryNullifierTree} from './common/commitment-storage.mjs';`, + `\nimport { storeCommitment, getCurrentWholeCommitment, getCommitmentsById, getAllCommitments, getInputCommitments, joinCommitments, markNullified,getnullifierMembershipWitness,temporaryUpdateNullifier,updateNullifierTree} from './common/commitment-storage.mjs';`, `\nimport { generateProof } from './common/zokrates.mjs';`, `\nimport { getMembershipWitness, getRoot } from './common/timber.mjs';`, `\nimport Web3 from './common/web3.mjs';`, diff --git a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts index a9aed9326..adc4f76e5 100644 --- a/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts +++ b/src/boilerplate/orchestration/javascript/raw/toOrchestration.ts @@ -750,20 +750,12 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => { }; case 'GenerateProof': - let resetNullifierNode = []; - for ([stateName, stateNode] of Object.entries(node.privateStates)) { - if(stateNode.nullifierRequired && !stateNode.accessedOnly && (resetNullifierNode.length === 0)) - resetNullifierNode.push(' await resetTemporaryNullifierTree();') - - } [ lines[0], params[0], latestNullifierRoot[0] ] = generateProofBoilerplate(node); return { statements: [ - `\n\n// Reset the temproary updates to the nullifier Tree`, - `\n ${resetNullifierNode[0]}`, - `\n\n// Call Zokrates to generate the proof:`, - ` \nconst allInputs = [`, + `\n\n// Call Zokrates to generate the proof: + \nconst allInputs = [`, `${lines[0]}`, `\nconst res = await generateProof('${node.circuitName}', allInputs);`, `\nconst proof = generalise(Object.values(res.proof).flat(Infinity)) From cd3bc355727af48e52fa74c423b6773ed4b04152 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Fri, 14 Jul 2023 12:56:36 +0100 Subject: [PATCH 11/19] chore: added fix for test imports --- src/boilerplate/common/generic-test.mjs | 2 +- .../orchestration/javascript/raw/boilerplate-generator.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/boilerplate/common/generic-test.mjs b/src/boilerplate/common/generic-test.mjs index 397959489..46609309a 100644 --- a/src/boilerplate/common/generic-test.mjs +++ b/src/boilerplate/common/generic-test.mjs @@ -2,7 +2,7 @@ import FUNCTION_NAME from './FUNCTION_NAME.mjs'; import { startEventFilter, getSiblingPath } from './common/timber.mjs'; import logger from './common/logger.mjs'; import web3 from './common/web3.mjs'; -import { resetTemporaryNullifierTree } from './common/commitment-storage.mjs'; + // 'sleep' just creates a delay, ensuring the tests don't overlap diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index a3cbc6261..eeb86dcc6 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -600,7 +600,7 @@ integrationTestBoilerplate = { ` }, preStatements(): string{ - return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\n import GN from "general-number";\nimport {getAllCommitments} from "./common/commitment-storage.mjs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport web3 from './common/web3.mjs';\n\n + return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\n import GN from "general-number";\nimport {getAllCommitments, resetTemporaryNullifierTree} from "./common/commitment-storage.mjs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport web3 from './common/web3.mjs';\n\n /** Welcome to your zApp's integration test! Depending on how your functions interact and the range of inputs they expect, the below may need to be changed. From d69df3dc4ee64c64af0cb13968932ea34666ad54 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Mon, 17 Jul 2023 12:38:55 +0100 Subject: [PATCH 12/19] chore: corrected the updateNullifierTree --- src/boilerplate/common/commitment-storage.mjs | 7 +++---- src/boilerplate/common/services/generic-api_services.mjs | 5 +++-- .../orchestration/javascript/raw/boilerplate-generator.ts | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 5409eebd6..0d930c8c8 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -173,7 +173,7 @@ export async function markNullified(commitmentHash, secretKey = null) { }, }; // updating the original tree - await updateNullifierTree(nullifier); + await updateNullifierTree(); return db.collection(COMMITMENTS_COLLECTION).updateOne(query, update); } @@ -493,9 +493,8 @@ const _getnullifierMembershipWitness = (binArr, element, tree, acc) => { } }; -export async function updateNullifierTree(nullifier) { - smt_tree = insertLeaf(generalise(nullifier).hex(32), smt_tree); - temp_smt_tree = smt_tree; +export async function updateNullifierTree() { + smt_tree = temp_smt_tree; } export async function resetTemporaryNullifierTree() { diff --git a/src/boilerplate/common/services/generic-api_services.mjs b/src/boilerplate/common/services/generic-api_services.mjs index 6dba0b2a6..48f0cf10e 100644 --- a/src/boilerplate/common/services/generic-api_services.mjs +++ b/src/boilerplate/common/services/generic-api_services.mjs @@ -6,7 +6,7 @@ import { startEventFilter, getSiblingPath } from "./common/timber.mjs"; import fs from "fs"; import logger from "./common/logger.mjs"; import { decrypt } from "./common/number-theory.mjs"; -import { getAllCommitments, getCommitmentsByState } from "./common/commitment-storage.mjs"; +import { getAllCommitments, getCommitmentsByState} from "./common/commitment-storage.mjs"; import web3 from "./common/web3.mjs"; /** @@ -44,7 +44,7 @@ export async function service_FUNCTION_NAME (req, res, next){ console.log(`Merkle tree event returnValues:`); console.log(tx.returnValues); } - if (encEvent.event) { + if (encEvent && encEvent[0]?.event) { encryption.msgs = encEvent[0].returnValues[0]; encryption.key = encEvent[0].returnValues[1]; console.log("EncryptedMsgs:"); @@ -52,6 +52,7 @@ export async function service_FUNCTION_NAME (req, res, next){ } await sleep(10); } catch (err) { + await resetTemporaryNullifierTree(); logger.error(err); res.send({ errors: [err.message] }); } diff --git a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts index eeb86dcc6..584dc15a6 100644 --- a/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts +++ b/src/boilerplate/orchestration/javascript/raw/boilerplate-generator.ts @@ -639,7 +639,7 @@ integrationApiServicesBoilerplate = { ` }, preStatements(): string{ - return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport { getAllCommitments, getCommitmentsByState } from "./common/commitment-storage.mjs";\nimport web3 from './common/web3.mjs';\n\n + return ` import { startEventFilter, getSiblingPath } from './common/timber.mjs';\nimport fs from "fs";\nimport logger from './common/logger.mjs';\nimport { decrypt } from "./common/number-theory.mjs";\nimport { getAllCommitments, getCommitmentsByState, resetTemporaryNullifierTree } from "./common/commitment-storage.mjs";\nimport web3 from './common/web3.mjs';\n\n /** NOTE: this is the api service file, if you need to call any function use the correct url and if Your input contract has two functions, add() and minus(). minus() cannot be called before an initial add(). */ From 66dbff92c05253974179065b8a8e27a02f982338 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Mon, 17 Jul 2023 12:55:01 +0100 Subject: [PATCH 13/19] fix: remove the reset nullifier tree in join commitment --- src/boilerplate/common/commitment-storage.mjs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/boilerplate/common/commitment-storage.mjs b/src/boilerplate/common/commitment-storage.mjs index 0d930c8c8..b69aad4ac 100644 --- a/src/boilerplate/common/commitment-storage.mjs +++ b/src/boilerplate/common/commitment-storage.mjs @@ -370,8 +370,6 @@ export async function joinCommitments( } // Call Zokrates to generate the proof: -await resetTemporaryNullifierTree(); - const allInputs = [ fromID, stateVarID, From de82554931c9285b30c9b532ebd2285ed99a5e5e Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Mon, 17 Jul 2023 16:23:48 +0100 Subject: [PATCH 14/19] chore: removed the extra call for nullifier update for accessed only --- .../sparse-merkle-tree/checkproof.zok | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok index c34f8988c..7fd06cfd6 100644 --- a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok +++ b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok @@ -2,8 +2,7 @@ from "hashes/poseidon/poseidon.zok" import main as poseidon from "../../concatenate/order-left-right-1x1.zok" import main as orderLeftRight from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256 -def main(field[32] siblingPath, field value, field root, bool isAccessed) -> (field): - +def checkRoot(field[32] siblingPath, field value, field root) -> (field): field accValue = 0 // checking against zero element field[2] preimage = [0, 0] @@ -22,10 +21,19 @@ for u32 i in 0..32 do assert(root == accValue) +accValue = if isAccessed == true then root else getUpdatedRoot(siblingPath, value, root) fi + +return accValue + + + +def getUpdatedRoot(field[32] siblingPath, field value, field root, bool isAccessed) -> (field): + // Calculate the new Root -accValue = value // checking against zero element -preimage = [0, 0] +field accValue = value // checking against zero element +field[2] preimage = [0, 0] +bool[32] valueIndex = field_to_bool_256(value)[2..34] for u32 i in 0..32 do u32 j = i // iterator for the siblingPath @@ -37,6 +45,4 @@ for u32 i in 0..32 do ]) endfor -accValue = if isAccessed == true then root else accValue fi - return accValue \ No newline at end of file From 40840fe666c0c9d0b2c249523c021711b1e9cdab Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 18 Jul 2023 08:23:08 +0100 Subject: [PATCH 15/19] fix: fixed code to reduce constraint --- .../sparse-merkle-tree/checkproof.zok | 8 +++---- .../zokrates/raw/BoilerplateGenerator.ts | 23 +++++++++++-------- .../circuit/zokrates/toCircuit.ts | 1 - 3 files changed, 17 insertions(+), 15 deletions(-) diff --git a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok index 7fd06cfd6..e27a91ac9 100644 --- a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok +++ b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok @@ -2,7 +2,7 @@ from "hashes/poseidon/poseidon.zok" import main as poseidon from "../../concatenate/order-left-right-1x1.zok" import main as orderLeftRight from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256 -def checkRoot(field[32] siblingPath, field value, field root) -> (field): +def checkRoot(field[32] siblingPath, field value, field root) -> (field): field accValue = 0 // checking against zero element field[2] preimage = [0, 0] @@ -21,13 +21,13 @@ for u32 i in 0..32 do assert(root == accValue) -accValue = if isAccessed == true then root else getUpdatedRoot(siblingPath, value, root) fi - return accValue -def getUpdatedRoot(field[32] siblingPath, field value, field root, bool isAccessed) -> (field): +def main(field[32] siblingPath, field value, field root) -> (field): + +assert(root == checkRoot(siblingPath, value, root)) // Calculate the new Root diff --git a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts index 62a569f14..4d25234f3 100644 --- a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts +++ b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts @@ -48,11 +48,18 @@ class BoilerplateGenerator { }; nullification = { - importStatements(): string[] { + importStatements({ isAccessed, isNullified }): string[] { + if(isAccessed && !isNullified) + return [ + `from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256`, + `from "./common/hashes/poseidon/poseidon.zok" import main as poseidon`, + `from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import checkRoot as checkNullifierRoot`, + ]; + return [ `from "utils/pack/bool/nonStrictUnpack256.zok" import main as field_to_bool_256`, `from "./common/hashes/poseidon/poseidon.zok" import main as poseidon`, - `from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as checkproof`, + `from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as updateNullifierRoot`, ]; }, @@ -117,24 +124,20 @@ class BoilerplateGenerator { // ${x}_oldCommitment_nullifier : non-existence check - isAccessed = true \\ - nullifierRoot = checkproof(\\ + nullifierRoot = checkNullifierRoot(\\ ${x}_nullifier_nonmembershipWitness_siblingPath,\\ ${x}_oldCommitment_nullifier,\\ - nullifierRoot,\\ - isAccessed\\ + nullifierRoot\\ )\ `, ] : lines.push( ` - isAccessed = false \\ - nullifierRoot = checkproof(\\ + nullifierRoot = updateNullifierRoot(\\ ${x}_nullifier_nonmembershipWitness_siblingPath,\\ ${x}_oldCommitment_nullifier,\\ - nullifierRoot,\\ - isAccessed\\ + nullifierRoot\\ )\ ` ); diff --git a/src/codeGenerators/circuit/zokrates/toCircuit.ts b/src/codeGenerators/circuit/zokrates/toCircuit.ts index 19b1d80bc..143c00228 100644 --- a/src/codeGenerators/circuit/zokrates/toCircuit.ts +++ b/src/codeGenerators/circuit/zokrates/toCircuit.ts @@ -98,7 +98,6 @@ function codeGenerator(node: any) { if(codeGenerator(node.parameters).includes('nullifierRoot')){ returnStatement.push('nullifierRoot'); returnType.push('field') ; - body = ('bool isAccessed = false \n').concat(body) } if(returnStatement.length === 0){ From 6c06094d0ca5eb453f9ff1d95ebaf59f9f4ac6d3 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 18 Jul 2023 08:45:08 +0100 Subject: [PATCH 16/19] fix: fix join commitment circuit --- circuits/common/joinCommitments.zok | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/circuits/common/joinCommitments.zok b/circuits/common/joinCommitments.zok index 104f3a5b3..d421d8b38 100644 --- a/circuits/common/joinCommitments.zok +++ b/circuits/common/joinCommitments.zok @@ -10,7 +10,7 @@ from "./common/hashes/poseidon/poseidon.zok" import main as poseidon from "./common/casts/u32_array_to_field.zok" import main as u32_array_to_field from "utils/pack/bool/pack256.zok" import main as bool_256_to_field from "./common/merkle-tree/mimc/altbn254/verify-membership/height32.zok" import main as checkRoot -from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as checkproof +from "./common/merkle-tree/sparse-merkle-tree/checkproof.zok" import main as updateNullifierRoot def main(\ private field fromId,\ @@ -53,8 +53,6 @@ def main(\ field oldCommitment_1 = oldCommitment_1_value - bool isAccessed = false - // oldCommitment_0 - PoKoSK: // The correctness of this secret key will be constrained within the oldCommitment existence check. @@ -93,11 +91,10 @@ def main(\ ) - nullifierRoot = checkproof(\ + nullifierRoot = updateNullifierRoot(\ oldCommitment_0_nullifier_nonmembershipWitness_siblingPath,\ oldCommitment_0_nullifier,\ - nullifierRoot,\ - isAccessed\ + nullifierRoot\ ) @@ -114,11 +111,10 @@ def main(\ ) - nullifierRoot = checkproof(\ + nullifierRoot = updateNullifierRoot(\ oldCommitment_1_nullifier_nonmembershipWitness_siblingPath,\ oldCommitment_1_nullifier,\ - nullifierRoot,\ - isAccessed\ + nullifierRoot\ ) From 4ae6e2fbb42e3197059a1caf553879c0de86a324 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Mon, 24 Jul 2023 09:35:59 +0100 Subject: [PATCH 17/19] chore: Fixed the comments --- circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok | 2 +- src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok index e27a91ac9..42170ee6f 100644 --- a/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok +++ b/circuits/common/merkle-tree/sparse-merkle-tree/checkproof.zok @@ -31,7 +31,7 @@ assert(root == checkRoot(siblingPath, value, root)) // Calculate the new Root -field accValue = value // checking against zero element +field accValue = value // Inserting the element field[2] preimage = [0, 0] bool[32] valueIndex = field_to_bool_256(value)[2..34] diff --git a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts index 4d25234f3..b4c769a6c 100644 --- a/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts +++ b/src/boilerplate/circuit/zokrates/raw/BoilerplateGenerator.ts @@ -114,7 +114,7 @@ class BoilerplateGenerator { (isAccessed && !isNullified) ? lines = [ ` - // Create the Nullifier for ${x} and no need to nnullify it as its accessed only: + // Create the Nullifier for ${x} and no need to nullify it as its accessed only: field ${x}_oldCommitment_nullifier = poseidon([\\ ${x}_stateVarId_field,\\ From cc045cb512dbc8dd3d903767a58b155b10941e9a Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Tue, 25 Jul 2023 11:49:32 +0100 Subject: [PATCH 18/19] chore: merge conflict resolved --- .../contract/solidity/raw/FunctionBoilerplateGenerator.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts b/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts index de82b2cad..270f1b540 100644 --- a/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts +++ b/src/boilerplate/contract/solidity/raw/FunctionBoilerplateGenerator.ts @@ -96,6 +96,11 @@ class FunctionBoilerplateGenerator { let msgSigCheck = ([...(isConstructor ? [] : [`bytes4 sig = bytes4(keccak256("${functionName}(${parameter})")) ; \n \t \t \t if (sig == msg.sig)`])]); customInputs = customInputs?.flat(Infinity).filter(p => p.inCircuit); + + customInputs?.forEach((input, i) => { + if(input.name === 1 && input.type === 'uint256' && newNullifiers) customInputs.splice(i,1); + }); + return [ ` From c9bf1b59921c1214b614fa6e4a7c63616c5189c2 Mon Sep 17 00:00:00 2001 From: SwatiEY <97442865+SwatiEY@users.noreply.github.com> Date: Thu, 31 Aug 2023 10:12:29 +0100 Subject: [PATCH 19/19] chore : return statement fix --- src/transformers/visitors/toContractVisitor.ts | 6 +++--- test/contracts/Assign-Return.zol | 7 ++++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/transformers/visitors/toContractVisitor.ts b/src/transformers/visitors/toContractVisitor.ts index 9e5c6618f..abedaf84b 100644 --- a/src/transformers/visitors/toContractVisitor.ts +++ b/src/transformers/visitors/toContractVisitor.ts @@ -29,13 +29,13 @@ const findCustomInputsVisitor = (thisPath: NodePath, thisState: any) => { item.expression.components.forEach(element => { if(element.kind === 'bool'){ thisState.customInputs ??= []; - thisState.customInputs.push({name: '1', typeName: {name: 'bool'}}); + thisState.customInputs.push({name: '1', typeName: {name: 'bool'}, inCircuit: true}); } }); } else { if(item.expression.kind === 'bool'){ thisState.customInputs ??= []; - thisState.customInputs.push({name: '1', typeName: {name: 'bool'}}); + thisState.customInputs.push({name: '1', typeName: {name: 'bool'}, inCircuit: true}); } } } @@ -44,7 +44,7 @@ const findCustomInputsVisitor = (thisPath: NodePath, thisState: any) => { if(thisPath.getAncestorOfType('Return') && binding instanceof VariableBinding && binding.isSecret){ thisState.customInputs ??= []; if(thisState.variableName.includes(indicator.node.name)) - thisState.customInputs.push({name: 'newCommitments['+(thisState.variableName.indexOf(indicator.node.name))+']', typeName: {name: 'uint256'}}); + thisState.customInputs.push({name: 'newCommitments['+(thisState.variableName.indexOf(indicator.node.name))+']', typeName: {name: 'uint256'},inCircuit: true}); } // for some reason, node.interactsWithSecret has disappeared here but not in toCircuit diff --git a/test/contracts/Assign-Return.zol b/test/contracts/Assign-Return.zol index 812ecdcd5..515bd29d5 100644 --- a/test/contracts/Assign-Return.zol +++ b/test/contracts/Assign-Return.zol @@ -5,11 +5,12 @@ pragma solidity ^0.8.0; contract Assign { secret uint256 private a; - uint256 private b; + secret uint256 private b; - function add( uint256 value) public returns (bool, uint256) { + function add( uint256 value) public { unknown a += value; - return (true, 5); + unknown b += value; + } function remove(secret uint256 value, uint256 value1) public returns (uint256, uint256) {