Skip to content

Commit

Permalink
change to inferInteractsWithSecret
Browse files Browse the repository at this point in the history
  • Loading branch information
kKahina committed Sep 2, 2024
1 parent 009fe48 commit 523bb1c
Show file tree
Hide file tree
Showing 5 changed files with 22 additions and 119 deletions.
31 changes: 3 additions & 28 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 All @@ -161,13 +159,11 @@ export const generateProofBoilerplate = (node: any) => {
: [];
// we add any extra params the circuit needs
node.parameters

.filter(
(para: string) =>
!privateStateNames.includes(para) && (
!output.join().includes(`${para}.integer`) && !output.join().includes('msgValue')),
)

?.forEach((param: string) => {
if (param == 'msgSender') {
parameters.unshift(`\t${param}.integer,`);
Expand All @@ -178,7 +174,6 @@ export const generateProofBoilerplate = (node: any) => {
else {
parameters.push(`\t${param}.integer,`);
}

});

// then we build boilerplate code per state
Expand Down Expand Up @@ -241,7 +236,6 @@ export const generateProofBoilerplate = (node: any) => {
isSharedSecret: stateNode.isSharedSecret,
parameters,
})

);
containsNullifierRoot = true;
containsNewNullifierRoot = true;
Expand Down Expand Up @@ -325,7 +319,6 @@ export const preimageBoilerPlate = (node: any) => {
accessedOnly: true,
stateVarIds,
}));

continue;
}

Expand Down Expand Up @@ -507,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 @@ -551,7 +540,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
statements: lines,
};
}

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

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

}
return {
statements: lines,
Expand Down Expand Up @@ -753,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 @@ -763,7 +749,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
accessedOnly: stateNode.accessedOnly,
stateType: 'partitioned',
}));

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

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

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

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

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

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

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

}
}
}
Expand All @@ -878,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 @@ -953,8 +931,6 @@ export const OrchestrationCodeBoilerPlate: any = (node: any) => {
]
}



return {
statements: [
`\n\n// Send transaction to the blockchain:
Expand Down Expand Up @@ -997,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 Down
43 changes: 15 additions & 28 deletions src/codeGenerators/orchestration/nodejs/toOrchestration.ts
Original file line number Diff line number Diff line change
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,17 +109,17 @@ 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':
Expand All @@ -131,15 +129,12 @@ export default function codeGenerator(node: any, options: any = {}): any {
if (node.incrementsSecretState && (node.interactsWithSecret ||node.containsPublic || node.expression?.internalFunctionInteractsWithSecret)){
let privateStateName = node.privateStateName.replace(/\./g, '_');
let increments;

if (node.expression.operator === '+='){
increments = codeGenerator(node.expression.rightHandSide);

// Although we have += in the case that the indicator is decremented elsewhere in the function, we need to subtract the increments.
if (!node.indicatorDecremented) return `\n${privateStateName}_newCommitmentValue = generalise(parseInt(${privateStateName}_newCommitmentValue.integer, 10) + ${increments});\n`;
if (node.indicatorDecremented) return `\n${privateStateName}_newCommitmentValue_inc = generalise(parseInt(${privateStateName}_newCommitmentValue_inc.integer, 10) + ${increments});\n`;
}

if (node.expression.operator === '-='){
increments = codeGenerator(node.expression.rightHandSide);
return `\n${privateStateName}_newCommitmentValue = generalise(parseInt(${privateStateName}_newCommitmentValue.integer, 10) + (${increments}));\n`;
Expand All @@ -160,17 +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).

if (!node.isInitializationAssignment && node.rightHandSide.subType !== 'generalNumber'){
if (['+=', '-=', '*='].includes(node.operator)) {
return `${codeGenerator(node.leftHandSide, {
Expand All @@ -182,7 +175,6 @@ export default function codeGenerator(node: any, options: any = {}): any {
return `${codeGenerator(node.leftHandSide, { lhs: true })} ${
node.operator
} generalise(${codeGenerator(node.rightHandSide)})`;

} else {
if (['+=', '-=', '*='].includes(node.operator)) {
return `${codeGenerator(node.leftHandSide, {
Expand All @@ -194,10 +186,8 @@ export default function codeGenerator(node: any, options: any = {}): any {
return `${codeGenerator(node.leftHandSide, { lhs: true })} ${
node.operator
} ${codeGenerator(node.rightHandSide)}`;

}


case 'BinaryOperation':
return `${codeGenerator(node.leftExpression, { lhs: options.condition })} ${
node.operator
Expand All @@ -208,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 @@ -219,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 @@ -236,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
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,10 @@ const markIndicatorSubtreeInteractsWithSecret = (thisPath: any, thisState: any)
indicator.addSecretInteractingPath(thisState.secretPath);
};

const interactwithInferSecret = (thisPath: any, thisState: any) => {
const inferInteractsWithSecret = (thisPath: any, thisState: any) => {
const { node, scope } = thisPath;
if (node.nodeType === 'ExpressionStatement') {
const leftHandSideIndicator = scope.getReferencedIndicator(node.expression.leftHandSide, true);

if (leftHandSideIndicator?.interactsWithSecret) {
thisPath.traversePathsFast(markIndicatorSubtreeInteractsWithSecret, {
secretPath: thisPath,
Expand All @@ -66,7 +65,6 @@ export default {
path.getAncestorOfType('ExpressionStatement') || path.parentPath;
if (path.isExternalFunctionCall()) {
path.markContainsPublic();
// below ensures that the return value and args are marked as interactsWithPublic
expressionPath.traversePathsFast(markSubtreeInteractsWithPublic, {
publicPath: path,
});
Expand All @@ -76,7 +74,7 @@ export default {

FunctionDefinition: {
exit(path: NodePath) {
path.traversePathsFast(interactwithInferSecret, {
path.traversePathsFast(inferInteractsWithSecret, {
publicPath: path,
});
},
Expand Down
Loading

0 comments on commit 523bb1c

Please sign in to comment.