Skip to content

Commit

Permalink
Merging ScalarStore and LightStore into ZStore #351 (#364)
Browse files Browse the repository at this point in the history
* separating Poseidon hashing into it's own module

* move pointer types, traits, methods from store.rs to ptr.rs

* move Expression/Continuation to expr.rs and cont.rs, respectively

* refactor Ptr representation

* update subcrates

* fix ptr equality

* remove no longer meaningful test in opaque_sym

* fix benches

* cargo clippy

* rename LightData -> ZData

* ZCont, ZExpr, ZPtr

* Renamed ScalarPtr to ZExprPtr, etc

* add new ZExpr variants with TODOs on implementation

* Removing ScalarStore from z_data

* ZStore now uses ZEntry instead of an Option

* Removed ScalarStore from Store

* ZExpr Encodable

* ZCont and ZExpr Encodable

* fix warnings

* fix fcomm

* z_store Encodable

* fix merge src/ptr.rs

* fix merge src/store.rs

* fix test

* warnings

* add z_ptr hashing functions

* stubbed get_z_expr

* some progress in 'get_z_expr'

* Small bug fixes

* add some function stubs

* Added intern_z_expr_ptr

* Added intern_z_cont_ptr

* remove scalar_store, refactor hashing, with stubs

* fixup merge

* put_z_strs and put_z_chars

* interning strings and symbols

* Progress on `intern_symcons`

* Small bugfix

* `to_store` finished

* cleanup and document

* cachemap

* update Cargo

* add ZCont::Call0

* refactor z modules

* None case for continuations

* implement conversions

* nil_z_ptr and related changes

* fix z_cont serialization

* Expression SymCons/StrCons with stubs

* Expression SymCons & StrCons progress

* fill todos

* reduce warnings

* rest of the warnings

* fmt; fix nil sym check; use poseidon cache to get nil ptr

* implement is_keyword_sym

* Jcb/nom and syntax (#383)

* preparation for nom parser and syntax

* syntax Display and Arbitrary

* syntax interning

* fix errors in src/eval/tests/mod.rs

* fix lang.rs

* fixing build; fixed 'sym_in_list' test

* add syntax_macros.rs

* fix macros

* more fixes

* added LurkSym enum for built-ins

* more parser infrastructure

* some fixes in the store tests

* credit FrozenMap; remove lurk_sym.rs; add dummy LurkSym

* populate z_expr_ptr_map when get_z_expr is called

* fix infinite loop when fetching keys

* remove writing test from eval tests file; add a writer test case

* `fetch_syntax` completed

* draft of parser

* `fetch_syntax` update

* Removed unused modules plus small fixes

* Fixed fetch functions related to symbol

* Finished `write_symbol`

* syntax parser

* Better `syntax.rs` tests

* parser/printer now passing proptest roundtrip

* Updated the repl to use new parser

* solved conflicts

* Static whitespace array and bug fix

* syntax_full_roundtrip proptest

* Fixed some opaque tests

There was a reordering of matches in part of the evaluator. Instead of
fetching the pointers and then checking the operator, the opposite is
done so that we won't need to fetch opaque pointers in `equal` and
`cons` cases

* Serde refactor (WIP)

* Fmt and clippy

* Build the tests

* fix opaque sym test

* hunt down misplaced '.sym(' occurrences

* fix some uppercasing

* use cache maps for poseidon cache

* Added parser for meta commands

* fmt; try to mitigate sources of bugs

* John's fix for 'get_sym'

* Added old char syntax and changed root symbol syntax

* ZData serialization

* fix hash char parser/printer, and solve some failing tests

* improve parse_list syntax, fix more tests

* fix more tests

* Refactor methods

* fix char coercion

* More test fixes

* add minimal failing test for lambdas with empty lists of arguments

* implement negative number and fraction syntax

* fix number of iterations

* Test serializer and create z_data nested modules

* fix hashing for functions

* Fixed `intern_z_cont_ptr`

* fix Call and Call2 argument orders

* Add deserializer (WIP)

* Add compound deserialization types, rustfmt

* Finish deserializer for compound types

* Fixed repl

* Fixed doc tests and `fetch_strcons`

* Fix ZExpr deserialization, roundtrip tests

* lowercase fcomm proof_tests

* get clutch building with todos

* Parser simplification

* Clippy

* Use ZExprPtr as Nova proof cache key

* Revert to canonical FWrap serialization

* Finish Nova proof key, fix proptest stack overflow

* Remove Encodable instances in favor of ZData serde

* Clippy

* Format proof key as base32, fix clutch tests

* resolve review comments

* remove unused dependencies

* Iterative version of `get_z_expr`

* remove bad opaque dereference

* disable makefile_tests which are broken on master

* add TODOs for opaque dereference

* small error message improvement

* replace some unwraps with expects

* some temporary debugs and printing shims

* Add minimal chained fcomm unit tests

* Proptest fcomm types into oblivion

* Use latest Nova for serde fix

* Fix chained fcomm test

* Cleanup & fix Wasm build

* fmt

* docs: Improve pull request merge guidelines (#418)

- Update CONTRIBUTING.md to enhance clarity on merge criteria
- Revise workflow diagram with accurate naming

* test: Add a test for enforce_implication_lc (#419)

* test: Add a test for enforce_implication_lc

- Add a new test for enforce_implication_lc function in constraints.rs

* test: Improve test coverage for enforce_implication_lc

- Add edge case test for enforce_implication_lc
- documented behavior with non-boolean nums

* chore: Less cloning (#420)

* refactor: Avoid unnecessary cloning of lang parameter

- Update multiframes creation to take a reference
- Add derive traits to HashArity enum in hash.rs for better usability

* refactor: Reduce cloning in LEM

- Enhance duplicate key error message in interpreter.rs to not need a clone
- Modify parameter type for `deconflict` function and its calls in mod.rs
- modification of helper functions in Symbol inspired by [C-CALLER-CONTROL](https://rust-lang.github.io/api-guidelines/flexibility.html#caller-decides-where-to-copy-and-place-data-c-caller-control)

* refactor: remove uneeded clones in circuit_frame

- take by reference where possible (and easy)

* Rectify language fields (#423)

* Assign correct FIELD.

* Use obviously-identifying Scalar type aliases.

* Correct fields and use obvious aliases.

* Document field names.

---------

Co-authored-by: porcuquine <[email protected]>

* Fix new_with_expr conversion to ZStore

* Fix commitment roundtrip test

* fix automatic conversion from string and string slices to symbol

* solve issue of pointer not found on syntax full roundtrip

* fix syntax full roundtrip test

* Fix lurk_tests with updated lurk-lib

* Rustfmt

* Revert to Nova 0.21.0

* Fix license formatting (#439)

* Fix branch comparison, remove unneeded permissions (#440)

* ci: make checkouts recursive (#442)

- Enable recursive submodule checkout for test, clippy, and rustfmt jobs

* Issue426 (#432)

* Include failing test for issue 426

* Minimum failing test

* Fixed circuit eval

* Issue 424 and 426 tests

* Issue 426 solved

* Issue 424 modified works

Maybe we shouldn't support inner letrecs, and only a single top level
letrec should be allowed.

* Minimal example

* fmt

---------

Co-authored-by: Gabriel Barreto <[email protected]>
Co-authored-by: Arthur Paulino <[email protected]>

* More clippy tuning (#441)

* Clippy 1.70

* style: Improve Clippy settings across multiple directories

- Introduce new `.clippy.toml` files for clutch, fcomm, and lurk-macros directories
- Create and configure a global `.clippy.toml` file with custom settings
- Establish `disallowed-methods` for `pasta_curves::Fp` and `pasta_curves::Fq`

* Fix head ref in benchmark action (#443)

* update flake.nix

* Add GPU test on PR merge (#444)

* Add GPU test on PR merge

* Add GPU options

* cleaner fetch_syntax_list

* comments

* add rust-analyzer to flake

* fetch_syntax_list comment

* remove double path clone in Symbol::extend

* small improvements on ZStore::get_expr and ZStore::new_with_expr

* resolve TODO remove child_z_ptrs

* fix unwrap on ZStore::insert_expr

* add back z_expr_ptr_from_parts z_cont_ptr_from_parts convenience functions

* fix cont.rs Call arg order typo

* fix u32->char conversion to allow for u32 values which are not Unicode codepoints to be Lurk chars

* clippy

* lowercase package symbols

* parser comments and fixes

* rename StrCons/StrNil, SymCons/SymNil to Str/EmptyStr, Sym/RootSym

* remove outdated comment

* improve parser::base::is_digit

* address LurkSym feedback

* revove unused store arg

* clippy

* ci: add action for signaling rebases on upstream (#448)

* `let` and `letrec` fix (#446)

* Include failing test for issue 426

* Minimum failing test

* Fixed circuit eval

* Issue 424 and 426 tests

* Issue 426 solved

* Issue 424 modified works

Maybe we shouldn't support inner letrecs, and only a single top level
letrec should be allowed.

* Fixed circuit bugs in both `let` and `letrec` cases

* Fixed `let` and `letrec` conflicts

* Removed unnecessary tests

* cargo fmt

* Fixed number of constraints

* Fixed flake.nix

* Added tests back

* Addressed the change requests

* Better tests

---------

Co-authored-by: emmorais <[email protected]>

* Optimize ci (#450)

* ci: Add dependeabot config for GH Actions

- Introduce new dependabot.yml configuration
- Implement weekly updates for GitHub Actions

* ci: fix issue creation in upstream_update

- Improve accuracy of condition checks in upstream_update.yml workflow

* ci: Refactor GPU tests and workflows in rust.yml

- Consolidate test-gpu job by merging CUDA and OpenCL tests
- Rename test-cuda job to test-gpu for clarity
- Set EC_GPU_FRAMEWORK as an environment variable for GPU tests

* chore(deps): bump actions/checkout from 2 to 3 (#454)

Bumps [actions/checkout](https://github.com/actions/checkout) from 2 to 3.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](actions/checkout@v2...v3)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Clean unused actions + Updates (#457)

* ci: remove unused epics-action

* chore(deps): bump lycheeverse/lychee-action from 1.5.4 to 1.8.0

Bumps [lycheeverse/lychee-action](https://github.com/lycheeverse/lychee-action) from 1.5.4 to 1.8.0.
- [Release notes](https://github.com/lycheeverse/lychee-action/releases)
- [Commits](lycheeverse/lychee-action@v1.5.4...v1.8.0)

---
updated-dependencies:
- dependency-name: lycheeverse/lychee-action
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): bump peter-evans/create-or-update-comment from 1 to 3

Bumps [peter-evans/create-or-update-comment](https://github.com/peter-evans/create-or-update-comment) from 1 to 3.
- [Release notes](https://github.com/peter-evans/create-or-update-comment/releases)
- [Commits](peter-evans/create-or-update-comment@v1...v3)

---
updated-dependencies:
- dependency-name: peter-evans/create-or-update-comment
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>

* chore(deps): bump peter-evans/close-issue from 2 to 3

Bumps [peter-evans/close-issue](https://github.com/peter-evans/close-issue) from 2 to 3.
- [Release notes](https://github.com/peter-evans/close-issue/releases)
- [Commits](peter-evans/close-issue@v2...v3)

---
updated-dependencies:
- dependency-name: peter-evans/close-issue
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* ci: clean up unused job (#461)

* ci: merge rustfmt, clippy

* ci: remove unused workflow

* refactor parser to use ParseResult

* change Keyword representation to keycons

- also rename fetch_scalar in src/store

* improve ZExpr::from_ptr

* remove outdated comment

* improve parser::error

* clippy

* cleanup fraction example

* ptr comments

* rewrite fetch_string

* clippy

* ZData docstrings & serde fixup

* fix a symbol.rs docstring; avoid unnecessary clone on Symbol::path; recover Symbol::parent and Symbol::child APIs

* symbol.rs tests cleanup

* Update ZData tests

* Cleanup & rename scalar_ptr to z_ptr

* include minimized test case error

* fmt

* address some review suggestions

* implement cache hits when interning strings

* further optimize 'intern_string'

* undo change on public parameters

* add some documentation; fix failing proptests (thanks to Sam)

* simplify symbol_cache

* recover recursive expr hashing and add hashing caches

* move None case to the bottom in 'get_z_expr'

* Fix ZStore roundtrip in get_z_expr

* refactor Symbol and Keyword representation

* clippy

* remove unused package.rs

* some cosmetic changes; improve some docstrings

* remove outdated tests for zdata

* add some extra test cases for src/parser/syntar.rs

* fmt

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: Gabriel Barreto <[email protected]>
Co-authored-by: Arthur Paulino <[email protected]>
Co-authored-by: Samuel Burnham <[email protected]>
Co-authored-by: Samuel Burnham <[email protected]>
Co-authored-by: François Garillot <[email protected]>
Co-authored-by: porcuquine <[email protected]>
Co-authored-by: porcuquine <[email protected]>
Co-authored-by: Eduardo Morais <[email protected]>
Co-authored-by: emmorais <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
  • Loading branch information
11 people authored Jul 4, 2023
1 parent 3288fe5 commit 57dfee0
Show file tree
Hide file tree
Showing 69 changed files with 7,658 additions and 5,512 deletions.
325 changes: 44 additions & 281 deletions Cargo.lock

Large diffs are not rendered by default.

9 changes: 4 additions & 5 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,24 @@ rust-version = "1.68.2"
ahash = "0.7.6"
anyhow = { workspace = true }
anymap = "0.12.1"
base32ct = { version = "0.2.0", features = ["std"] }
base64 = { workspace = true }
base-x = "0.2.11"
bellperson = { workspace = true }
bincode = "1.3.3"
blstrs = { workspace = true }
cid = { version = "0.8.6", default-features = false, features = ["alloc", "serde-codec"] }
clap = "4.1.8"
dashmap = "5.4.0"
ff = { workspace = true }
generic-array = "0.14.6"
hex = { version = "0.4.3", features = ["serde"] }
indexmap = { version = "1.9.2", features = ["rayon"] }
itertools = "0.9"
libipld = { workspace = true, default-features = false, features = ["dag-cbor", "dag-json", "serde-codec"] }
log = { workspace = true }
lurk-macros = { path = "lurk-macros" }
multihash = { version = "0.16.3", features = ["alloc", "blake3"] }
neptune = { workspace = true, features = ["arity2","arity4","arity8","arity16","pasta","bls"] }
nom = "7.1.3"
nom_locate = "4.1.0"
nova = { workspace = true, default-features = false }
num-bigint = "0.4.3"
num-integer = "0.1.45"
Expand All @@ -48,8 +48,8 @@ rustyline-derive = "0.8.0"
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
serde_repr = "0.1.10"
string-interner = "0.14.0"
tap = "1.0.1"
stable_deref_trait = "1.1.1"
thiserror = { workspace = true }

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
Expand Down Expand Up @@ -98,7 +98,6 @@ bellperson = "0.25"
blstrs = "0.7.0"
# TODO: clap
ff = "0.13"
libipld = { package = "lurk-ipld", version = "0.3.0", default-features = false }
log = "0.4.17"
neptune = { version = "10.0.0" }
nova = { package = "nova-snark", version = "0.21", default-features = false }
Expand Down
2 changes: 1 addition & 1 deletion benches/end2end.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,7 @@ cfg_if::cfg_if! {
}
}

// To run these benchmarks, first download `criterion` with `cargo install cargo install cargo-criterion`.
// To run these benchmarks, first download `criterion` with `cargo install cargo-criterion`.
// Then `cargo criterion --bench end2end`. The results are located in `target/criterion/data/<name-of-benchmark>`.
// For flamegraphs, run `cargo criterion --bench end2end --features flamegraph -- --profile-time <secs>`.
// The results are located in `target/criterion/profile/<name-of-benchmark>`.
Expand Down
1 change: 1 addition & 0 deletions clutch/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ repository = "https://github.com/lurk-lab/lurk-rs"
anyhow = { workspace = true }
blstrs = { workspace = true }
clap = "4.1.8"
ff = "0.13"
lurk = { path = "../" }
pasta_curves = { workspace = true, features = ["repr-c", "serde"] }
pretty_env_logger = "0.4"
Expand Down
12 changes: 6 additions & 6 deletions clutch/demo/chained-functional-commitment.lurk
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

;; We chain a next commitment by applying the committed function to a value of 9.

!(chain 0x3ce3d2df00eb623965384c5b57e162221eb984065eadb19f9daa3190afdcb121 9)
!(chain 0x2da6ae5854eb3055c31cbcd632f4d833a2a73fae5f5be4ee20fad3100285a28a 9)

;; The new counter value is 9, and the function returns a new functional commitment.

Expand All @@ -21,11 +21,11 @@

;; We can verify the proof.

!(verify "bafkr4ienz7ksx2kmv35vrdr5ptfr7ng3zrylkicr3b5b6c5b7nkdnidfwq")
!(verify "aeaaz7gfwqsj6ggbokebnnt2in5kjg3jugzie5hafonednmjnfqvw5iya")

;; Now let's chain another call to the new head, adding 12 to the counter.

!(chain 0x16e909ae4e83b4fc29faa8e8dad0a90f301cf99fd2a1329f6cec685b81d1091a 12)
!(chain 0x30773603a363eac816a6e6e80e39c8eda0342635ffeb63e9c2412e3d3fb4da5b 12)

;; Now the counter is 21, and we have a new head commitment.

Expand All @@ -35,11 +35,11 @@

;; And verify.

!(verify "bafkr4iawd7nchejy73jdhg6ua4aji4nsfllnkgac3exm5jmicpfowjbh7u")
!(verify "aeaazi2visjk4l2zouuyjafvxwg7jfmpoad43gc3foikulipxdir5iila")

;; One more time, we'll add 14 to the head commitment's internal state.

!(chain 0x1f9c18bdabf909167df079312b1921010ec5250aa352195ded4eaf6a2aa9c66e 14)
!(chain 0x0d628d7c6def025fe258334476b4950cfac1f86cadc68c06497aaee27f208532 14)

;; 21 + 14 = 35, as expected.

Expand All @@ -49,7 +49,7 @@

;; Verify.

!(verify "bafkr4ie7xnlqlaoqpg63d3nbtgw2qsj3uae23v7tyngkfl2rkguaxvezga")
!(verify "aeaazlu4pjff7qo64jbsemqzlfonmbaqnnzkl2x7dbdtfg7xxboxtwikq")

;; Repeat indefinitely.

Expand Down
10 changes: 5 additions & 5 deletions clutch/demo/functional-commitment.lurk
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,24 @@

;; We open the functional commitment on input 5: Evaluate f(5).

!(call 0x396e9cd726a3c323ad1ec3a7651da94bc08c2d7baa68211186101d3735fb31d3 5)
!(call 0x3238c07bcc3c57b7466ee2370571a7cb862368036943abf41e956aa7f95bcd3d 5)

;; We can prove the functional-commitment opening.

!(prove)

;; We can inspect the input expression that was proved.

!(proof-in-expr "bafkr4icba2o33x7tupuu7p6a5jdtsohreiyn6qfa3d4swa4nqo2urr6vgq")
!(proof-in-expr "aeaaztyfm7bd3zry22nwpqxa3b5tvanwdn3jtpd7lqy64ycjjn3ydgefq")

;; And also the output expression.

!(proof-out-expr "bafkr4icba2o33x7tupuu7p6a5jdtsohreiyn6qfa3d4swa4nqo2urr6vgq")
!(proof-out-expr "aeaaztyfm7bd3zry22nwpqxa3b5tvanwdn3jtpd7lqy64ycjjn3ydgefq")

;; We can also see exactly what we claim to have proved.

!(proof-claim "bafkr4icba2o33x7tupuu7p6a5jdtsohreiyn6qfa3d4swa4nqo2urr6vgq")
!(proof-claim "aeaaztyfm7bd3zry22nwpqxa3b5tvanwdn3jtpd7lqy64ycjjn3ydgefq")

;; Finally, and most importantly, we can verify the proof.

!(verify "bafkr4icba2o33x7tupuu7p6a5jdtsohreiyn6qfa3d4swa4nqo2urr6vgq")
!(verify "aeaaztyfm7bd3zry22nwpqxa3b5tvanwdn3jtpd7lqy64ycjjn3ydgefq")
93 changes: 44 additions & 49 deletions clutch/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
#![doc = include_str!("../README.md")]

use anyhow::{anyhow, bail, Context, Result};
use anyhow::{anyhow, bail, Context, Error, Result};
use clap::{Arg, ArgAction, Command};
use lurk::public_parameters::{
public_params, Claim, Commitment, CommittedExpression, CommittedExpressionMap, Id, LurkCont,
public_params, Claim, Commitment, CommittedExpression, CommittedExpressionMap, LurkCont,
LurkPtr, NovaProofCache, Opening, Proof, PtrEvaluation,
};
use pasta_curves::pallas;
Expand All @@ -15,12 +15,11 @@ use lurk::eval::{
};
use lurk::expr::Expression;
use lurk::field::LurkField;
use lurk::package::Package;
use lurk::proof::{nova::NovaProver, Prover};
use lurk::ptr::Ptr;
use lurk::repl::{ReplState, ReplTrait};
use lurk::store::Store;
use lurk::sym::Sym;
use lurk::symbol::Symbol;
use lurk::tag::ExprTag;
use lurk::writer::Write;

Expand Down Expand Up @@ -193,31 +192,35 @@ impl ReplTrait<F, Coproc<F>> for ClutchState<F, Coproc<F>> {
&mut self,
store: &mut Store<F>,
expr_ptr: Ptr<F>,
package: &Package,
p: P,
) -> Result<()> {
let expr = store.fetch(&expr_ptr).unwrap();

macro_rules! delegate {
() => {
self.repl_state.handle_meta(store, expr_ptr, package, p)
self.repl_state.handle_meta(store, expr_ptr, p)
};
}

let res: Option<Ptr<F>> = match expr {
Expression::Cons(car, rest) => match &store.fetch(&car).unwrap() {
Expression::Sym(Sym::Sym(s)) => match s.name().as_str() {
"CALL" => self.call(store, rest)?,
"CHAIN" => self.chain(store, rest)?,
"COMMIT" => self.commit(store, rest)?,
"OPEN" => self.open(store, rest)?,
"PROOF-IN-EXPR" => self.proof_in_expr(store, rest)?,
"PROOF-OUT-EXPR" => self.proof_out_expr(store, rest)?,
"PROOF-CLAIM" => self.proof_claim(store, rest)?,
"PROVE" => self.prove(store, rest)?,
"VERIFY" => self.verify(store, rest)?,
_ => return delegate!(),
},
Expression::Sym(_, _) => {
let s: Symbol = store
.fetch_sym(&car)
.ok_or(Error::msg("handle_meta fetch symbol"))?;
match format!("{}", s).as_str() {
"call" => self.call(store, rest)?,
"chain" => self.chain(store, rest)?,
"lurk.commit" => self.commit(store, rest)?,
"lurk.open" => self.open(store, rest)?,
"proof-in-expr" => self.proof_in_expr(store, rest)?,
"proof-out-expr" => self.proof_out_expr(store, rest)?,
"proof-claim" => self.proof_claim(store, rest)?,
"prove" => self.prove(store, rest)?,
"verify" => self.verify(store, rest)?,
_ => return delegate!(),
}
}
Expression::Comm(_, c) => {
// NOTE: this cannot happen from a text-based REPL, since there is not currrently a literal Comm syntax.
self.apply_comm(store, *c, rest)?
Expand Down Expand Up @@ -286,7 +289,7 @@ impl ClutchState<F, Coproc<F>> {

let (expr, secret) = if rest.is_nil() {
// TODO: also support Commitment::from_ptr_with_hiding (randomized secret at runtime).
(first, F::zero())
(first, <F as ff::Field>::ZERO)
} else if let Expression::Num(n) = store
.fetch(&second)
.ok_or_else(|| anyhow!("second arg to !:COMMIT must be a number."))?
Expand All @@ -298,7 +301,7 @@ impl ClutchState<F, Coproc<F>> {

let (evaled, _, _, _) = self.repl_state.eval_expr(expr, store)?;

let commitment = Commitment::from_ptr_and_secret(store, &evaled, secret);
let commitment = Commitment::from_ptr_and_secret(store, &evaled, secret)?;

let committed_expression = CommittedExpression {
expr: LurkPtr::from_ptr(store, &evaled),
Expand Down Expand Up @@ -341,7 +344,7 @@ impl ClutchState<F, Coproc<F>> {
.ok_or_else(|| anyhow!("secret missing"))
.and_then(|hash| {
store
.get_expr_hash(&hash)
.hash_expr(&hash)
.ok_or_else(|| anyhow!("hash missing"))
})
.map(|hash| *hash.value())?;
Expand All @@ -350,7 +353,7 @@ impl ClutchState<F, Coproc<F>> {
.open(new_comm)
.ok_or_else(|| anyhow!("opening missing"))?;

let new_commitment = Commitment::from_comm(store, &new_comm);
let new_commitment = Commitment::from_comm(store, &new_comm)?;

let expr = LurkPtr::from_ptr(store, &new_fun);

Expand Down Expand Up @@ -387,7 +390,7 @@ impl ClutchState<F, Coproc<F>> {

let (output, new_commitment) = if chain {
let (output, new_comm) = store.car_cdr(&result)?;
(output, Some(Commitment::from_comm(store, &new_comm)))
(output, Some(Commitment::from_comm(store, &new_comm)?))
} else {
(result, None)
};
Expand Down Expand Up @@ -427,7 +430,7 @@ impl ClutchState<F, Coproc<F>> {
}
};

let commitment = Commitment::from_comm(store, &comm);
let commitment = Commitment::from_comm(store, &comm)?;

if let Ok((_secret, value)) = store.open_mut(maybe_comm) {
return Ok((commitment, Some(value)));
Expand Down Expand Up @@ -476,19 +479,13 @@ impl ClutchState<F, Coproc<F>> {

fn get_proof(&self, store: &mut Store<F>, rest: Ptr<F>) -> Result<Proof<F>> {
let (proof_cid, _rest1) = store.car_cdr(&rest)?;
let cid_string = if let Expression::Str(p) = store
.fetch(&proof_cid)
.ok_or_else(|| anyhow!("failed to fetch cid string"))?
{
p.to_string()
} else {
bail!("proof cid must be a string");
};
let zptr_string = store
.fetch_string(&proof_cid)
.ok_or_else(|| anyhow!("proof cid must be a string"))?;

let cid = lurk::public_parameters::cid_from_string(&cid_string)?;
self.proof_map
.get(&cid)
.ok_or_else(|| anyhow!("proof not found: {cid}"))
.get(&zptr_string)
.ok_or_else(|| anyhow!("proof not found: {zptr_string}"))
}

fn prove(&mut self, store: &mut Store<F>, rest: Ptr<F>) -> Result<Option<Ptr<F>>> {
Expand Down Expand Up @@ -526,35 +523,33 @@ impl ClutchState<F, Coproc<F>> {
}?;

if proof.verify(&pp, &self.lang())?.verified {
let cid_str = proof.claim.cid().to_string();
let zptr_string = proof
.claim
.proof_key()
.map_err(|_| Error::msg("Failed to generate proof key"))?
.to_base32();
match proof.claim {
Claim::Evaluation(_) | Claim::Opening(_) => println!("{0:#?}", proof.claim),
Claim::PtrEvaluation(_) => println!("Claim::PtrEvaluation elided."),
}

let cid = store.str(cid_str);
Ok(Some(cid))
let zid = store.str(zptr_string);
Ok(Some(zid))
} else {
bail!("verification of new proof failed");
}
}
fn verify(&mut self, store: &mut Store<F>, rest: Ptr<F>) -> Result<Option<Ptr<F>>> {
let (proof_cid, _) = store.car_cdr(&rest)?;

let cid_string = if let Expression::Str(p) = store
.fetch(&proof_cid)
.ok_or_else(|| anyhow!("failed to fetch cid string"))?
{
p.to_string()
} else {
bail!("proof cid must be a string");
};
let zptr_string = store
.fetch_string(&proof_cid)
.ok_or_else(|| anyhow!("failed to fetch zptr string"))?;

let cid = lurk::public_parameters::cid_from_string(&cid_string)?;
let proof = self
.proof_map
.get(&cid)
.ok_or_else(|| anyhow!("proof not found: {cid}"))?;
.get(&zptr_string)
.ok_or_else(|| anyhow!("proof not found: {zptr_string}"))?;

let pp = public_params(self.reduction_count, self.lang())?;
let result = proof.verify(&pp, &self.lang()).unwrap();
Expand Down
1 change: 0 additions & 1 deletion fcomm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ clap = { version = "3.2", features = ["derive"] }
clap-verbosity-flag = "1.0"
ff = { workspace = true }
hex = { version = "0.4.3", features = ["serde"] }
libipld = { workspace = true, features = ["dag-cbor", "dag-json", "serde-codec"] }
log = { workspace = true }
lurk = { path = "../", package = "lurk" }
once_cell = { workspace = true }
Expand Down
Loading

0 comments on commit 57dfee0

Please sign in to comment.