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

Public signals struct #13

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,14 @@ const templateContent = CircuitZKit.getTemplate("groth16", "sol");

Creates a Solidity | Vyper verifier contract on `verifierDirPath` path, which was specified in the config.

Two functions are available for proof verification within the contract:
- `verifyProof`: accepts an array of public inputs for verification.
- `verifyProofWithStruct`: allows passing public signals as a struct, enabling easier access and typization.

> [!TIP]
> It’s recommended to create structs using the `{ fieldName: value }` syntax. This ensures that your code
> continues to work correctly even if the order of outputs in the circuit changes.

```typescript
await multiplier.createVerifier("sol");
```
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@solarity/zkit",
"version": "0.2.6",
"version": "0.2.7",
"license": "MIT",
"author": "Distributed Lab",
"readme": "README.md",
Expand Down
36 changes: 35 additions & 1 deletion src/core/CircuitZKit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import {
ProofStruct,
VerifierProvingSystem,
VerifierLanguageType,
PublicSignalInfo,
ArtifactSignal,
CircuitArtifacts,
} from "../types/circuit-zkit";

/**
Expand Down Expand Up @@ -51,6 +54,7 @@ export class CircuitZKit {

const templateParams = JSON.parse(fs.readFileSync(vKeyFilePath, "utf-8"));
templateParams["verifier_id"] = this.getVerifierName();
templateParams["signals"] = this.getPublicSignalsInfo();

const verifierCode = ejs.render(verifierTemplate, templateParams);

Expand Down Expand Up @@ -192,9 +196,12 @@ export class CircuitZKit {
case "sym":
fileName = `${circuitName}.sym`;
break;
case "json":
case "constraints":
fileName = `${circuitName}_constraints.json`;
break;
case "artifacts":
fileName = `${circuitName}_artifacts.json`;
break;
case "wasm":
fileName = `${circuitName}.wasm`;
fileDir = path.join(fileDir, `${circuitName}_js`);
Expand All @@ -205,4 +212,31 @@ export class CircuitZKit {

return path.join(fileDir, fileName);
}

/**
* Returns the public signals information from the circuit artifacts.
*
* @dev Dimensions are reversed to align with the declaration order of multidimensional arrays in Solidity and Vyper.
*
* @returns {Array<PublicSignalInfo>} An array of objects containing the public signal names and their reversed dimensions.
*/
public getPublicSignalsInfo(): Array<PublicSignalInfo> {
const artifactsFilePath: string = this.mustGetArtifactsFilePath("artifacts");
const artifacts: CircuitArtifacts = JSON.parse(fs.readFileSync(artifactsFilePath, "utf-8"));

const signals: ArtifactSignal[] = artifacts.baseCircuitInfo.signals;

const getSignals = (signalType: string) =>
signals
.filter((signal) => signal.type === signalType && signal.visibility === "Public")
.map((signal) => ({
name: signal.name,
dimension: [...signal.dimension].reverse(),
}));

const outputSignals = getSignals("Output");
const publicInputs = getSignals("Input");

return [...outputSignals, ...publicInputs];
}
}
96 changes: 94 additions & 2 deletions src/core/templates/verifier_groth16.sol.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,24 @@ contract <%=verifier_id%> {
/// @dev memory pointer sizes
uint16 public constant P_PUBLIC_SIGNALS_ACCUMULATOR_SIZE = 128;
uint16 public constant P_TOTAL_SIZE = 896;
<%function generateType(dimension) {
if (dimension.length === 0) {
return "uint256";
} else {
return "uint256" + dimension.map(d => `[${d}]`).join("");
}
}

const structFields = signals
.map(signal => {
return `${generateType(signal.dimension)} ${signal.name};`
})
.join("\n\t\t");
-%>

struct PubSignals {
<%= structFields %>
}

function verifyProof(
uint256[2] memory pointA_,
Expand Down Expand Up @@ -145,13 +163,87 @@ contract <%=verifier_id%> {

/// @dev check that all public signals are in F
verified_ := 1
<% for (let i = 0; i < nPublic; i++) { %>verified_ := and(verified_, checkField(mload(add(publicSignals_, <%=i * 32%>))))
<% } -%>
for { let i := 0 } lt(i, <%= nPublic %>) { i := add(i, 32) } {
verified_ := and(verified_, checkField(mload(add(publicSignals_, i))))
}

/// @dev check pairings
if not(iszero(verified_)) {
verified_ := checkPairing(pointA_, pointB_, pointC_, publicSignals_, pointer_)
}
}
}

function verifyProofWithStruct(
uint256[2] memory pointA_,
uint256[2][2] memory pointB_,
uint256[2] memory pointC_,
PubSignals memory publicSignals_
) public view returns (bool verified_) {
return verifyProof(pointA_, pointB_, pointC_, _linearizePubSignals(publicSignals_));
}

<%
const generateLinearizationFunction = (name, dimension, offsetVar) => {
if (dimension.length === 0) {
return `currentOffset := _linearizeUint(linearizedArray_, currentOffset, add(publicSignals_, ${offsetVar}))`;
} else if (dimension.length === 1) {
return `currentOffset := _linearize1DArray(linearizedArray_, currentOffset, mload(add(publicSignals_, ${offsetVar})), ${dimension[0]})`;
} else {
return `currentOffset := _linearize${dimension.length}DArray(linearizedArray_, currentOffset, mload(add(publicSignals_, ${offsetVar})), ${dimension.reverse().join(", ")})`;
}
};

const generateHelperFunctions = (maxDimension) => {
let helperFunctions = "";
const indent = "\t\t\t";

if (maxDimension >= 1) {
helperFunctions += `
\n${indent}function _linearize1DArray(resultArray_, currentOffset_, ptr_, arrayLength_) -> offset_ {
for { let i := 0 } lt(i, arrayLength_) { i := add(i, 1) } {
currentOffset_ := _linearizeUint(resultArray_, currentOffset_, add(ptr_, mul(i, 32)))
}

offset_ := currentOffset_
}`;
}

const generateDimensionParams = (dimensionsNumber, startIndex = 0) => {
return Array.from({ length: dimensionsNumber }, (_, i) => `dim${i + startIndex}Length`).join(", ");
}

for (let d = 2; d <= maxDimension; d++) {
let func = `
\n${indent}function _linearize${d}DArray(resultArray_, currentOffset_, ptr_, ${generateDimensionParams(d)}) -> offset_ {
for { let i := 0 } lt(i, dim0Length) { i := add(i, 1) } {
currentOffset_ := _linearize${d - 1}DArray(resultArray_, currentOffset_, mload(add(ptr_, mul(i, 32))), ${generateDimensionParams(d - 1, 1)})
}

offset_ := currentOffset_
}`;
helperFunctions += func;
}

return helperFunctions;
};

const maxDimension = Math.max(...signals.map(signal => signal.dimension.length));
-%>
function _linearizePubSignals(PubSignals memory publicSignals_) private pure returns (uint256[<%= IC.length - 1 %>] memory linearizedArray_) {
assembly {
let currentOffset := 0

function _linearizeUint(resultArray_, currentOffset_, valuePtr_) -> offset_ {
mstore(add(resultArray_, currentOffset_), mload(valuePtr_))
offset_ := add(currentOffset_, 32)
}<%- generateHelperFunctions(maxDimension) %><%
signals.forEach((signal, index) => {
const linearizationCode = generateLinearizationFunction(signal.name, signal.dimension, index * 32);
%>

// <%= signal.name %>
<%= linearizationCode %><%}); %>
}
}
}
77 changes: 75 additions & 2 deletions src/core/templates/verifier_groth16.vy.ejs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ DELTA_Y1: constant(uint256) = <%=vk_delta_2[1][1]%>
DELTA_Y2: constant(uint256) = <%=vk_delta_2[1][0] -%>


IC: constant(uint256[<%=IC.length%>][2]) = [
IC: constant(uint256[2][<%=IC.length%>]) = [
<% IC.forEach(function(innerArray, index) { %> [
<%= innerArray[0] %>,
<%= innerArray[1] %>
Expand All @@ -33,17 +33,90 @@ EC_ADD_PRECOMPILED_ADDRESS: constant(address) = 0x000000000000000000000000000000
EC_MUL_PRECOMPILED_ADDRESS: constant(address) = 0x0000000000000000000000000000000000000007
EC_PAIRING_PRECOMPILED_ADDRESS: constant(address) = 0x0000000000000000000000000000000000000008

<%function generateType(dimension) {
if (dimension.length === 0) {
return "uint256";
} else {
return "uint256" + dimension.map(d => `[${d}]`).join("");
}
}

const structFields = signals
.map(signal => {
return `\t${signal.name}: ${generateType(signal.dimension)}`
})
.join("\n");
-%>
struct PubSignals:
<%= structFields %>


@view
@external
def verifyProof(pointA: uint256[2], pointB: uint256[2][2], pointC: uint256[2], publicSignals: uint256[<%= IC.length - 1 %>]) -> bool:
return self._verifyProof(pointA, pointB, pointC, publicSignals)


@view
@external
def verifyProof(pointA: uint256[2], pointB: uint256[2][2], pointC: uint256[2], publicSignals: uint256[<%=IC.length-1%>]) -> bool:
def verifyProofWithStruct(pointA: uint256[2], pointB: uint256[2][2], pointC: uint256[2], publicSignals: PubSignals) -> bool:
return self._verifyProof(pointA, pointB, pointC, self._linearizePubSignals(publicSignals))


@view
@internal
def _verifyProof(pointA: uint256[2], pointB: uint256[2][2], pointC: uint256[2], publicSignals: uint256[<%= IC.length - 1 %>]) -> bool:
# @dev check that all public signals are in F
for signal: uint256 in publicSignals:
if signal >= BASE_FIELD_SIZE:
return False

return self._checkPairing(pointA, pointB, pointC, publicSignals)

<%
function generateLoops(dimensions, signalName, depth = 0, indices = []) {
let loopCode = '';
let indent = '\t'.repeat(depth + 1);
let currentIndex = `i_${depth}`;

if (depth < dimensions.length) {
loopCode += `${indent}for ${currentIndex}: uint256 in range(${dimensions[depth]}):\n`;

indices.push(currentIndex);

loopCode += generateLoops(dimensions, signalName, depth + 1, indices);
} else {
let accessExpression = indices.map(idx => `[${idx}]`).join('');

loopCode += `${indent}linearizedArray[idx] = publicSignals.${signalName}${accessExpression}\n`;
loopCode += `${indent}idx += 1\n`;
}

return loopCode;
}

let linearizeCode = "\tidx: uint256 = 0\n";
linearizeCode += `\tlinearizedArray: uint256[${nPublic}] = empty(uint256[${nPublic}])\n`;

for (let i = 0; i < signals.length; i++) {
linearizeCode += `\n\t# ${signals[i].name}\n`;

if (signals[i].dimension.length) {
linearizeCode += generateLoops(signals[i].dimension.reverse(), signals[i].name);
} else {
linearizeCode += `\tlinearizedArray[idx] = publicSignals.${signals[i].name}\n`;
linearizeCode += `\tidx += 1\n`;
}
}

linearizeCode += "\n\treturn linearizedArray";
-%>

@view
@internal
def _linearizePubSignals(publicSignals: PubSignals) -> uint256[<%= IC.length - 1 %>]:
<%= linearizeCode %>


@view
@internal
Expand Down
24 changes: 23 additions & 1 deletion src/types/circuit-zkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,28 @@ export type Calldata = [
PublicSignals,
];

export type CircuitArtifacts = {
circuitTemplateName: string;
circuitFileName: string;
circuitSourceName: string;
baseCircuitInfo: {
constraintsNumber: number;
signals: ArtifactSignal[];
};
};

export type ArtifactSignal = {
name: string;
dimension: string[];
type: string;
visibility: string;
};

export type PublicSignalInfo = {
name: string;
dimension: string[];
};

export type ProofStruct = {
proof: Groth16Proof;
publicSignals: PublicSignals;
Expand All @@ -27,7 +49,7 @@ export type ArrayLike = NumberLike[] | ArrayLike[];
export type Signal = NumberLike | ArrayLike;
export type Signals = Record<string, Signal>;

export type ArtifactsFileType = "r1cs" | "zkey" | "vkey" | "sym" | "json" | "wasm";
export type ArtifactsFileType = "r1cs" | "zkey" | "vkey" | "sym" | "constraints" | "artifacts" | "wasm";
export type VerifierProvingSystem = "groth16";
export type VerifierLanguageType = "sol" | "vy";

Expand Down
Loading
Loading