-
Notifications
You must be signed in to change notification settings - Fork 317
/
proof.rs
2058 lines (1833 loc) · 81.3 KB
/
proof.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
use std::fs::{self, File};
use std::io::{BufReader, BufWriter};
use std::marker::PhantomData;
use std::panic::panic_any;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use anyhow::{ensure, Context};
use bincode::deserialize;
use blstrs::Scalar as Fr;
use fdlimit::raise_fd_limit;
use filecoin_hashers::{Domain, HashFunction, Hasher, PoseidonArity};
use generic_array::typenum::{Unsigned, U0, U11, U2};
use lazy_static::lazy_static;
use log::{error, info, trace};
use merkletree::{
merkle::{get_merkle_tree_len, is_merkle_tree_size_valid},
store::{DiskStore, Store, StoreConfig},
};
use rayon::prelude::{
IndexedParallelIterator, IntoParallelIterator, ParallelIterator, ParallelSliceMut,
};
#[cfg(any(feature = "cuda", feature = "multicore-sdr", feature = "opencl"))]
use storage_proofs_core::settings::SETTINGS;
use storage_proofs_core::{
cache_key::CacheKey,
data::Data,
drgraph::Graph,
error::Result,
measurements::{measure_op, Operation},
merkle::{
create_disk_tree, create_lc_tree, get_base_tree_count, split_config,
split_config_and_replica, BinaryMerkleTree, DiskTree, LCTree, MerkleProofTrait,
MerkleTreeTrait,
},
util::{default_rows_to_discard, NODE_SIZE},
};
use yastl::Pool;
use crate::{
encode::{decode, encode},
stacked::vanilla::{
challenges::{Challenges, SynthChallenges},
column::Column,
create_label,
graph::StackedBucketGraph,
hash::hash_single_column,
params::{
get_node, Labels, LabelsCache, PersistentAux, Proof, PublicInputs, PublicParams,
ReplicaColumnProof, SynthProofs, Tau, TemporaryAux, TemporaryAuxCache,
TransformedLayers, BINARY_ARITY,
},
EncodingProof, LabelingProof,
},
};
pub const TOTAL_PARENTS: usize = 37;
struct InvalidEncodingProofCoordinate {
failure_detected: bool,
layer: usize,
challenge_index: usize,
}
struct InvalidChallengeCoordinate {
failure_detected: bool,
challenge_index: usize,
}
lazy_static! {
/// Ensure that only one `TreeBuilder` or `ColumnTreeBuilder` uses the GPU at a time.
/// Curently, this is accomplished by only instantiating at most one at a time.
/// It might be possible to relax this constraint, but in that case, only one builder
/// should actually be active at any given time, so the mutex should still be used.
static ref GPU_LOCK: Mutex<()> = Mutex::new(());
static ref THREAD_POOL: Pool = Pool::new(num_cpus::get());
}
#[derive(Debug)]
pub struct StackedDrg<'a, Tree: MerkleTreeTrait, G: Hasher> {
_a: PhantomData<&'a Tree>,
_b: PhantomData<&'a G>,
}
#[derive(Debug)]
pub struct LayerState {
pub config: StoreConfig,
pub generated: bool,
}
pub enum TreeRElementData<Tree: MerkleTreeTrait> {
FrList(Vec<Fr>),
ElementList(Vec<<Tree::Hasher as Hasher>::Domain>),
}
#[allow(type_alias_bounds)]
pub type PrepareTreeRDataCallback<Tree: 'static + MerkleTreeTrait> =
fn(
source: &DiskStore<<Tree::Hasher as Hasher>::Domain>,
data: Option<&mut Data<'_>>,
start: usize,
end: usize,
) -> Result<TreeRElementData<Tree>>;
impl<'a, Tree: 'static + MerkleTreeTrait, G: 'static + Hasher> StackedDrg<'a, Tree, G> {
#[allow(clippy::too_many_arguments)]
pub(crate) fn prove_layers(
graph: &StackedBucketGraph<Tree::Hasher>,
pub_inputs: &PublicInputs<<Tree::Hasher as Hasher>::Domain, <G as Hasher>::Domain>,
p_aux: &PersistentAux<<Tree::Hasher as Hasher>::Domain>,
t_aux: &TemporaryAuxCache<Tree, G>,
challenges: &Challenges,
num_layers: usize,
partition_count: usize,
) -> Result<Vec<Vec<Proof<Tree, G>>>> {
assert!(num_layers > 0);
// Sanity checks on restored trees.
assert!(pub_inputs.tau.is_some());
match challenges {
Challenges::Interactive(interactive_challenges) => {
info!("generating interactive vanilla proofs");
let seed = pub_inputs
.seed
.expect("seed must be set for interactive vanilla proofs");
(0..partition_count)
.map(|k| {
trace!("proving partition {}/{}", k + 1, partition_count);
// Derive the set of challenges we are proving over.
let challenge_positions = interactive_challenges.derive(
graph.size(),
&pub_inputs.replica_id,
&seed,
k as u8,
);
Self::prove_layers_generate(
graph,
pub_inputs,
p_aux.comm_c,
t_aux,
challenge_positions,
num_layers,
)
})
.collect::<Result<Vec<Vec<Proof<Tree, G>>>>>()
}
Challenges::Synth(synth_challenges) => {
// If there are no synthetic vanilla proofs stored on disk yet, generate them.
if pub_inputs.seed.is_none() {
info!("generating all required synthetic vanilla proofs");
let comm_r = pub_inputs.tau.as_ref().expect("tau is set").comm_r;
// Derive the set of challenges we are proving over.
let challenge_positions = SynthChallenges::derive_synthetic(
graph.size(),
&pub_inputs.replica_id,
&comm_r,
);
let synth_proofs = Self::prove_layers_generate(
graph,
pub_inputs,
p_aux.comm_c,
t_aux,
challenge_positions,
num_layers,
)?;
Self::write_synth_proofs(
&synth_proofs,
pub_inputs,
graph,
synth_challenges,
num_layers,
t_aux.synth_proofs_path(),
)?;
Ok(vec![vec![]; partition_count])
}
// Else the synthetic vanilla proofs are stored on disk, read and return the proofs
// corresponding to the porep challlenge set.
else {
Self::read_porep_proofs_from_synth(
graph.size(),
pub_inputs,
synth_challenges,
num_layers,
t_aux.synth_proofs_path(),
partition_count,
)
.map_err(|error| {
info!(
"failed to read porep proofs from synthetic proofs file: {:?}",
t_aux.synth_proofs_path(),
);
error
})
}
}
Challenges::Ni(ni_challenges) => {
info!("generating non-interactive vanilla proofs");
let comm_r = pub_inputs.tau.as_ref().expect("tau is set").comm_r;
(0..partition_count)
.map(|k| {
trace!("proving partition {}/{}", k + 1, partition_count);
// Derive the set of challenges we are proving over.
let challenge_positions = ni_challenges.derive(
graph.size(),
&pub_inputs.replica_id,
&comm_r,
k as u8,
);
Self::prove_layers_generate(
graph,
pub_inputs,
p_aux.comm_c,
t_aux,
challenge_positions,
num_layers,
)
})
.collect::<Result<Vec<Vec<Proof<Tree, G>>>>>()
}
}
}
fn prove_layers_generate(
graph: &StackedBucketGraph<Tree::Hasher>,
pub_inputs: &PublicInputs<<Tree::Hasher as Hasher>::Domain, <G as Hasher>::Domain>,
comm_c: <Tree::Hasher as Hasher>::Domain,
t_aux: &TemporaryAuxCache<Tree, G>,
challenges: Vec<usize>,
num_layers: usize,
) -> Result<Vec<Proof<Tree, G>>> {
assert_eq!(t_aux.labels.len(), num_layers);
assert_eq!(
pub_inputs.tau.as_ref().expect("as_ref failure").comm_d,
t_aux.tree_d.as_ref().expect("failed to get tree_d").root()
);
let get_drg_parents_columns = |x: usize| -> Result<Vec<Column<Tree::Hasher>>> {
let base_degree = graph.base_graph().degree();
let mut columns = Vec::with_capacity(base_degree);
let mut parents = vec![0; base_degree];
graph.base_parents(x, &mut parents)?;
columns.extend(
parents
.into_par_iter()
.map(|parent| t_aux.column(parent))
.collect::<Result<Vec<Column<Tree::Hasher>>>>()?,
);
debug_assert!(columns.len() == base_degree);
Ok(columns)
};
let get_exp_parents_columns = |x: usize| -> Result<Vec<Column<Tree::Hasher>>> {
let mut parents = vec![0; graph.expansion_degree()];
graph.expanded_parents(x, &mut parents)?;
parents
.into_par_iter()
.map(|parent| t_aux.column(parent))
.collect()
};
// Error propagation mechanism for scoped parallel verification.
let invalid_encoding_proof = Arc::new(Mutex::new(InvalidEncodingProofCoordinate {
failure_detected: false,
layer: 0,
challenge_index: 0,
}));
let invalid_comm_d = Arc::new(Mutex::new(InvalidChallengeCoordinate {
failure_detected: false,
challenge_index: 0,
}));
let invalid_comm_r = Arc::new(Mutex::new(InvalidChallengeCoordinate {
failure_detected: false,
challenge_index: 0,
}));
THREAD_POOL.scoped(|scope| {
// Stacked commitment specifics
challenges
.into_par_iter()
.enumerate()
.map(|(challenge_index, challenge)| {
trace!(" challenge {} ({})", challenge, challenge_index);
assert!(challenge < graph.size(), "Invalid challenge");
assert!(challenge > 0, "Invalid challenge");
let comm_d_proof = t_aux
.tree_d
.as_ref()
.expect("failed to get tree_d")
.gen_proof(challenge)?;
let challenge_inner = challenge;
let comm_d_proof_inner = comm_d_proof.clone();
let invalid_comm_d_inner = Arc::clone(&invalid_comm_d);
scope.execute(move || {
if !comm_d_proof_inner.validate(challenge_inner) {
let mut invalid = invalid_comm_d_inner.lock().expect("failed to get lock on invalid_comm_d_inner");
*invalid = InvalidChallengeCoordinate {
failure_detected: true,
challenge_index,
};
error!("Invalid comm_d detected at challenge index {}", challenge_index);
}
});
// Stacked replica column openings
let rcp = {
let (c_x, drg_parents, exp_parents) = {
assert!(t_aux.tree_c.is_some());
let tree_c = t_aux.tree_c.as_ref().expect("failed to get tree_c");
assert_eq!(comm_c, tree_c.root());
// All labels in C_X
trace!(" c_x");
let c_x = t_aux.column(challenge as u32)?.into_proof(tree_c)?;
// All labels in the DRG parents.
trace!(" drg_parents");
let drg_parents = get_drg_parents_columns(challenge)?
.into_iter()
.map(|column| column.into_proof(tree_c))
.collect::<Result<_>>()?;
// Labels for the expander parents
trace!(" exp_parents");
let exp_parents = get_exp_parents_columns(challenge)?
.into_iter()
.map(|column| column.into_proof(tree_c))
.collect::<Result<_>>()?;
(c_x, drg_parents, exp_parents)
};
ReplicaColumnProof {
c_x,
drg_parents,
exp_parents,
}
};
// Final replica layer openings
trace!("final replica layer openings");
let comm_r_last_proof = t_aux.tree_r_last.gen_cached_proof(
challenge,
Some(t_aux.tree_r_last_config_rows_to_discard),
)?;
let comm_r_last_proof_inner = comm_r_last_proof.clone();
let invalid_comm_r_inner = Arc::clone(&invalid_comm_r);
scope.execute(move || {
if !comm_r_last_proof_inner.validate(challenge) {
let mut invalid = invalid_comm_r_inner.lock().expect("failed to get lock on invalid_comm_r_inner");
*invalid = InvalidChallengeCoordinate {
failure_detected: true,
challenge_index: challenge,
};
error!("Invalid comm_r detected at challenge index {}", challenge);
}
});
// Labeling Proofs Layer 1..l
let mut labeling_proofs = Vec::with_capacity(num_layers);
let mut encoding_proof = None;
for layer in 1..=num_layers {
trace!(" encoding proof layer {}", layer,);
let parents_data: Vec<<Tree::Hasher as Hasher>::Domain> = if layer == 1 {
let mut parents = vec![0; graph.base_graph().degree()];
graph.base_parents(challenge, &mut parents)?;
parents
.into_par_iter()
.map(|parent| t_aux.domain_node_at_layer(layer, parent))
.collect::<Result<_>>()?
} else {
let mut parents = vec![0; graph.degree()];
graph.parents(challenge, &mut parents)?;
let base_parents_count = graph.base_graph().degree();
parents
.into_par_iter()
.enumerate()
.map(|(i, parent)| {
if i < base_parents_count {
// parents data for base parents is from the current layer
t_aux.domain_node_at_layer(layer, parent)
} else {
// parents data for exp parents is from the previous layer
t_aux.domain_node_at_layer(layer - 1, parent)
}
})
.collect::<Result<_>>()?
};
// repeat parents
let mut parents_data_full = vec![Default::default(); TOTAL_PARENTS];
for chunk in parents_data_full.chunks_mut(parents_data.len()) {
chunk.copy_from_slice(&parents_data[..chunk.len()]);
}
let proof = LabelingProof::<Tree::Hasher>::new(
layer as u32,
challenge as u64,
parents_data_full.clone(),
);
{
let labeled_node = *rcp.c_x.get_node_at_layer(layer)?;
let replica_id = &pub_inputs.replica_id;
let proof_inner = proof.clone();
let invalid_encoding_proof_inner = Arc::clone(&invalid_encoding_proof);
scope.execute(move || {
if !proof_inner.verify(replica_id, &labeled_node) {
let mut invalid = invalid_encoding_proof_inner.lock().expect("failed to get lock on invalid_encoding_proof_inner");
*invalid = InvalidEncodingProofCoordinate {
failure_detected: true,
layer,
challenge_index,
};
error!("Invalid encoding proof generated at layer {}, challenge index {}", layer, challenge_index);
} else {
trace!("Valid encoding proof generated at layer {}", layer);
}
});
}
labeling_proofs.push(proof);
if layer == num_layers {
encoding_proof = Some(EncodingProof::new(
layer as u32,
challenge as u64,
parents_data_full,
));
}
// Check if a proof was detected as invalid
let invalid_comm_d_coordinate = invalid_comm_d.lock().expect("failed to get lock on invalid_comm_d");
ensure!(!invalid_comm_d_coordinate.failure_detected, "Invalid comm_d detected at challenge_index {}",
invalid_comm_d_coordinate.challenge_index);
let invalid_comm_r_coordinate = invalid_comm_r.lock().expect("failed to get lock on invalid_comm_r");
ensure!(!invalid_comm_r_coordinate.failure_detected, "Invalid comm_r detected at challenge_index {}",
invalid_comm_r_coordinate.challenge_index);
let invalid_encoding_proof_coordinate = invalid_encoding_proof.lock().expect("failed to get lock on invalid_encoding_proof");
ensure!(!invalid_encoding_proof_coordinate.failure_detected, "Invalid encoding proof generated at layer {}, challenge_index {}",
invalid_encoding_proof_coordinate.layer, invalid_encoding_proof_coordinate.challenge_index);
}
Ok(Proof {
comm_d_proofs: comm_d_proof,
replica_column_proofs: rcp,
comm_r_last_proof,
labeling_proofs,
encoding_proof: encoding_proof.expect("invalid tapering"),
})
})
.collect()
})
}
fn write_synth_proofs(
synth_proofs: &[Proof<Tree, G>],
pub_inputs: &PublicInputs<<Tree::Hasher as Hasher>::Domain, <G as Hasher>::Domain>,
graph: &StackedBucketGraph<Tree::Hasher>,
challenges: &SynthChallenges,
num_layers: usize,
path: PathBuf,
) -> Result<()> {
use crate::stacked::vanilla::challenges::synthetic::SynthChallengeGenerator;
ensure!(
pub_inputs.tau.is_some(),
"comm_r must be set prior to generating synthetic challenges",
);
let invalid_synth_porep_proof = Arc::new(Mutex::new(InvalidChallengeCoordinate {
failure_detected: false,
challenge_index: 0,
}));
// Verify synth proofs prior to writing because `ProofScheme`'s verification API is not
// amenable to prover-only verification (i.e. the API uses public values, whereas synthetic
// proofs are known only to the prover).
let pub_params = PublicParams::<Tree>::new(
graph.clone(),
Challenges::Synth(challenges.clone()),
num_layers,
);
let replica_id: Fr = pub_inputs.replica_id.into();
let comm_r: Fr = pub_inputs
.tau
.as_ref()
.map(|tau| tau.comm_r.into())
.expect("unwrapping should not fail");
let synth_challenges = SynthChallengeGenerator::default(graph.size(), &replica_id, &comm_r);
ensure!(
synth_proofs.len() == synth_challenges.num_synth_challenges,
"Mismatched synth porep proofs for the required challenge set"
);
THREAD_POOL.scoped(|scope| {
for (challenge, proof) in synth_challenges.zip(synth_proofs) {
let proof_inner = proof.clone();
let challenge_inner = challenge;
let pub_params_inner = pub_params.clone();
let pub_inputs_inner = pub_inputs.clone();
let invalid_synth_porep_proof_inner = Arc::clone(&invalid_synth_porep_proof);
scope.execute(move || {
if !proof_inner.verify(
&pub_params_inner,
&pub_inputs_inner,
challenge_inner,
graph,
) {
let mut invalid = invalid_synth_porep_proof_inner
.lock()
.expect("failed to get lock on invalid_synth_porep_proof_inner");
*invalid = InvalidChallengeCoordinate {
failure_detected: true,
challenge_index: challenge_inner,
};
error!(
"Invalid synth porep proof generated at challenge index {}",
challenge_inner
);
}
});
}
});
let invalid_synth_porep_proof_coordinate = invalid_synth_porep_proof
.lock()
.expect("failed to get lock on invalid_synth_porep_proof");
ensure!(
!invalid_synth_porep_proof_coordinate.failure_detected,
"Invalid synth_porep proof generated at challenge_index {}",
invalid_synth_porep_proof_coordinate.challenge_index
);
info!("writing synth-porep vanilla proofs to file: {:?}", path);
let file = File::create(&path).map(BufWriter::new).with_context(|| {
format!(
"failed to create synth-porep vanilla proofs file: {:?}",
path,
)
})?;
SynthProofs::write(file, synth_proofs).with_context(|| {
format!(
"failed to write synth-porep vanilla proofs to file: {:?}",
path,
)
})?;
info!(
"successfully stored synth-porep vanilla proofs to file: {:?}",
path,
);
Ok(())
}
fn read_porep_proofs_from_synth(
sector_nodes: usize,
pub_inputs: &PublicInputs<<Tree::Hasher as Hasher>::Domain, <G as Hasher>::Domain>,
challenges: &SynthChallenges,
num_layers: usize,
path: PathBuf,
partition_count: usize,
) -> Result<Vec<Vec<Proof<Tree, G>>>> {
ensure!(
pub_inputs.seed.is_some(),
"porep challenge seed must be set prior to reading porep proofs from synthetic",
);
ensure!(
pub_inputs.tau.is_some(),
"comm_r must be set prior to generating synthetic porep challenges",
);
let seed = pub_inputs
.seed
.as_ref()
.expect("unwrapping should not fail");
let comm_r = pub_inputs
.tau
.as_ref()
.map(|tau| &tau.comm_r)
.expect("unwrapping should not fail");
info!("reading synthetic vanilla proofs from file: {:?}", path);
let mut file = File::open(&path)
.map(BufReader::new)
.with_context(|| format!("failed to open synthetic vanilla proofs file: {:?}", path))?;
let porep_proofs = (0..partition_count as u8)
.map(|k| {
let synth_indexes = challenges.derive_indexes(
sector_nodes,
&pub_inputs.replica_id,
comm_r,
seed,
k,
);
SynthProofs::read(
&mut file,
sector_nodes,
num_layers,
synth_indexes.into_iter(),
)
.with_context(|| {
format!(
"failed to read partition k={} synthetic proofs from file: {:?}",
k, path,
)
})
})
.collect::<Result<Vec<Vec<Proof<Tree, G>>>>>()?;
info!("successfully read porep vanilla proofs from synthetic file");
Ok(porep_proofs)
}
pub fn extract_and_invert_transform_layers(
graph: &StackedBucketGraph<Tree::Hasher>,
num_layers: usize,
replica_id: &<Tree::Hasher as Hasher>::Domain,
data: &mut [u8],
config: StoreConfig,
) -> Result<()> {
trace!("extract_and_invert_transform_layers");
assert!(num_layers > 0);
let labels = Self::generate_labels_for_decoding(graph, num_layers, replica_id, config)?;
let last_layer_labels = labels.labels_for_last_layer()?;
let size = Store::len(last_layer_labels);
for (key, encoded_node_bytes) in last_layer_labels
.read_range(0..size)?
.into_iter()
.zip(data.chunks_mut(NODE_SIZE))
{
let encoded_node =
<Tree::Hasher as Hasher>::Domain::try_from_bytes(encoded_node_bytes)?;
let data_node = decode::<<Tree::Hasher as Hasher>::Domain>(key, encoded_node);
// store result in the data
encoded_node_bytes.copy_from_slice(AsRef::<[u8]>::as_ref(&data_node));
}
Ok(())
}
/// Generates the layers as needed for encoding.
fn generate_labels_for_encoding<P>(
graph: &StackedBucketGraph<Tree::Hasher>,
num_layers: usize,
replica_id: &<Tree::Hasher as Hasher>::Domain,
cache_path: P,
) -> Result<(Labels<Tree>, Vec<LayerState>)>
where
P: AsRef<Path>,
{
let mut parent_cache = graph.parent_cache()?;
#[cfg(feature = "multicore-sdr")]
{
if SETTINGS.use_multicore_sdr {
info!("multi core replication");
create_label::multi::create_labels_for_encoding(
graph,
&parent_cache,
num_layers,
replica_id,
&cache_path,
)
} else {
info!("single core replication");
create_label::single::create_labels_for_encoding(
graph,
&mut parent_cache,
num_layers,
replica_id,
&cache_path,
)
}
}
#[cfg(not(feature = "multicore-sdr"))]
{
info!("single core replication");
create_label::single::create_labels_for_encoding(
graph,
&mut parent_cache,
num_layers,
replica_id,
&cache_path,
)
}
}
/// Generates the layers, as needed for decoding.
pub fn generate_labels_for_decoding(
graph: &StackedBucketGraph<Tree::Hasher>,
num_layers: usize,
replica_id: &<Tree::Hasher as Hasher>::Domain,
config: StoreConfig,
) -> Result<LabelsCache<Tree>> {
let mut parent_cache = graph.parent_cache()?;
#[cfg(feature = "multicore-sdr")]
{
if SETTINGS.use_multicore_sdr {
info!("multi core replication");
create_label::multi::create_labels_for_decoding(
graph,
&parent_cache,
num_layers,
replica_id,
config,
)
} else {
info!("single core replication");
create_label::single::create_labels_for_decoding(
graph,
&mut parent_cache,
num_layers,
replica_id,
config,
)
}
}
#[cfg(not(feature = "multicore-sdr"))]
{
info!("single core replication");
create_label::single::create_labels_for_decoding(
graph,
&mut parent_cache,
num_layers,
replica_id,
config,
)
}
}
// NOTE: Unlike
// storage_proofs_core::merkle::create_base_merkle_tree, this
// method requires the data on disk to be exactly the same size as
// the tree length / NODE_SIZE.
fn build_binary_tree<K: Hasher>(
tree_data: &[u8],
config: StoreConfig,
) -> Result<BinaryMerkleTree<K>> {
trace!("building tree (size: {})", tree_data.len());
let leafs = tree_data.len() / NODE_SIZE;
assert_eq!(tree_data.len() % NODE_SIZE, 0);
let tree = BinaryMerkleTree::from_par_iter_with_config(
(0..leafs)
.into_par_iter()
// TODO: proper error handling instead of `unwrap()`
.map(|i| get_node::<K>(tree_data, i).expect("get_node failure")),
config,
)?;
Ok(tree)
}
#[cfg(any(feature = "cuda", feature = "opencl"))]
pub fn generate_tree_c<ColumnArity, TreeArity>(
nodes_count: usize,
tree_count: usize,
configs: Vec<StoreConfig>,
labels: &LabelsCache<Tree>,
) -> Result<DiskTree<Tree::Hasher, Tree::Arity, Tree::SubTreeArity, Tree::TopTreeArity>>
where
ColumnArity: 'static + PoseidonArity,
TreeArity: PoseidonArity,
{
if SETTINGS.use_gpu_column_builder::<Tree>() {
Self::generate_tree_c_gpu::<ColumnArity, TreeArity>(
nodes_count,
tree_count,
configs,
labels,
)
} else {
Self::generate_tree_c_cpu::<ColumnArity>(nodes_count, tree_count, configs, labels)
}
}
#[cfg(not(any(feature = "cuda", feature = "opencl")))]
pub fn generate_tree_c<ColumnArity, TreeArity>(
nodes_count: usize,
tree_count: usize,
configs: Vec<StoreConfig>,
labels: &LabelsCache<Tree>,
) -> Result<DiskTree<Tree::Hasher, Tree::Arity, Tree::SubTreeArity, Tree::TopTreeArity>>
where
ColumnArity: 'static + PoseidonArity,
TreeArity: PoseidonArity,
{
Self::generate_tree_c_cpu::<ColumnArity>(nodes_count, tree_count, configs, labels)
}
#[allow(clippy::needless_range_loop)]
#[cfg(any(feature = "cuda", feature = "opencl"))]
fn generate_tree_c_gpu<ColumnArity, TreeArity>(
nodes_count: usize,
tree_count: usize,
configs: Vec<StoreConfig>,
labels: &LabelsCache<Tree>,
) -> Result<DiskTree<Tree::Hasher, Tree::Arity, Tree::SubTreeArity, Tree::TopTreeArity>>
where
ColumnArity: 'static + PoseidonArity,
TreeArity: PoseidonArity,
{
use std::cmp::min;
use std::sync::{mpsc::sync_channel as channel, RwLock};
use fr32::fr_into_bytes;
use generic_array::GenericArray;
use log::warn;
use neptune::{
batch_hasher::Batcher,
column_tree_builder::{ColumnTreeBuilder, ColumnTreeBuilderTrait},
};
info!("generating tree c using the GPU");
// Build the tree for CommC
measure_op(Operation::GenerateTreeC, || {
info!("Building column hashes");
// NOTE: The max number of columns we recommend sending to the GPU at once is
// 400000 for columns and 700000 for trees (conservative soft-limits discussed).
//
// 'column_write_batch_size' is how many nodes to chunk the base layer of data
// into when persisting to disk.
//
// Override these values with care using environment variables:
// FIL_PROOFS_MAX_GPU_COLUMN_BATCH_SIZE, FIL_PROOFS_MAX_GPU_TREE_BATCH_SIZE, and
// FIL_PROOFS_COLUMN_WRITE_BATCH_SIZE respectively.
let max_gpu_column_batch_size = SETTINGS.max_gpu_column_batch_size as usize;
let max_gpu_tree_batch_size = SETTINGS.max_gpu_tree_batch_size as usize;
let column_write_batch_size = SETTINGS.column_write_batch_size as usize;
// This channel will receive batches of columns and add them to the ColumnTreeBuilder.
let (builder_tx, builder_rx) = channel(0);
let config_count = configs.len(); // Don't move config into closure below.
THREAD_POOL.scoped(|s| {
// This channel will receive the finished tree data to be written to disk.
let (writer_tx, writer_rx) = channel::<(Vec<Fr>, Vec<Fr>)>(0);
s.execute(move || {
for i in 0..config_count {
let mut node_index = 0;
let builder_tx = builder_tx.clone();
while node_index != nodes_count {
let chunked_nodes_count =
min(nodes_count - node_index, max_gpu_column_batch_size);
trace!(
"processing config {}/{} with column nodes {}",
i + 1,
tree_count,
chunked_nodes_count,
);
let columns: Vec<GenericArray<Fr, ColumnArity>> = {
use fr32::bytes_into_fr;
// Allocate layer data array and insert a placeholder for each layer.
let mut layer_data: Vec<Vec<u8>> =
vec![
vec![0u8; chunked_nodes_count * std::mem::size_of::<Fr>()];
ColumnArity::to_usize()
];
// gather all layer data.
for (layer_index, layer_bytes) in
layer_data.iter_mut().enumerate()
{
let store = labels.labels_for_layer(layer_index + 1);
let start = (i * nodes_count) + node_index;
let end = start + chunked_nodes_count;
store
.read_range_into(start, end, layer_bytes)
.expect("failed to read store range");
}
(0..chunked_nodes_count)
.into_par_iter()
.map(|index| {
(0..ColumnArity::to_usize())
.map(|layer_index| {
bytes_into_fr(
&layer_data[layer_index][std::mem::size_of::<Fr>()
* index
..std::mem::size_of::<Fr>() * (index + 1)],
)
.expect("Could not create Fr from bytes.")
})
.collect::<GenericArray<Fr, ColumnArity>>()
})
.collect()
};
node_index += chunked_nodes_count;
trace!(
"node index {}/{}/{}",
node_index,
chunked_nodes_count,
nodes_count,
);
let is_final = node_index == nodes_count;
builder_tx
.send((columns, is_final))
.expect("failed to send columns");
}
}
});
s.execute(move || {
let _gpu_lock = GPU_LOCK.lock().expect("failed to get gpu lock");
let tree_batcher = match Batcher::pick_gpu(max_gpu_tree_batch_size) {
Ok(b) => Some(b),
Err(err) => {
warn!("no GPU found, falling back to CPU tree builder: {}", err);
None
}
};
let column_batcher = match Batcher::pick_gpu(max_gpu_column_batch_size) {
Ok(b) => Some(b),
Err(err) => {
warn!("no GPU found, falling back to CPU tree builder: {}", err);
None
}
};
let mut column_tree_builder = ColumnTreeBuilder::<Fr, ColumnArity, TreeArity>::new(
column_batcher,
tree_batcher,
nodes_count,
)
.expect("failed to create ColumnTreeBuilder");
// Loop until all trees for all configs have been built.
for i in 0..config_count {
loop {
let (columns, is_final): (Vec<GenericArray<Fr, ColumnArity>>, bool) =
builder_rx.recv().expect("failed to recv columns");
// Just add non-final column batches.
if !is_final {
column_tree_builder
.add_columns(&columns)
.expect("failed to add columns");
continue;
};
// If we get here, this is a final column: build a sub-tree.
let (base_data, tree_data) = column_tree_builder
.add_final_columns(&columns)
.expect("failed to add final columns");
trace!(
"base data len {}, tree data len {}",
base_data.len(),
tree_data.len()
);
let tree_len = base_data.len() + tree_data.len();
info!(
"persisting base tree_c {}/{} of length {}",
i + 1,
tree_count,
tree_len,
);
writer_tx
.send((base_data, tree_data))
.expect("failed to send base_data, tree_data");
break;
}
}