1
0
Fork 0
mirror of synced 2025-09-24 04:40:05 +00:00

revert promises, use wasm-pack from npm

This commit is contained in:
dark64 2022-01-12 14:04:37 +01:00
parent 7dd25c2945
commit 7ee1371d37
9 changed files with 304 additions and 162 deletions

View file

@ -145,6 +145,25 @@ jobs:
name: Run tests name: Run tests
no_output_timeout: "30m" no_output_timeout: "30m"
command: npm run test command: npm run test
zokrates_js_test2:
docker:
- image: circleci/python:latest-node
steps:
- checkout
- setup_remote_docker:
docker_layer_caching: true
- run:
no_output_timeout: "30m"
command: |
docker build -t zokrates_js -f zokrates_js/Dockerfile .
CID=$(docker create zokrates_js)
docker cp ${CID}:/build zokrates_js/dist
docker rm -f ${CID}
cd zokrates_js/dist
npm publish --dry-run
cross_build: cross_build:
parameters: parameters:
os: os:
@ -240,69 +259,70 @@ tag-only: &tag-only
workflows: workflows:
build-test-and-deploy: build-test-and-deploy:
jobs: jobs:
- build # - build
- test # - test
- cpp_format # - cpp_format
- wasm_test # - wasm_test
- integration_test # - integration_test
- zokrates_js_build - zokrates_js_build
- zokrates_js_test - zokrates_js_test
- cross_build: - zokrates_js_test2
<<: *tag-only # - cross_build:
pre-steps: # <<: *tag-only
- install_rust # pre-steps:
- install_cross # - install_rust
matrix: # - install_cross
alias: cross-build-linux # matrix:
parameters: # alias: cross-build-linux
os: # parameters:
- linux # os:
target: # - linux
- aarch64-unknown-linux-gnu # target:
- arm-unknown-linux-gnueabi # - aarch64-unknown-linux-gnu
- x86_64-unknown-linux-gnu # - arm-unknown-linux-gnueabi
- x86_64-pc-windows-gnu # - x86_64-unknown-linux-gnu
- cross_build: # - x86_64-pc-windows-gnu
<<: *tag-only # - cross_build:
pre-steps: # <<: *tag-only
- install_rust # pre-steps:
build-with: cargo # - install_rust
matrix: # build-with: cargo
alias: cross-build-macos # matrix:
parameters: # alias: cross-build-macos
os: # parameters:
- macos # os:
target: # - macos
- x86_64-apple-darwin # target:
- cross_build: # - x86_64-apple-darwin
<<: *tag-only # - cross_build:
pre-steps: # <<: *tag-only
- install_rust # pre-steps:
build-with: SDKROOT=$(xcrun -sdk macosx11.1 --show-sdk-path) MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx11.1 --show-sdk-platform-version) cargo # - install_rust
add-target: true # build-with: SDKROOT=$(xcrun -sdk macosx11.1 --show-sdk-path) MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx11.1 --show-sdk-platform-version) cargo
matrix: # add-target: true
alias: cross-build-apple-silicon # matrix:
parameters: # alias: cross-build-apple-silicon
os: # parameters:
- macos # os:
target: # - macos
- aarch64-apple-darwin # target:
- publish_artifacts: # - aarch64-apple-darwin
<<: *tag-only # - publish_artifacts:
requires: # <<: *tag-only
- cross-build-linux # requires:
- cross-build-macos # - cross-build-linux
- cross-build-apple-silicon # - cross-build-macos
- deploy: # - cross-build-apple-silicon
filters: # - deploy:
branches: # filters:
only: # branches:
- deploy # only:
requires: # - deploy
- build # requires:
- test # - build
- cpp_format # - test
- wasm_test # - cpp_format
- integration_test # - wasm_test
- zokrates_js_build # - integration_test
- zokrates_js_test # - zokrates_js_build
# - zokrates_js_test

View file

@ -32,13 +32,11 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain none -y \ RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- --default-toolchain none -y \
&& rustup toolchain install $RUST_VERSION --allow-downgrade --profile minimal --component rustfmt clippy \ && rustup toolchain install $RUST_VERSION --allow-downgrade --profile minimal --component rustfmt clippy \
&& cargo install --git https://github.com/rustwasm/wasm-pack \
&& rm -rf /usr/local/cargo/registry \
&& curl -sL https://deb.nodesource.com/setup_lts.x | bash - && apt-get install -y nodejs && npm i -g solc \ && curl -sL https://deb.nodesource.com/setup_lts.x | bash - && apt-get install -y nodejs && npm i -g solc \
&& curl -sL https://raw.githubusercontent.com/Sarcasm/run-clang-format/master/run-clang-format.py > /opt/run-clang-format.py \ && curl -sL https://raw.githubusercontent.com/Sarcasm/run-clang-format/master/run-clang-format.py > /opt/run-clang-format.py \
&& chmod +x /opt/run-clang-format.py \ && chmod +x /opt/run-clang-format.py \
&& ln -s /opt/run-clang-format.py /usr/bin \ && ln -s /opt/run-clang-format.py /usr/bin \
&& rustup --version; cargo --version; rustc --version; wasm-pack --version; echo nodejs $(node -v); && rustup --version; cargo --version; rustc --version; echo nodejs $(node -v);
RUN cd /opt && curl -LO https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-linux64.tar.gz \ RUN cd /opt && curl -LO https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-linux64.tar.gz \
&& tar -xzf geckodriver-v0.28.0-linux64.tar.gz geckodriver \ && tar -xzf geckodriver-v0.28.0-linux64.tar.gz geckodriver \

View file

@ -1,7 +1,7 @@
use crate::typed_absy::types::{ConcreteSignature, ConcreteType}; use crate::typed_absy::types::{ConcreteSignature, ConcreteType};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct AbiInput { pub struct AbiInput {
pub name: String, pub name: String,
pub public: bool, pub public: bool,
@ -11,7 +11,7 @@ pub struct AbiInput {
pub type AbiOutput = ConcreteType; pub type AbiOutput = ConcreteType;
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq)] #[derive(Serialize, Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct Abi { pub struct Abi {
pub inputs: Vec<AbiInput>, pub inputs: Vec<AbiInput>,
pub outputs: Vec<AbiOutput>, pub outputs: Vec<AbiOutput>,

View file

@ -64,12 +64,12 @@ declare module 'zokrates-js' {
} }
export interface ZoKratesProvider { export interface ZoKratesProvider {
compile(source: string, options?: CompileOptions): Promise<CompilationArtifacts>; compile(source: string, options?: CompileOptions): CompilationArtifacts;
setup(program: Uint8Array): Promise<SetupKeypair>; setup(program: Uint8Array): SetupKeypair;
computeWitness(artifacts: CompilationArtifacts, args: any[]): Promise<ComputationResult>; computeWitness(artifacts: CompilationArtifacts, args: any[]): ComputationResult;
exportSolidityVerifier(verificationKey: VerificationKey): Promise<string>; exportSolidityVerifier(verificationKey: VerificationKey): string;
generateProof(program: Uint8Array, witness: string, provingKey: Uint8Array): Promise<Proof>; generateProof(program: Uint8Array, witness: string, provingKey: Uint8Array): Proof;
verify(verificationKey: VerificationKey, proof: Proof): Promise<boolean>; verify(verificationKey: VerificationKey, proof: Proof): boolean;
} }
export interface Metadata { export interface Metadata {

View file

@ -306,6 +306,15 @@
"integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==", "integrity": "sha512-Wm6ukoaOGJi/73p/cl2GvLjTI5JM1k/O14isD73YML8StrH/7/lRFgmg8nICZgD3bZZvjwCGxtMOD3wWNAu8cg==",
"dev": true "dev": true
}, },
"axios": {
"version": "0.21.4",
"resolved": "https://registry.npmjs.org/axios/-/axios-0.21.4.tgz",
"integrity": "sha512-ut5vewkiu8jjGBdqpM44XxjuCjq9LAKeHVmoVfHVzy8eHgxxq8SbAVQNovDA8mVi05kP0Ea/n/UzcSHcTJQfNg==",
"dev": true,
"requires": {
"follow-redirects": "^1.14.0"
}
},
"bach": { "bach": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/bach/-/bach-1.2.0.tgz", "resolved": "https://registry.npmjs.org/bach/-/bach-1.2.0.tgz",
@ -390,6 +399,17 @@
"integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==", "integrity": "sha512-Un7MIEDdUC5gNpcGDV97op1Ywk748MpHcFTHoYs6qnj1Z3j7I53VG3nwZhKzoBZmbdRNnb6WRdFlwl7tSDuZGw==",
"dev": true "dev": true
}, },
"binary-install": {
"version": "0.1.1",
"resolved": "https://registry.npmjs.org/binary-install/-/binary-install-0.1.1.tgz",
"integrity": "sha512-DqED0D/6LrS+BHDkKn34vhRqOGjy5gTMgvYZsGK2TpNbdPuz4h+MRlNgGv5QBRd7pWq/jylM4eKNCizgAq3kNQ==",
"dev": true,
"requires": {
"axios": "^0.21.1",
"rimraf": "^3.0.2",
"tar": "^6.1.0"
}
},
"bindings": { "bindings": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz",
@ -624,6 +644,12 @@
} }
} }
}, },
"chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
"dev": true
},
"class-utils": { "class-utils": {
"version": "0.3.6", "version": "0.3.6",
"resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz", "resolved": "https://registry.npmjs.org/class-utils/-/class-utils-0.3.6.tgz",
@ -1463,6 +1489,12 @@
"readable-stream": "^2.3.6" "readable-stream": "^2.3.6"
} }
}, },
"follow-redirects": {
"version": "1.14.7",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.7.tgz",
"integrity": "sha512-+hbxoLbFMbRKDwohX8GkTataGqO6Jb7jGwpAlwgy2bIz25XtRm7KEzJM76R1WiNT5SwZkX4Y75SwBolkpmE7iQ==",
"dev": true
},
"for-in": { "for-in": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz", "resolved": "https://registry.npmjs.org/for-in/-/for-in-1.0.2.tgz",
@ -1487,6 +1519,15 @@
"map-cache": "^0.2.2" "map-cache": "^0.2.2"
} }
}, },
"fs-minipass": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
"dev": true,
"requires": {
"minipass": "^3.0.0"
}
},
"fs-mkdirp-stream": { "fs-mkdirp-stream": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz", "resolved": "https://registry.npmjs.org/fs-mkdirp-stream/-/fs-mkdirp-stream-1.0.0.tgz",
@ -2968,6 +3009,41 @@
"integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==", "integrity": "sha512-FM9nNUYrRBAELZQT3xeZQ7fmMOBg6nWNmJKTcgsJeaLstP/UODVpGsr5OhXhhXg6f+qtJ8uiZ+PUxkDWcgIXLw==",
"dev": true "dev": true
}, },
"minipass": {
"version": "3.1.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.1.6.tgz",
"integrity": "sha512-rty5kpw9/z8SX9dmxblFA6edItUmwJgMeYDZRrwlIVN27i8gysGbznJwUggw2V/FVqFSDdWy040ZPS811DYAqQ==",
"dev": true,
"requires": {
"yallist": "^4.0.0"
},
"dependencies": {
"yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true
}
}
},
"minizlib": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
"dev": true,
"requires": {
"minipass": "^3.0.0",
"yallist": "^4.0.0"
},
"dependencies": {
"yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true
}
}
},
"mixin-deep": { "mixin-deep": {
"version": "1.3.2", "version": "1.3.2",
"resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz", "resolved": "https://registry.npmjs.org/mixin-deep/-/mixin-deep-1.3.2.tgz",
@ -4498,6 +4574,34 @@
"es6-symbol": "^3.1.1" "es6-symbol": "^3.1.1"
} }
}, },
"tar": {
"version": "6.1.11",
"resolved": "https://registry.npmjs.org/tar/-/tar-6.1.11.tgz",
"integrity": "sha512-an/KZQzQUkZCkuoAA64hM92X0Urb6VpRhAFllDzz44U2mcD5scmT3zBc4VgVpkugF580+DQn8eAFSyoQt0tznA==",
"dev": true,
"requires": {
"chownr": "^2.0.0",
"fs-minipass": "^2.0.0",
"minipass": "^3.0.0",
"minizlib": "^2.1.1",
"mkdirp": "^1.0.3",
"yallist": "^4.0.0"
},
"dependencies": {
"mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
"dev": true
},
"yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"dev": true
}
}
},
"term-size": { "term-size": {
"version": "1.2.0", "version": "1.2.0",
"resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz", "resolved": "https://registry.npmjs.org/term-size/-/term-size-1.2.0.tgz",
@ -4837,6 +4941,15 @@
"vinyl": "^2.0.0" "vinyl": "^2.0.0"
} }
}, },
"wasm-pack": {
"version": "0.10.2",
"resolved": "https://registry.npmjs.org/wasm-pack/-/wasm-pack-0.10.2.tgz",
"integrity": "sha512-Kuh8XAArQNVoikMUenjDs4+g6LpktgfXgqlp03G2dJKDBokA7Y8Cx6MDCnvREzNnmprk9IohHytwycVSemwe/w==",
"dev": true,
"requires": {
"binary-install": "^0.1.0"
}
},
"which": { "which": {
"version": "1.3.1", "version": "1.3.1",
"resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz", "resolved": "https://registry.npmjs.org/which/-/which-1.3.1.tgz",

View file

@ -34,7 +34,8 @@
"clean-pkg": "rimraf pkg/README.md", "clean-pkg": "rimraf pkg/README.md",
"clean-node-pkg": "rimraf node/pkg/README.md", "clean-node-pkg": "rimraf node/pkg/README.md",
"pretest": "npm run setup && npm run build:node", "pretest": "npm run setup && npm run build:node",
"test": "mocha --require esm --recursive tests" "test": "npm run run-tests",
"run-tests": "mocha --require esm --recursive tests"
}, },
"devDependencies": { "devDependencies": {
"dree": "^2.6.1", "dree": "^2.6.1",
@ -45,7 +46,8 @@
"rimraf": "^3.0.2", "rimraf": "^3.0.2",
"serve": "^11.3.2", "serve": "^11.3.2",
"text-encoding": "^0.7.0", "text-encoding": "^0.7.0",
"toml": "^3.0.0" "toml": "^3.0.0",
"wasm-pack": "^0.10.2"
}, },
"dependencies": {} "dependencies": {}
} }

View file

@ -23,18 +23,18 @@ use zokrates_field::Bn128Field;
#[wasm_bindgen] #[wasm_bindgen]
pub struct CompilationResult { pub struct CompilationResult {
program: Vec<u8>, program: Vec<u8>,
abi: String, abi: Abi,
} }
#[wasm_bindgen] #[wasm_bindgen]
impl CompilationResult { impl CompilationResult {
pub fn get_program(&self) -> js_sys::Uint8Array { pub fn program(&self) -> js_sys::Uint8Array {
let arr = js_sys::Uint8Array::new_with_length(self.program.len() as u32); let arr = js_sys::Uint8Array::new_with_length(self.program.len() as u32);
arr.copy_from(&self.program); arr.copy_from(&self.program);
arr arr
} }
pub fn get_abi(&self) -> js_sys::JsString { pub fn abi(&self) -> JsValue {
js_sys::JsString::from(self.abi.as_str()) JsValue::from_serde(&self.abi).unwrap()
} }
} }
@ -142,7 +142,7 @@ pub fn compile(
})?; })?;
Ok(CompilationResult { Ok(CompilationResult {
abi: to_string_pretty(artifacts.abi()).unwrap(), abi: artifacts.abi().clone(),
program: serialize_program(artifacts.prog()), program: serialize_program(artifacts.prog()),
}) })
} }

View file

@ -12,103 +12,112 @@ describe('tests', function() {
}); });
describe("compilation", () => { describe("compilation", () => {
it('should compile', async function() { it('should compile', function() {
let result = await this.zokrates.compile("def main() -> field: return 42"); assert.doesNotThrow(() => {
assert.ok(result !== undefined); const artifacts = this.zokrates.compile("def main() -> field: return 42");
assert.ok(artifacts !== undefined);
})
}); });
it('should throw on invalid code', async function() { it('should throw on invalid code', function() {
return assert.rejects(() => this.zokrates.compile(":-)")); assert.throws(() => this.zokrates.compile(":-)"));
}); });
it('should resolve stdlib module', async function() { it('should resolve stdlib module', function() {
const stdlib = require('../stdlib.json'); const stdlib = require('../stdlib.json');
const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main(): return`; assert.doesNotThrow(() => {
return this.zokrates.compile(code); const code = `import "${Object.keys(stdlib)[0]}" as func\ndef main(): return`;
this.zokrates.compile(code);
});
}); });
it('should resolve user module', async function() { it('should resolve user module', function() {
const code = 'import "test" as test\ndef main() -> field: return test()'; assert.doesNotThrow(() => {
const options = {
resolveCallback: (_, path) => {
return {
source: "def main() -> (field): return 1",
location: path
}
}
};
return this.zokrates.compile(code, options);
});
it('should throw on unresolved module', async function() {
return assert.rejects(() => {
const code = 'import "test" as test\ndef main() -> field: return test()'; const code = 'import "test" as test\ndef main() -> field: return test()';
return this.zokrates.compile(code); const options = {
resolveCallback: (_, path) => {
return {
source: "def main() -> (field): return 1",
location: path
}
}
};
this.zokrates.compile(code, options);
});
});
it('should throw on unresolved module', function() {
assert.throws(() => {
const code = 'import "test" as test\ndef main() -> field: return test()';
this.zokrates.compile(code);
}); });
}); });
}); });
describe("computation", () => { describe("computation", () => {
it('should compute with valid inputs', async function() { it('should compute with valid inputs', function() {
const code = 'def main(private field a) -> field: return a * a'; assert.doesNotThrow(() => {
const artifacts = await this.zokrates.compile(code);
const result = await this.zokrates.computeWitness(artifacts, ["2"]);
const output = JSON.parse(result.output);
assert.deepEqual(output, ["4"]);
});
it('should throw on invalid input count', async function() {
return assert.rejects(async () => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
return this.zokrates.computeWitness(artifacts, ["1", "2"]); const result = this.zokrates.computeWitness(artifacts, ["2"]);
const output = JSON.parse(result.output);
assert.deepEqual(output, ["4"]);
}); });
}); });
it('should throw on invalid input type', async function() { it('should throw on invalid input count', function() {
return assert.rejects(async () => { assert.throws(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
return this.zokrates.computeWitness(artifacts, [true]); this.zokrates.computeWitness(artifacts, ["1", "2"]);
});
});
it('should throw on invalid input type', function() {
assert.throws(() => {
const code = 'def main(private field a) -> field: return a * a';
const artifacts = this.zokrates.compile(code);
this.zokrates.computeWitness(artifacts, [true]);
}); });
}); });
}); });
describe("setup", () => { describe("setup", () => {
it('should run setup', async function() { it('should run setup', function() {
return assert.doesNotReject(async () => { assert.doesNotThrow(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
return this.zokrates.setup(artifacts.program); this.zokrates.setup(artifacts.program);
}); });
}); });
}); });
describe("export-verifier", () => { describe("export-verifier", () => {
it('should export solidity verifier', async function() { it('should export solidity verifier', function() {
return assert.doesNotReject(async () => { assert.doesNotThrow(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
const keypair = await this.zokrates.setup(artifacts.program); const keypair = this.zokrates.setup(artifacts.program);
const verifier = await this.zokrates.exportSolidityVerifier(keypair.vk); const verifier = this.zokrates.exportSolidityVerifier(keypair.vk);
assert.ok(verifier.length > 0); assert.ok(verifier.length > 0);
}); });
}); });
}); });
describe("generate-proof", () => { describe("generate-proof", () => {
it('should generate proof', async function() { it('should generate proof', function() {
return assert.doesNotReject(async () => { assert.doesNotThrow(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
const computationResult = await this.zokrates.computeWitness(artifacts, ["2"]) const computationResult = this.zokrates.computeWitness(artifacts, ["2"])
const keypair = await this.zokrates.setup(artifacts.program); const keypair = this.zokrates.setup(artifacts.program);
const proof = await this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk); const proof = this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk);
assert.ok(proof !== undefined); assert.ok(proof !== undefined);
assert.deepEqual(proof.inputs, ["0x0000000000000000000000000000000000000000000000000000000000000004"]); assert.deepEqual(proof.inputs, ["0x0000000000000000000000000000000000000000000000000000000000000004"]);
@ -117,29 +126,29 @@ describe('tests', function() {
}); });
describe("verify", () => { describe("verify", () => {
it('should pass', async function() { it('should pass', function() {
return assert.doesNotReject(async () => { assert.doesNotThrow(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
const computationResult = await this.zokrates.computeWitness(artifacts, ["2"]) const computationResult = this.zokrates.computeWitness(artifacts, ["2"])
const keypair = await this.zokrates.setup(artifacts.program); const keypair = this.zokrates.setup(artifacts.program);
const proof = await this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk); const proof = this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk);
assert(await this.zokrates.verify(keypair.vk, proof) == true); assert(this.zokrates.verify(keypair.vk, proof) == true);
}) })
}); });
it('should fail', async function() { it('should fail', function() {
return assert.doesNotReject(async () => { assert.doesNotThrow(() => {
const code = 'def main(private field a) -> field: return a * a'; const code = 'def main(private field a) -> field: return a * a';
const artifacts = await this.zokrates.compile(code); const artifacts = this.zokrates.compile(code);
const computationResult = await this.zokrates.computeWitness(artifacts, ["2"]) const computationResult = this.zokrates.computeWitness(artifacts, ["2"])
const keypair = await this.zokrates.setup(artifacts.program); const keypair = this.zokrates.setup(artifacts.program);
let proof = await this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk); let proof = this.zokrates.generateProof(artifacts.program, computationResult.witness, keypair.pk);
// falsify proof // falsify proof
proof["proof"]["a"][0] = "0x0000000000000000000000000000000000000000000000000000000000000000"; proof["proof"]["a"][0] = "0x0000000000000000000000000000000000000000000000000000000000000000";
assert(await this.zokrates.verify(keypair.vk, proof) == false); assert(this.zokrates.verify(keypair.vk, proof) == false);
}) })
}); });
}); });

View file

@ -35,35 +35,35 @@ module.exports = (dep) => {
} }
return { return {
compile: async (source, options = {}) => { compile: (source, options = {}) => {
const { location = "main.zok", resolveCallback = () => null, config = {} } = options; const { location = "main.zok", resolveCallback = () => null, config = {} } = options;
const callback = (currentLocation, importLocation) => { const callback = (currentLocation, importLocation) => {
return resolveFromStdlib(currentLocation, importLocation) || resolveCallback(currentLocation, importLocation); return resolveFromStdlib(currentLocation, importLocation) || resolveCallback(currentLocation, importLocation);
}; };
const ptr = zokrates.compile(source, location, callback, config); const ptr = zokrates.compile(source, location, callback, config);
return { return {
program: ptr.get_program(), program: ptr.program(),
abi: JSON.parse(ptr.get_abi()) abi: ptr.abi()
} }
}, },
setup: async (program) => { setup: (program) => {
const { vk, pk } = zokrates.setup(program); const { vk, pk } = zokrates.setup(program);
return { return {
vk, vk,
pk: new Uint8Array(pk) pk: new Uint8Array(pk)
}; };
}, },
computeWitness: async (artifacts, args) => { computeWitness: (artifacts, args) => {
const { program, abi } = artifacts; const { program, abi } = artifacts;
return zokrates.compute_witness(program, abi, JSON.stringify(Array.from(args))); return zokrates.compute_witness(program, abi, JSON.stringify(Array.from(args)));
}, },
exportSolidityVerifier: async (verificationKey) => { exportSolidityVerifier: (verificationKey) => {
return zokrates.export_solidity_verifier(verificationKey); return zokrates.export_solidity_verifier(verificationKey);
}, },
generateProof: async (program, witness, provingKey) => { generateProof: (program, witness, provingKey) => {
return zokrates.generate_proof(program, witness, provingKey); return zokrates.generate_proof(program, witness, provingKey);
}, },
verify: async (verificationKey, proof) => { verify: (verificationKey, proof) => {
return zokrates.verify(verificationKey, proof); return zokrates.verify(verificationKey, proof);
} }
} }