Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kahina/non secret array #322

Merged
merged 27 commits into from
Sep 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ class FunctionBoilerplateGenerator {
});
return { structName: structDef.name, properties: names, isParam: path.isFunctionParameter(node), isConstantArray: path.isConstantArray(node) ? node.typeName.length.value : false, inCircuit: node.interactsWithSecret };
}
return { name: node.name, type: node.typeName.name || node.typeName.baseType?.name || node.typeName.pathNode?.name, isParam: path.isFunctionParameter(node), isConstantArray: path.isConstantArray(node) ? node.typeName.length.value : false, inCircuit: node.interactsWithSecret };
return { name: node.name, type: node.typeName.name || node.typeName.baseType?.name || node.typeName.pathNode?.name, isParam: path.isFunctionParameter(node), isConstantArray: path.isConstantArray(node) ? node.typeName.length.value : false, inCircuit: node.interactsWithSecret || scope.getReferencedIndicator(node)?.interactsWithSecret };
}

const params = path.getFunctionParameters();
Expand Down
30 changes: 5 additions & 25 deletions src/boilerplate/orchestration/javascript/raw/toOrchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ export const sendTransactionBoilerplate = (node: any) => {
output[5].push(`${privateStateName}_cipherText`);
output[6].push(`${privateStateName}_encKey`);
}

break;
}
}
Expand Down Expand Up @@ -139,7 +138,6 @@ export const generateProofBoilerplate = (node: any) => {
// 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';
const msgValueParamAndMappingKey = stateNode.isMapping && (node.parameters.includes('msgValue') || output.join().includes('_msg_stateVarId_key.integer')) && stateNode.stateVarId[1] === 'msg';

const constantMappingKey = stateNode.isMapping && (+stateNode.stateVarId[1] || stateNode.stateVarId[1] === '0');

// We are keeping this code in comments, for future if have any issue with extra mapping keys getting added for a zapp we can come to this
Expand Down Expand Up @@ -176,8 +174,8 @@ export const generateProofBoilerplate = (node: any) => {
else {
parameters.push(`\t${param}.integer,`);
}

});

// then we build boilerplate code per state
switch (stateNode.isWhole) {
case true:
Expand Down Expand Up @@ -321,7 +319,6 @@ export const preimageBoilerPlate = (node: any) => {
accessedOnly: true,
stateVarIds,
}));

continue;
}

Expand Down Expand Up @@ -503,29 +500,25 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
lines.push(`\nconst ${param} = generalise(_${param});`);
params.push(`_${param}`);
});

node.parameters.modifiedStateVariables.forEach((param: any) => {
states.push(`_${param.name}_newOwnerPublicKey = 0`);
lines.push(
`\nlet ${param.name}_newOwnerPublicKey = generalise(_${param.name}_newOwnerPublicKey);`,
);
});

if (node.decrementsSecretState) {
node.decrementedSecretStates.forEach((decrementedState: string) => {
states.push(` _${decrementedState}_0_oldCommitment = 0`);
states.push(` _${decrementedState}_1_oldCommitment = 0`);
});
}

node.returnParameters.forEach( (param, index) => {
if(param === 'true')
rtnparams?.push('bool: bool');
else
rtnparams?.push( ` ${param.replace('_change', '')}_newCommitmentValue : ${param}.integer `);
});
if (params) params[params.length - 1] += `,`;

if (node.name === 'cnstrctr')
return {
signature: [
Expand All @@ -547,7 +540,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
statements: lines,
};
}

if(rtnparams.includes('bool: bool')) {
return {
signature: [
Expand All @@ -560,7 +552,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
statements: lines,
};
}

return {
signature: [
` ${functionSig}
Expand Down Expand Up @@ -603,7 +594,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
mappingName: stateNode.mappingName || stateName,
structProperties: stateNode.structProperties
}));

}
return {
statements: lines,
Expand Down Expand Up @@ -749,7 +739,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
statements: [`\n// Extract set membership witness: \n\n`, ...lines],
};

case 'CalculateNullifier':
case 'CalculateNullifier':
for ([stateName, stateNode] of Object.entries(node.privateStates)) {
if (stateNode.isPartitioned) {
lines.push(
Expand All @@ -759,7 +749,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
accessedOnly: stateNode.accessedOnly,
stateType: 'partitioned',
}));

} else {
lines.push(
Orchestrationbp.calculateNullifier.postStatements({
Expand All @@ -770,7 +759,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
}));
}
}

for ([stateName, stateNode] of Object.entries(node.privateStates)) {
if (stateNode.isPartitioned) {
lines.push(
Expand All @@ -779,7 +767,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
accessedOnly: stateNode.accessedOnly,
stateType: 'partitioned',
}));

} else {
lines.push(
Orchestrationbp.temporaryUpdatedNullifier.postStatements({
Expand All @@ -789,7 +776,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
}));
}
}

for ([stateName, stateNode] of Object.entries(node.privateStates)) {
if (stateNode.isPartitioned) {
lines.push(
Expand All @@ -808,7 +794,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
}));
}
}

return {
statements: [`\n// Calculate nullifier(s): \n`, ...lines],
};
Expand All @@ -825,7 +810,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
isSharedSecret: stateNode.isSharedSecret,
structProperties: stateNode.structProperties,
}));

break;
case true:
default:
Expand All @@ -839,7 +823,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
isSharedSecret: stateNode.isSharedSecret,
structProperties: stateNode.structProperties,
}));

break;
case false:
default:
Expand All @@ -851,7 +834,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
isSharedSecret: stateNode.isSharedSecret,
structProperties: stateNode.structProperties,
}));

}
}
}
Expand All @@ -874,7 +856,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
],
};

case 'EncryptBackupPreimage':
case 'EncryptBackupPreimage':
lines.push(`let BackupData = [];\n`)
for ([stateName, stateNode] of Object.entries(node.privateStates)) {
let stateType;
Expand Down Expand Up @@ -949,8 +931,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
]
}



return {
statements: [
`\n\n// Send transaction to the blockchain:
Expand Down Expand Up @@ -993,8 +973,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
],
};


case 'SendPublicTransaction':
case 'SendPublicTransaction':
if (node.publicInputs[0]) {
node.publicInputs.forEach((input: any) => {
if (input.properties) {
Expand All @@ -1011,6 +990,7 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
}
});
}

return {
statements: [
`\n\n// Send transaction to the blockchain:
Expand Down
47 changes: 20 additions & 27 deletions src/codeGenerators/orchestration/nodejs/toOrchestration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@ const getAccessedValue = (name: string) => {
*/
const getPublicValue = (node: any) => {
if (node.nodeType !== 'IndexAccess')
// In the _init variable we save the initial value of the variable for use later.
// In the _init variable we save the initial value of the variable for use later.
return `\nlet ${node.name} = generalise(await instance.methods.${codeGenerator(node)}().call());\n let ${node.name}_init = ${node.name};`;
return `\nconst ${node.name} = generalise(await instance.methods.${codeGenerator(node.baseExpression, { lhs: true} )}(${codeGenerator(node.indexExpression, { contractCall: true })}).call());`;
return `\nlet ${node.name} = generalise(await instance.methods.${codeGenerator(node.baseExpression, { lhs: true} )}(${codeGenerator(node.indexExpression, { contractCall: true })}).call()); \n let ${node.name}_init = ${node.name}`;
};

/**
Expand Down Expand Up @@ -63,7 +63,6 @@ export default function codeGenerator(node: any, options: any = {}): any {
const fn = OrchestrationCodeBoilerPlate(node);
const statements = codeGenerator(node.body);
fn.statements.push(statements);

return `${fn.signature[0]}\n\t${fn.statements.join('')}\n${
fn.signature[1]
}`;
Expand Down Expand Up @@ -96,7 +95,6 @@ export default function codeGenerator(node: any, options: any = {}): any {
} else if (node.declarations[0].isAccessed) {
return `${getAccessedValue(node.declarations[0].name)}`;
}

if (!node.initialValue && !node.declarations[0].isAccessed) return `\nlet ${codeGenerator(node.declarations[0])};`;
if (node.initialValue &&
node.initialValue.operator &&
Expand All @@ -111,24 +109,24 @@ export default function codeGenerator(node: any, options: any = {}): any {
if (node.initialValue.nodeType === 'Literal' && node.isInitializationExpression) return `\nlet ${codeGenerator(node.declarations[0])} = ${codeGenerator(node.initialValue)};`;
return `\nlet ${codeGenerator(node.declarations[0])} = generalise(${codeGenerator(node.initialValue)});`;
}
return `\nlet ${codeGenerator(node.initialValue)};`;
return `\nlet ${codeGenerator(node.initialValue)};`;
}

case 'ElementaryTypeName':
return;

case 'Block': {
const preStatements: string = (node.preStatements.flatMap(codeGenerator));
const statements:string = (node.statements.flatMap(codeGenerator));
const postStatements: string = (node.postStatements.flatMap(codeGenerator));
return [...preStatements, ...statements, ...postStatements].join('\n\n');
case 'Block': {
const preStatements: string = (node.preStatements.flatMap(codeGenerator));
const statements:string = (node.statements.flatMap(codeGenerator));
const postStatements: string = (node.postStatements.flatMap(codeGenerator));
return [...preStatements, ...statements, ...postStatements].join('\n\n');
}

case 'ExpressionStatement':
if (!node.incrementsSecretState && (node.interactsWithSecret || node.expression?.internalFunctionInteractsWithSecret)){
return `\n${codeGenerator(node.expression)};`;
}
if (node.incrementsSecretState && (node.interactsWithSecret || node.expression?.internalFunctionInteractsWithSecret)){
if (node.incrementsSecretState && (node.interactsWithSecret ||node.containsPublic || node.expression?.internalFunctionInteractsWithSecret)){
let privateStateName = node.privateStateName.replace(/\./g, '_');
let increments;
if (node.expression.operator === '+='){
Expand Down Expand Up @@ -157,16 +155,15 @@ export default function codeGenerator(node: any, options: any = {}): any {
}
}
}

if (!node.interactsWithSecret)
return `\n// non-secret line would go here but has been filtered out`;
return `\n// increment would go here but has been filtered out`;
return `\n// non-secret line would go here but has been filtered out`;
return `\n// increment would go here but has been filtered out`;

case 'InternalFunctionCall':
return " ";

case 'Assignment':
// To ensure the left hand side is always a general number, we generalise it here (excluding the initialisation in a for loop).
// To ensure the left hand side is always a general number, we generalise it here (excluding the initialisation in a for loop).
if (!node.isInitializationAssignment && node.rightHandSide.subType !== 'generalNumber'){
if (['+=', '-=', '*='].includes(node.operator)) {
return `${codeGenerator(node.leftHandSide, {
Expand All @@ -175,7 +172,7 @@ export default function codeGenerator(node: any, options: any = {}): any {
0,
)} ${codeGenerator(node.rightHandSide)})`;
}
return `${codeGenerator(node.leftHandSide, { lhs: true })} ${
return `${codeGenerator(node.leftHandSide, { lhs: true })} ${
node.operator
} generalise(${codeGenerator(node.rightHandSide)})`;
} else {
Expand All @@ -190,7 +187,6 @@ export default function codeGenerator(node: any, options: any = {}): any {
node.operator
} ${codeGenerator(node.rightHandSide)}`;
}


case 'BinaryOperation':
return `${codeGenerator(node.leftExpression, { lhs: options.condition })} ${
Expand All @@ -202,9 +198,8 @@ export default function codeGenerator(node: any, options: any = {}): any {
return `(${node.components.map(codeGenerator).join(` `)})`;
return ` `;

case 'IfStatement': {
case 'IfStatement': {
let comment = (node.inPreStatements) ? "// some public statements of this if statement have been moved to pre-statements here, any other statements appear later" : '';

// We need to declare some variables before the if statement begins (because they are used outside the if statement).
let preIfStatements = node.trueBody.filter((node: any) => node.outsideIf).concat(node.falseBody.filter((node: any) => node.outsideIf));
let newPreIfStatements = [];
Expand All @@ -213,7 +208,6 @@ export default function codeGenerator(node: any, options: any = {}): any {
newPreIfStatements[newPreIfStatements.length - 1].outsideIf = false;
});
let preIfStatementsString = newPreIfStatements.flatMap(codeGenerator).join('\n');

if(node.falseBody.length)
return `${comment}
${preIfStatementsString}
Expand All @@ -230,22 +224,21 @@ export default function codeGenerator(node: any, options: any = {}): any {
}`
}

case 'Conditional': {
return ` ${codeGenerator(node.condition)} ?
${node.trueExpression.flatMap(codeGenerator).join('\n')} : ${node.falseExpression.flatMap(codeGenerator).join('\n')}`
case 'Conditional': {
return ` ${codeGenerator(node.condition)} ?
${node.trueExpression.flatMap(codeGenerator).join('\n')} : ${node.falseExpression.flatMap(codeGenerator).join('\n')}`
}

case 'ForStatement': {
case 'ForStatement': {
if(node.interactsWithSecret) {
let initializationExpression = `${codeGenerator(node.initializationExpression).trim()}`;
let condition = `${codeGenerator(node.condition, { condition: true })};`;
let loopExpression = ` ${node.loopExpression.expression.rightHandSide.subExpression.name} ${node.loopExpression.expression.rightHandSide.operator}`;
return `for( ${node.initializationExpression.nodeType === 'VariableDeclarationStatement' ? `` : `let`} ${initializationExpression} ${condition} ${loopExpression}) {
${codeGenerator(node.body)}
}`
}
else
return '';
} else
return '';
}

case 'MsgSender':
Expand Down
Loading
Loading