-
Notifications
You must be signed in to change notification settings - Fork 58
/
mod.rs
1607 lines (1391 loc) · 52.3 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! The `memoset` module implements a `MemoSet`.
//!
//! A `MemoSet` is an abstraction we use to memoize deferred proof of (potentially mutually-recursive) query results.
//! Whenever a computation being proved needs the result of a query, the prover non-deterministically supplies the
//! correct result. The resulting key-value pair is then added to a multiset representing deferred proofs. The
//! dependent proof now must not be accepted until every element in the deferred-proof multiset has been proved.
//!
//! Implementation depends on a cryptographic multiset -- for example, ECMH or LogUp (implemented here). This allows us
//! to prove that every element added to to the multiset is later removed only after having been proved. The
//! cryptographic assumption is that it is infeasible to fraudulently demonstrate multiset equality.
//!
//! Our use of the LogUp (logarithmic derivative) technique in the `LogMemo` implementation of `MemoSet` unfortunately
//! requires that the entire history of insertions and removals be committed to in advance -- so that Fiat-Shamir
//! randomness derived from the transcript can be used when mapping field elements to multiset elements. We use Lurk
//! data to assemble the transcript, so that the final randomness is the hash/value component of a `ZPtr` to the
//! content-addressed data structure representing the transcript as assembled.
//!
//! Transcript elements represent deferred proofs that are either added to (when their results are used) or removed from
//! (when correctness of those results is proved) the 'deferred proof' multiset. Insertions are recorded in the
//! transcript as key-value pairs (Lurk data: `(key . value)`); and removals further include the removal multiplicity
//! (Lurk data: `((key . value) . multiplicity)`). It is critical that the multiplicity be included in the transcript,
//! since if free to choose it after the randomness has been derived, the prover can trivially falsify the contents of
//! the multiset -- decoupling claimed truths from those actually proved.
//!
//! Bookkeeping required to correctly build the transcript after evaluation but before proving is maintained by the
//! `Scope`. This allows us to accumulate queries and the subqueries on which they depend, along with the memoized query
//! results computed 'naturally' during evaluation. We then separate and sort in an order matching that which the NIVC
//! prover will follow when provably maintaining the multiset accumulator and Fiat-Shamir transcript in the circuit.
use indexmap::IndexMap;
use itertools::Itertools;
use std::collections::HashSet;
use std::fmt::{Debug, Formatter};
use std::marker::PhantomData;
use std::sync::Arc;
use bellpepper_core::{
boolean::{AllocatedBit, Boolean},
num::AllocatedNum,
ConstraintSystem, SynthesisError,
};
use once_cell::sync::OnceCell;
use crate::circuit::gadgets::{
constraints::{enforce_equal, enforce_equal_zero, invert, sub},
pointer::AllocatedPtr,
};
use crate::coprocessor::gadgets::{
construct_cons, construct_list, construct_provenance, deconstruct_provenance,
};
use crate::field::LurkField;
use crate::lem::circuit::GlobalAllocator;
use crate::lem::tag::Tag;
use crate::lem::{
pointers::Ptr,
store::{Store, WithStore},
};
use crate::symbol::Symbol;
use crate::tag::{ExprTag, Tag as XTag};
use crate::z_ptr::ZPtr;
use multiset::MultiSet;
pub use query::{CircuitQuery, Query};
mod demo;
mod env;
mod multiset;
pub mod prove;
mod query;
#[derive(Debug)]
pub enum MemoSetError {
QueryDependenciesMissing,
QueryResultMissing,
}
#[derive(Clone, Debug)]
pub struct Transcript<F> {
acc: Ptr,
_p: PhantomData<F>,
}
impl<F: LurkField> Transcript<F> {
fn new(s: &Store<F>) -> Self {
let nil = s.intern_nil();
Self {
acc: nil,
_p: Default::default(),
}
}
fn add(&mut self, s: &Store<F>, item: Ptr) {
self.acc = s.cons(item, self.acc);
}
fn make_kv(s: &Store<F>, key: Ptr, value: Ptr) -> Ptr {
s.cons(key, value)
}
fn make_provenance_count(s: &Store<F>, provenance: Ptr, count: usize) -> Ptr {
let count_num = s.num(F::from_u64(count as u64));
s.cons(provenance, count_num)
}
/// Since the transcript is just a content-addressed Lurk list, its randomness is the hash value of the associated
/// top-level `Cons`. This function sanity-checks the type and extracts that field element.
fn r(&self, s: &Store<F>) -> F {
let z_ptr = s.hash_ptr(&self.acc);
assert_eq!(Tag::Expr(ExprTag::Cons), *z_ptr.tag());
*z_ptr.value()
}
#[allow(dead_code)]
fn dbg(&self, s: &Store<F>) {
tracing::debug!("transcript: {}", self.acc.fmt_to_string_simple(s));
}
#[allow(dead_code)]
fn fmt_to_string_simple(&self, s: &Store<F>) -> String {
self.acc.fmt_to_string_simple(s)
}
}
#[derive(Clone, Debug)]
pub struct CircuitTranscript<F: LurkField> {
acc: AllocatedPtr<F>,
}
impl<F: LurkField> CircuitTranscript<F> {
fn new<CS: ConstraintSystem<F>>(cs: &mut CS, g: &GlobalAllocator<F>, s: &Store<F>) -> Self {
let nil = s.intern_nil();
let allocated_nil = g.alloc_ptr(cs, &nil, s);
Self {
acc: allocated_nil.clone(),
}
}
pub fn pick<CS: ConstraintSystem<F>>(
cs: &mut CS,
condition: &Boolean,
a: &Self,
b: &Self,
) -> Result<Self, SynthesisError> {
let picked = AllocatedPtr::pick(cs, condition, &a.acc, &b.acc)?;
Ok(Self { acc: picked })
}
fn add<CS: ConstraintSystem<F>>(
&self,
cs: &mut CS,
g: &GlobalAllocator<F>,
s: &Store<F>,
item: &AllocatedPtr<F>,
) -> Result<Self, SynthesisError> {
let acc = construct_cons(cs, g, s, item, &self.acc)?;
Ok(Self { acc })
}
fn make_provenance_count<CS: ConstraintSystem<F>>(
cs: &mut CS,
g: &GlobalAllocator<F>,
s: &Store<F>,
provenance: &AllocatedPtr<F>,
count: u64,
) -> Result<(AllocatedPtr<F>, AllocatedNum<F>), SynthesisError> {
let allocated_count = { AllocatedNum::alloc(ns!(cs, "count"), || Ok(F::from_u64(count)))? };
let count_ptr = AllocatedPtr::alloc_tag(
ns!(cs, "count_ptr"),
ExprTag::Num.to_field(),
allocated_count.clone(),
)?;
Ok((
construct_cons(cs, g, s, provenance, &count_ptr)?,
allocated_count,
))
}
fn r(&self) -> &AllocatedNum<F> {
self.acc.hash()
}
#[allow(dead_code)]
fn dbg(&self, s: &Store<F>) {
let z = self.acc.get_value::<Tag>().unwrap();
let transcript = s.to_ptr(&z);
tracing::debug!("transcript: {}", transcript.fmt_to_string_simple(s));
}
}
#[derive(Debug)]
pub struct Provenance {
ptr: OnceCell<Ptr>,
query: Ptr,
result: Ptr,
// Dependencies is an ordered list of provenance(Ptr)s on which this depends.
dependencies: Vec<Ptr>,
}
impl Provenance {
fn new(
query: Ptr,
result: Ptr,
// Provenances on which this depends.
dependencies: Vec<Ptr>,
) -> Self {
Self {
ptr: OnceCell::new(),
query,
result,
dependencies,
}
}
fn dummy<F: LurkField>(store: &Store<F>) -> Self {
let nil = store.intern_nil();
let sym = store.intern_symbol(&Symbol::sym(&["lurk", "query", "dummy"]));
let query = store.cons(sym, nil);
Self::new(query, nil, vec![])
}
fn to_ptr<F: LurkField>(&self, store: &Store<F>) -> &Ptr {
self.ptr.get_or_init(|| {
let dependencies_list = if self.dependencies.len() == 1 {
self.dependencies[0]
} else {
store.list(self.dependencies.clone())
};
store.intern_provenance(self.query, self.result, dependencies_list)
})
}
}
#[derive(Debug)]
pub struct AllocatedProvenance<F: LurkField> {
ptr: OnceCell<AllocatedPtr<F>>,
query: AllocatedPtr<F>,
result: AllocatedPtr<F>,
// Dependencies is an ordered list of provenance(Ptr)s on which this depends.
dependencies: Vec<AllocatedPtr<F>>,
}
impl<F: LurkField> AllocatedProvenance<F> {
fn new(
query: AllocatedPtr<F>,
result: AllocatedPtr<F>,
// Provenances on which this depends.
dependencies: Vec<AllocatedPtr<F>>,
) -> Self {
Self {
ptr: OnceCell::new(),
query,
result,
dependencies,
}
}
fn to_ptr<CS: ConstraintSystem<F>>(
&self,
cs: &mut CS,
g: &GlobalAllocator<F>,
s: &Store<F>,
) -> Result<&AllocatedPtr<F>, SynthesisError> {
self.ptr.get_or_try_init(|| {
let deps = {
let arity = self.dependencies.len();
if arity == 1 {
self.dependencies[0].clone()
} else {
// TODO: Use a hash of exactly `arity` instead of a Lurk list.
construct_list(ns!(cs, "dependencies_list"), g, s, &self.dependencies, None)?
}
};
construct_provenance(
ns!(cs, "provenance"),
g,
s,
self.query.hash(),
&self.result,
deps.hash(),
)
})
}
}
type PW<'a, F> = WithStore<'a, F, Provenance>;
impl<'a, F: LurkField> Debug for PW<'a, F> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), std::fmt::Error> {
let p = self.inner();
let s = self.store();
f.debug_struct("Provenance")
.field("full", &p.to_ptr(s).fmt_to_string_simple(s))
.field("query", &p.query.fmt_to_string_simple(s))
.field(
"dependencies",
&p.dependencies
.iter()
.map(|ptr| ptr.fmt_to_string_simple(s))
.join(", "),
)
.finish()
}
}
#[derive(Clone, Debug)]
/// A `Scope` tracks the queries made while evaluating, including the subqueries that result from evaluating other
/// queries -- then makes use of the bookkeeping performed at evaluation time to synthesize proof of each query
/// performed.
pub struct Scope<Q: Query<F>, M, F: LurkField> {
memoset: M,
/// k => v
queries: IndexMap<Ptr, Ptr>,
/// k => ordered subqueries
dependencies: IndexMap<Ptr, Vec<Q>>,
/// inverse of dependencies
dependents: IndexMap<Ptr, HashSet<Ptr>>,
/// kv pairs
toplevel_insertions: Vec<Ptr>,
/// internally-inserted keys
internal_insertions: Vec<Ptr>,
/// unique keys: query-index -> [key]
unique_inserted_keys: IndexMap<usize, Vec<Ptr>>,
// This may become an explicit map or something allowing more fine-grained control.
provenances: OnceCell<IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>>>,
default_rc: usize,
pub(crate) store: Arc<Store<F>>,
pub(crate) runtime_data: Q::RD,
}
const DEFAULT_RC_FOR_QUERY: usize = 1;
impl<F: LurkField, Q: Query<F>> Scope<Q, LogMemo<F>, F> {
#[allow(dead_code)]
pub fn new(default_rc: usize, store: Arc<Store<F>>, runtime_data: Q::RD) -> Self {
Self {
memoset: Default::default(),
queries: Default::default(),
dependencies: Default::default(),
dependents: Default::default(),
toplevel_insertions: Default::default(),
internal_insertions: Default::default(),
unique_inserted_keys: Default::default(),
provenances: Default::default(),
default_rc,
runtime_data,
store,
}
}
fn provenance(&self, query: Ptr) -> Result<Provenance, MemoSetError> {
let store = self.store.as_ref();
let query_dependencies = self.dependencies.get(&query);
let result = self
.queries
.get(&query)
.ok_or(MemoSetError::QueryResultMissing)?;
let dependencies = if let Some(deps) = query_dependencies {
Ok(deps
.iter()
.map(|query| {
let ptr = query.to_ptr(store);
*self.provenance(ptr).unwrap().to_ptr(store)
})
.collect())
} else {
Err(MemoSetError::QueryDependenciesMissing)
}?;
Ok(Provenance::new(query, *result, dependencies))
}
fn provenance_from_kv(&self, kv: &Ptr) -> Result<Provenance, MemoSetError> {
let store = self.store.as_ref();
let (query, result) = store.car_cdr_simple(kv).expect("kv missing");
let query_dependencies = self.dependencies.get(&query);
let dependencies = if let Some(deps) = query_dependencies {
Ok(deps
.iter()
.map(|query| {
let ptr = query.to_ptr(store);
*self.provenance(ptr).unwrap().to_ptr(store)
})
.collect())
} else {
Ok(Vec::new())
}?;
Ok(Provenance::new(query, result, dependencies))
}
fn init_memoset(&self) -> Ptr {
let s = self.store.as_ref();
let mut memoset = s.num(F::ZERO);
for kv in self.toplevel_insertions.iter() {
let provenance = self.provenance_from_kv(kv).unwrap();
memoset = self.memoset.acc_add(&memoset, provenance.to_ptr(s), s);
}
memoset
}
fn init_transcript(&self) -> Ptr {
let s = self.store.as_ref();
let mut transcript = Transcript::new(s);
for kv in self.toplevel_insertions.iter() {
let provenance = self.provenance_from_kv(kv).unwrap();
transcript.add(s, *provenance.to_ptr(s));
}
transcript.acc
}
}
#[derive(Debug, Clone)]
pub struct CircuitScope<'a, F: LurkField, CM, RD> {
memoset: CM, // CircuitMemoSet
/// k -> allocated v
transcript: CircuitTranscript<F>,
/// k -> prov
provenances: Option<&'a IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>>>,
acc: Option<AllocatedPtr<F>>,
pub(crate) runtime_data: RD,
}
#[derive(Clone)]
pub struct CoroutineCircuit<'a, F: LurkField, M, Q: Query<F>> {
query_index: usize,
rc: usize,
store: &'a Store<F>,
runtime_data: &'a Q::RD,
// `None` for circuit synthesis
// `Some` for witness generation
witness_data: Option<WitnessData<'a, F, M>>,
}
#[derive(Clone, Copy)]
struct WitnessData<'a, F: LurkField, M> {
keys: &'a [Ptr],
memoset: &'a M,
provenances: &'a IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>>,
next_query_index: usize,
}
impl<'a, F: LurkField, M, Q: Query<F>> CoroutineCircuit<'a, F, M, Q> {
pub fn blank(
query_index: usize,
rc: usize,
store: &'a Store<F>,
runtime_data: &'a Q::RD,
) -> Self {
Self {
query_index,
store,
rc,
runtime_data,
witness_data: None,
}
}
fn witness_data(&self) -> Option<&WitnessData<'a, F, M>> {
self.witness_data.as_ref()
}
}
// TODO: Make this generic rather than specialized to LogMemo.
// That will require a CircuitScopeTrait.
impl<'a, F: LurkField, Q: Query<F>> CoroutineCircuit<'a, F, LogMemo<F>, Q> {
pub fn new(
scope: &'a Scope<Q, LogMemo<F>, F>,
keys: &'a [Ptr],
query_index: usize,
next_query_index: usize,
rc: usize,
) -> Self {
assert!(keys.len() <= rc);
let memoset = &scope.memoset;
let provenances = scope.provenances();
Self {
rc,
query_index,
store: &scope.store,
runtime_data: &scope.runtime_data,
witness_data: Some(WitnessData {
keys,
memoset,
provenances,
next_query_index,
}),
}
}
// This is a supernova::StepCircuit method.
// // TODO: we need to create a supernova::StepCircuit that will prove up to a fixed number of queries of a given type.
pub(crate) fn supernova_synthesize<CS: ConstraintSystem<F>>(
&self,
cs: &mut CS,
z: &[AllocatedPtr<F>],
) -> Result<(Option<AllocatedNum<F>>, Vec<AllocatedPtr<F>>), SynthesisError> {
let g = &GlobalAllocator::<F>::default();
assert_eq!(6, z.len());
let [c, e, k, memoset_acc, transcript, r] = z else {
unreachable!()
};
let multiset = self.witness_data().map(|w| &w.memoset.multiset);
let memoset = LogMemoCircuit {
multiset,
r: r.hash().clone(),
};
let provenances = self.witness_data().map(|w| w.provenances);
let mut circuit_scope: CircuitScope<'_, F, LogMemoCircuit<'_, F>, Q::RD> =
CircuitScope::new(
cs,
g,
self.store,
memoset,
provenances,
self.runtime_data.clone(),
);
circuit_scope.update_from_io(memoset_acc.clone(), transcript.clone(), r);
let keys: &[Ptr] = self.witness_data().map_or(&[], |w| w.keys);
for (i, key) in keys
.iter()
.map(Some)
.pad_using(self.rc, |_| None)
.enumerate()
{
let cs = ns!(cs, format!("internal-{i}"));
circuit_scope.synthesize_prove_key_query::<_, Q>(
cs,
g,
self.store,
key,
self.query_index,
)?;
}
let (memoset_acc, transcript, r_num) = circuit_scope.io();
let r = AllocatedPtr::alloc_tag(ns!(cs, "r"), ExprTag::Cons.to_field(), r_num)?;
let z_out = vec![c.clone(), e.clone(), k.clone(), memoset_acc, transcript, r];
let next_pc = AllocatedNum::alloc_infallible(&mut cs.namespace(|| "next_pc"), || {
let index = self.witness_data().unwrap().next_query_index;
F::from_u64(index as u64)
});
Ok((Some(next_pc), z_out))
}
}
impl<F: LurkField, Q: Query<F>> Scope<Q, LogMemo<F>, F> {
pub fn query(&mut self, form: Ptr) -> Ptr {
let (result, kv_ptr) = self.query_aux(form);
self.toplevel_insertions.push(kv_ptr);
result
}
fn query_recursively(&mut self, parent: &Q, child: Q) -> Ptr {
let s = self.store.as_ref();
let form = child.to_ptr(s);
self.internal_insertions.push(form);
let (result, _) = self.query_aux(form);
self.register_dependency(parent, child);
result
}
fn register_dependency(&mut self, parent: &Q, child: Q) {
let s = self.store.as_ref();
let parent_ptr = parent.to_ptr(s);
self.dependents
.entry(child.to_ptr(s))
.and_modify(|parents| {
parents.insert(parent_ptr);
})
.or_insert_with(|| {
let mut set = HashSet::new();
set.insert(parent_ptr);
set
});
self.dependencies
.entry(parent_ptr)
.and_modify(|children| children.push(child.clone()))
.or_insert_with(|| vec![child]);
}
fn query_aux(&mut self, form: Ptr) -> (Ptr, Ptr) {
// Ensure base-case queries explicitly contain no dependencies.
self.dependencies.entry(form).or_insert_with(|| Vec::new());
let result = self.queries.get(&form).cloned().unwrap_or_else(|| {
let s = self.store.as_ref();
let query = Q::from_ptr(&self.runtime_data, s, &form).expect("invalid query");
let evaluated = query.eval(self);
self.queries.insert(form, evaluated);
evaluated
});
let s = self.store.as_ref();
let kv = Transcript::make_kv(s, form, result);
// FIXME: The memoset should hold the provenances, not the kvs.
self.memoset.add(kv);
(result, kv)
}
pub(crate) fn finalize_transcript(&mut self) -> Transcript<F> {
let s = self.store.as_ref();
let (transcript, insertions) = self.build_transcript();
self.memoset.finalize_transcript(s, transcript.clone());
self.unique_inserted_keys = insertions;
transcript
}
fn provenances(&self) -> &IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>> {
self.provenances.get_or_init(|| self.compute_provenances())
}
// Retain for use when debugging.
//
// fn dbg_provenances(&self, store: &Store<F>) {
// Self::dbg_provenances_zptrs(store, self.provenances(store));
// }
// fn dbg_provenances_ptrs(store: &Store<F>, provenances: &IndexMap<Ptr, Ptr>) {
// for provenance in provenances.values() {
// dbg!(provenance.fmt_to_string_simple(store));
// }
// }
// fn dbg_provenances_zptrs(store: &Store<F>, provenances: &IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>>) {
// for (q, provenance) in provenances {
// dbg!(
// store.to_ptr(q).fmt_to_string_simple(store),
// store.to_ptr(provenance).fmt_to_string_simple(store)
// );
// }
// }
fn compute_provenances(&self) -> IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>> {
let mut provenances = IndexMap::default();
let mut ready = HashSet::new();
let mut missing_dependency_counts: IndexMap<&Ptr, usize> = self
.queries
.keys()
.map(|key| {
let dep_count = self.dependencies.get(key).map_or(0, |x| x.len());
if dep_count == 0 {
// Queries are ready if they have no missing dependencies.
// Initially, this will be the base cases -- which have no dependencies.
ready.insert(key);
}
(key, dep_count)
})
.collect();
while !ready.is_empty() {
ready =
self.extend_provenances(&mut provenances, ready, &mut missing_dependency_counts);
}
assert_eq!(
self.queries.len(),
provenances.len(),
"incomplete provenance computation (probably a forbidden cyclic query)"
);
let store = self.store.as_ref();
provenances
.iter()
.map(|(k, v)| (store.hash_ptr(k), store.hash_ptr(v)))
.collect()
}
fn extend_provenances<'a>(
&'a self,
provenances: &mut IndexMap<Ptr, Ptr>,
ready: HashSet<&Ptr>,
missing_dependency_counts: &mut IndexMap<&'a Ptr, usize>,
) -> HashSet<&Ptr> {
let mut next = HashSet::new();
for query in ready.into_iter() {
if provenances.get(query).is_some() {
// Skip if already complete. This should not happen if called by `compute_provenances` when computing
// all provenances from scratch, but it could happen if we compute more incrementally in the future.
continue;
};
let store = self.store.as_ref();
let sub_provenances = self
.dependencies
.get(query)
.expect("dependencies missing")
.iter()
.map(|dep| provenances.get(&dep.to_ptr(store)).unwrap())
.cloned()
.collect::<Vec<_>>();
let result = self.queries.get(query).expect("result missing");
let p = Provenance::new(*query, *result, sub_provenances);
let provenance = p.to_ptr(store);
// Insert new provenance before decrementing `missing_dependency_counts`.
provenances.insert(*query, *provenance);
if let Some(dependents) = self.dependents.get(query) {
for dependent in dependents {
missing_dependency_counts
.entry(dependent)
.and_modify(|missing_count| {
// NOTE: A query only becomes the `dependent` here when one of its dependencies is
// processed. Any query with `missing_count` 0 has no unprocessed dependencies to trigger
// the following update. Therefore, the underflow guarded against below should never occur
// if the implicit topological sort worked correctly. Any failure suggests the algorithm has
// been broken accidentally.
*missing_count = missing_count
.checked_sub(1)
.expect("topological sort has been broken; a dependency was processed out of order");
if *missing_count == 0 {
next.insert(dependent);
}
});
}
};
}
next
}
fn ensure_transcript_finalized(&mut self) {
if !self.memoset.is_finalized() {
self.finalize_transcript();
}
}
fn build_transcript(&self) -> (Transcript<F>, IndexMap<usize, Vec<Ptr>>) {
let s = self.store.as_ref();
let mut transcript = Transcript::new(s);
// k -> kv
let mut kvs_by_key: IndexMap<Ptr, Ptr> = IndexMap::new();
let mut unique_keys: IndexMap<usize, Vec<Ptr>> = Default::default();
let mut record_kv = |kv: &Ptr| {
let key = s.car_cdr_simple(kv).unwrap().0;
let kv1 = kvs_by_key.entry(key).or_insert_with(|| {
let index = Q::from_ptr(&self.runtime_data, s, &key)
.expect("bad query")
.index(&self.runtime_data);
// We only add to `unique_keys` inside this closure, which only happens once per key. This accomplishes
// the 'deduplication' referred to below.
unique_keys
.entry(index)
.and_modify(|keys| keys.push(key))
.or_insert_with(|| vec![key]);
*kv
});
assert_eq!(*kv, *kv1);
};
for kv in &self.toplevel_insertions {
record_kv(kv);
}
self.internal_insertions.iter().for_each(|key| {
let value = self.queries.get(key).expect("value missing for key");
let kv = Transcript::make_kv(s, *key, *value);
record_kv(&kv)
});
for kv in self.toplevel_insertions.iter() {
let provenance = self.provenance_from_kv(kv).unwrap();
transcript.add(s, *provenance.to_ptr(s));
}
// Then add insertions and removals interleaved, sorted by query type. We interleave insertions and removals
// because when proving later, each query's proof must record that its subquery proofs are being deferred
// (insertions) before then proving itself (making use of any subquery results) and removing the now-proved
// deferral from the MemoSet.
for index in 0..Q::count(&self.runtime_data) {
if let Some(keys) = unique_keys.get(&index) {
let rc = self.rc_for_query(index);
for chunk in &keys.iter().chunks(rc) {
for key in chunk.map(Some).pad_using(rc, |_| None) {
let (provenance, count) = if let Some(key) = key {
// This should not fail: `kv` was added in `record` above, when the key was added to
// `unique_keys`.
let kv = kvs_by_key.get(key).expect("kv missing");
let count = self.memoset.count(kv);
let provenance = self.provenance_from_kv(kv).unwrap();
(provenance, count)
} else {
(Provenance::dummy(s), 0)
};
let prov = provenance.to_ptr(s);
let prov_count = Transcript::make_provenance_count(s, *prov, count);
// Add removal for the query identified by `key`. The queries being removed here were deduplicated
// above, so each is removed only once. However, we freely choose the multiplicity (`count`) of the
// removal to match the total number of insertions actually made (considering dependencies).
transcript.add(s, prov_count);
}
}
}
}
(transcript, unique_keys)
}
pub fn synthesize<CS: ConstraintSystem<F>>(
&mut self,
cs: &mut CS,
g: &GlobalAllocator<F>,
) -> Result<(), SynthesisError> {
self.ensure_transcript_finalized();
let s = self.store.as_ref();
// FIXME: Do we need to allocate a new GlobalAllocator here?
// Is it okay for this memoset circuit to be shared between all CoroutineCircuits?
let r = self.memoset.allocated_r(ns!(cs, "memoset_allocated_r"));
let memoset_circuit = LogMemoCircuit {
multiset: Some(&self.memoset.multiset),
r,
};
let mut circuit_scope = CircuitScope::new(
ns!(cs, "transcript"),
g,
s,
memoset_circuit.clone(),
Some(self.provenances()),
self.runtime_data.clone(),
);
circuit_scope.init(cs, g, s);
{
circuit_scope.synthesize_insert_toplevel_queries(self, cs, g)?;
{
let s = self.store.as_ref();
let (memoset_acc, transcript, r_num) = circuit_scope.io();
let r = AllocatedPtr::from_parts(g.alloc_tag(cs, &ExprTag::Num).clone(), r_num);
let dummy = g.alloc_ptr(cs, &s.intern_nil(), s);
let mut z = vec![
dummy.clone(),
dummy.clone(),
dummy.clone(),
memoset_acc,
transcript,
r,
];
for (index, keys) in self.unique_inserted_keys.iter() {
let cs = ns!(cs, format!("query-index-{index}"));
let rc = self.rc_for_query(*index);
for (i, chunk) in keys.chunks(rc).enumerate() {
// This namespace exists only because we are putting multiple 'chunks' into a single, larger circuit (as a stage in development).
// It shouldn't exist, when instead we have only the single NIVC circuit repeated multiple times.
let cs = ns!(cs, format!("chunk-{i}"));
// `next_query_index` is only relevant for SuperNova
let next_query_index = 0;
let circuit: CoroutineCircuit<'_, F, LogMemo<F>, Q> =
CoroutineCircuit::new(self, chunk, *index, next_query_index, rc);
let (_next_pc, z_out) = circuit.supernova_synthesize(cs, &z)?;
{
let memoset_acc = &z_out[3];
let transcript = &z_out[4];
let r = &z_out[5];
circuit_scope.update_from_io(
memoset_acc.clone(),
transcript.clone(),
r,
);
z = z_out;
}
}
}
}
}
circuit_scope.finalize(cs, g);
Ok(())
}
fn rc_for_query(&self, _index: usize) -> usize {
self.default_rc
}
}
impl<'a, F: LurkField, RD> CircuitScope<'a, F, LogMemoCircuit<'a, F>, RD> {
fn new<CS: ConstraintSystem<F>>(
cs: &mut CS,
g: &GlobalAllocator<F>,
s: &Store<F>,
memoset: LogMemoCircuit<'a, F>,
provenances: Option<&'a IndexMap<ZPtr<Tag, F>, ZPtr<Tag, F>>>,
runtime_data: RD,
) -> Self {
Self {
memoset,
provenances,
transcript: CircuitTranscript::new(cs, g, s),
acc: Default::default(),
runtime_data,
}
}
fn init<CS: ConstraintSystem<F>>(&mut self, cs: &mut CS, g: &GlobalAllocator<F>, s: &Store<F>) {
self.acc =
Some(AllocatedPtr::alloc_constant(ns!(cs, "acc"), s.hash_ptr(&s.num_u64(0))).unwrap());
self.transcript = CircuitTranscript::new(cs, g, s);
}
fn io(&self) -> (AllocatedPtr<F>, AllocatedPtr<F>, AllocatedNum<F>) {
(
self.acc.as_ref().unwrap().clone(),
self.transcript.acc.clone(),
self.memoset.r.clone(),
)
}
fn update_from_io(
&mut self,
acc: AllocatedPtr<F>,
transcript: AllocatedPtr<F>,
r: &AllocatedPtr<F>,
) {
self.acc = Some(acc);
self.transcript.acc = transcript;
self.memoset.r = r.hash().clone();
}
fn synthesize_insert_query<CS: ConstraintSystem<F>>(
&self,
cs: &mut CS,
g: &GlobalAllocator<F>,
s: &Store<F>,
acc: &AllocatedPtr<F>,
transcript: &CircuitTranscript<F>,
provenance: &AllocatedPtr<F>,
) -> Result<(AllocatedPtr<F>, CircuitTranscript<F>), SynthesisError> {
let new_transcript = transcript.add(ns!(cs, "new_transcript"), g, s, provenance)?;
let acc_v = acc.hash();
let new_acc_v = self
.memoset
.synthesize_add(ns!(cs, "new_acc_v"), acc_v, provenance)?;
let new_acc =
AllocatedPtr::alloc_tag(ns!(cs, "new_acc"), ExprTag::Num.to_field(), new_acc_v)?;
Ok((new_acc, new_transcript))
}
fn synthesize_insert_internal_query<CS: ConstraintSystem<F>>(
&self,
cs: &mut CS,
acc: &AllocatedPtr<F>,
provenance: &AllocatedPtr<F>,
) -> Result<AllocatedPtr<F>, SynthesisError> {
let acc_v = acc.hash();
let new_acc_v = self
.memoset
.synthesize_add(ns!(cs, "new_acc_v"), acc_v, provenance)?;
let new_acc =