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
use dashmap::DashMap;
use fastcrypto::Hash;
use std::{collections::VecDeque, iter, sync::Arc};
use store::{
rocks::{DBMap, TypedStoreError::RocksDBError},
Map,
};
use tokio::sync::{oneshot, oneshot::Sender};
use tracing::warn;
use types::{Certificate, CertificateDigest, Round, StoreResult};
pub type CertificateToken = u8;
#[derive(Clone)]
pub struct CertificateStore {
certificates_by_id: DBMap<CertificateDigest, Certificate>,
certificate_ids_by_round: DBMap<(Round, CertificateDigest), CertificateToken>,
notify_on_write_subscribers: Arc<DashMap<CertificateDigest, VecDeque<Sender<Certificate>>>>,
}
impl CertificateStore {
pub fn new(
certificates_by_id: DBMap<CertificateDigest, Certificate>,
certificate_ids_by_round: DBMap<(Round, CertificateDigest), CertificateToken>,
) -> CertificateStore {
Self {
certificates_by_id,
certificate_ids_by_round,
notify_on_write_subscribers: Arc::new(DashMap::new()),
}
}
pub fn write(&self, certificate: Certificate) -> StoreResult<()> {
let mut batch = self.certificates_by_id.batch();
let id = certificate.digest();
let round = certificate.round();
batch = batch.insert_batch(
&self.certificates_by_id,
iter::once((id, certificate.clone())),
)?;
let key = (round, id);
let value = 0;
batch = batch.insert_batch(&self.certificate_ids_by_round, iter::once((key, value)))?;
let result = batch.write();
if result.is_ok() {
self.notify_subscribers(id, certificate);
}
result
}
pub fn write_all(
&self,
certificates: impl IntoIterator<Item = Certificate>,
) -> StoreResult<()> {
let mut batch = self.certificates_by_id.batch();
let certificates: Vec<_> = certificates
.into_iter()
.map(|certificate| (certificate.digest(), certificate))
.collect();
batch = batch.insert_batch(&self.certificates_by_id, certificates.clone())?;
let values = certificates.iter().map(|(digest, c)| {
let key = (c.round(), *digest);
let value = 0;
(key, value)
});
batch = batch.insert_batch(&self.certificate_ids_by_round, values)?;
let result = batch.write();
if result.is_ok() {
for (_id, certificate) in certificates {
self.notify_subscribers(certificate.digest(), certificate);
}
}
result
}
pub fn read(&self, id: CertificateDigest) -> StoreResult<Option<Certificate>> {
self.certificates_by_id.get(&id)
}
pub fn read_all(
&self,
ids: impl IntoIterator<Item = CertificateDigest>,
) -> StoreResult<Vec<Option<Certificate>>> {
self.certificates_by_id.multi_get(ids)
}
pub async fn notify_read(&self, id: CertificateDigest) -> StoreResult<Certificate> {
let (sender, receiver) = oneshot::channel();
self.notify_on_write_subscribers
.entry(id)
.or_insert_with(VecDeque::new)
.push_back(sender);
if let Ok(Some(cert)) = self.read(id) {
self.notify_subscribers(id, cert.clone());
return Ok(cert);
}
let result = receiver
.await
.expect("Irrecoverable error while waiting to receive the notify_read result");
Ok(result)
}
pub fn delete(&self, id: CertificateDigest) -> StoreResult<()> {
let cert = match self.read(id)? {
Some(cert) => cert,
None => return Ok(()),
};
let round = cert.round();
let mut batch = self.certificates_by_id.batch();
batch = batch.delete_batch(&self.certificates_by_id, iter::once(id))?;
let key = (round, id);
batch = batch.delete_batch(&self.certificate_ids_by_round, iter::once(key))?;
batch.write()
}
pub fn delete_all(&self, ids: impl IntoIterator<Item = CertificateDigest>) -> StoreResult<()> {
let certs = self.read_all(ids)?;
let keys_by_round = certs
.into_iter()
.filter_map(|c| c.map(|cert| (cert.round(), cert.digest())))
.collect::<Vec<_>>();
if keys_by_round.is_empty() {
return Ok(());
}
let mut batch = self.certificates_by_id.batch();
batch = batch.delete_batch(&self.certificate_ids_by_round, keys_by_round.clone())?;
let ids = keys_by_round.into_iter().map(|(_round, digest)| digest);
batch = batch.delete_batch(&self.certificates_by_id, ids)?;
batch.write()
}
pub fn after_round(&self, round: Round) -> StoreResult<Vec<Certificate>> {
let key = (round, CertificateDigest::default());
let digests = self
.certificate_ids_by_round
.keys()
.skip_to(&key)?
.map(|(_round, digest)| digest);
self.certificates_by_id
.multi_get(digests)?
.into_iter()
.map(|opt_cert| {
opt_cert.ok_or_else(|| {
RocksDBError(format!(
"Certificate with id {} not found, CertificateStore invariant violation",
key.1
))
})
})
.collect()
}
pub fn last_round(&self) -> StoreResult<Vec<Certificate>> {
let certificates_reverse = self
.certificate_ids_by_round
.iter()
.skip_to_last()
.reverse();
let mut round = 0;
let mut certificates = Vec::new();
for (key, _value) in certificates_reverse {
let (certificate_round, certificate_id) = key;
if round == 0 {
round = certificate_round;
}
if round != certificate_round {
break;
}
let certificate = self
.certificates_by_id
.get(&certificate_id)?
.ok_or_else(|| {
RocksDBError(format!(
"Certificate with id {} not found in main storage although it should",
certificate_id
))
})?;
certificates.push(certificate);
}
Ok(certificates)
}
pub fn last_round_number(&self) -> Option<Round> {
if let Some(((last_round_num, _), _)) = self
.certificate_ids_by_round
.iter()
.skip_to_last()
.reverse()
.next()
{
return Some(last_round_num);
}
None
}
pub fn clear(&self) -> StoreResult<()> {
self.certificates_by_id.clear()?;
self.certificate_ids_by_round.clear()
}
pub fn is_empty(&self) -> bool {
self.certificates_by_id.is_empty()
}
fn notify_subscribers(&self, id: CertificateDigest, value: Certificate) {
if let Some((_, mut senders)) = self.notify_on_write_subscribers.remove(&id) {
while let Some(s) = senders.pop_front() {
if s.send(value.clone()).is_err() {
warn!("Couldn't notify obligation for certificate with id {id}");
}
}
}
}
}
#[cfg(test)]
mod test {
use crate::certificate_store::{CertificateStore, CertificateToken};
use fastcrypto::Hash;
use futures::future::join_all;
use std::{
collections::{BTreeSet, HashSet},
time::Instant,
};
use store::{
reopen,
rocks::{open_cf, DBMap},
};
use test_utils::{temp_dir, CommitteeFixture};
use types::{Certificate, CertificateDigest, Round};
fn new_store(path: std::path::PathBuf) -> CertificateStore {
const CERTIFICATES_CF: &str = "certificates";
const CERTIFICATE_IDS_BY_ROUND_CF: &str = "certificate_ids_by_round";
let rocksdb = open_cf(path, None, &[CERTIFICATES_CF, CERTIFICATE_IDS_BY_ROUND_CF])
.expect("Cannot open database");
let (certificate_map, certificate_ids_by_round_map) = reopen!(&rocksdb,
CERTIFICATES_CF;<CertificateDigest, Certificate>,
CERTIFICATE_IDS_BY_ROUND_CF;<(Round,CertificateDigest), CertificateToken>
);
CertificateStore::new(certificate_map, certificate_ids_by_round_map)
}
fn certificates(rounds: u64) -> Vec<Certificate> {
let fixture = CommitteeFixture::builder().build();
let committee = fixture.committee();
let mut current_round: Vec<_> = Certificate::genesis(&committee)
.into_iter()
.map(|cert| cert.header)
.collect();
let mut result: Vec<Certificate> = Vec::new();
for i in 0..rounds {
let parents: BTreeSet<_> = current_round
.iter()
.map(|header| fixture.certificate(header).digest())
.collect();
(_, current_round) = fixture.headers_round(i, &parents);
result.extend(
current_round
.iter()
.map(|h| fixture.certificate(h))
.collect::<Vec<Certificate>>(),
);
}
result
}
#[tokio::test]
async fn test_write_all_and_read_all() {
let store = new_store(temp_dir());
let certs = certificates(10);
let ids = certs
.iter()
.map(|c| c.digest())
.collect::<Vec<CertificateDigest>>();
store.write_all(certs.clone()).unwrap();
let result = store.read_all(ids).unwrap();
assert_eq!(certs.len(), result.len());
for (i, cert) in result.into_iter().enumerate() {
let c = cert.expect("Certificate should have been found");
assert_eq!(&c, certs.get(i).unwrap());
}
}
#[tokio::test]
async fn test_last_round() {
let store = new_store(temp_dir());
let certs = certificates(50);
store.write_all(certs).unwrap();
let result = store.last_round().unwrap();
let last_round = store.last_round_number().unwrap();
assert_eq!(result.len(), 4);
assert_eq!(last_round, 50);
for certificate in result {
assert_eq!(certificate.round(), last_round);
}
}
#[tokio::test]
async fn test_last_round_in_empty_store() {
let store = new_store(temp_dir());
let result = store.last_round().unwrap();
let last_round = store.last_round_number();
assert!(result.is_empty());
assert!(last_round.is_none());
}
#[tokio::test]
async fn test_after_round() {
let store = new_store(temp_dir());
let total_rounds = 100;
let now = Instant::now();
println!("Generating certificates");
let certs = certificates(total_rounds);
println!(
"Created certificates: {} seconds",
now.elapsed().as_secs_f32()
);
let now = Instant::now();
println!("Storing certificates");
store.write_all(certs.clone()).unwrap();
println!(
"Stored certificates: {} seconds",
now.elapsed().as_secs_f32()
);
let round_cutoff = 21;
let mut certs_ids_over_cutoff_round = certs
.into_iter()
.filter_map(|c| {
if c.round() >= round_cutoff {
Some(c.digest())
} else {
None
}
})
.collect::<HashSet<_>>();
println!("Access after round");
let now = Instant::now();
let result = store
.after_round(round_cutoff)
.expect("Error returned while reading after_round");
println!("Total time: {} seconds", now.elapsed().as_secs_f32());
let certs_per_round = 4;
assert_eq!(
result.len() as u64,
(total_rounds - round_cutoff + 1) * certs_per_round
);
let mut last_round = 0;
for certificate in result {
assert!(certificate.round() >= last_round);
last_round = certificate.round();
assert!(certs_ids_over_cutoff_round.remove(&certificate.digest()));
}
assert!(certs_ids_over_cutoff_round.is_empty());
}
#[tokio::test]
async fn test_notify_read() {
let store = new_store(temp_dir());
for _ in 0..10 {
let mut certs = certificates(3);
let mut ids = certs
.iter()
.map(|c| c.digest())
.collect::<Vec<CertificateDigest>>();
let cloned_store = store.clone();
let c1 = certs.remove(0);
store.write(c1.clone()).unwrap();
let id = ids.remove(0);
let handle_1 = tokio::spawn(async move { cloned_store.notify_read(id).await });
let mut handles = vec![];
for id in ids {
let cloned_store = store.clone();
let handle = tokio::spawn(async move {
cloned_store.notify_read(id).await
});
handles.push(handle)
}
store.write_all(certs).unwrap();
let received_certificate = handle_1
.await
.expect("error")
.expect("shouldn't receive store error");
assert_eq!(received_certificate, c1);
let result = join_all(handles).await;
for r in result {
let certificate_result = r.unwrap();
assert!(certificate_result.is_ok());
}
store.clear().unwrap();
}
}
#[tokio::test]
async fn test_write_all_and_clear() {
let store = new_store(temp_dir());
let certs = certificates(10);
store.write_all(certs).unwrap();
assert!(!store.is_empty());
store.clear().unwrap();
assert!(store.is_empty());
}
#[tokio::test]
async fn test_delete() {
let store = new_store(temp_dir());
let certs = certificates(10);
store.write_all(certs.clone()).unwrap();
let to_delete = certs.iter().take(2).map(|c| c.digest()).collect::<Vec<_>>();
store.delete(to_delete[0]).unwrap();
store.delete(to_delete[1]).unwrap();
assert!(store.read(to_delete[0]).unwrap().is_none());
assert!(store.read(to_delete[1]).unwrap().is_none());
}
#[tokio::test]
async fn test_delete_all() {
let store = new_store(temp_dir());
let certs = certificates(10);
store.write_all(certs.clone()).unwrap();
let to_delete = certs.iter().take(2).map(|c| c.digest()).collect::<Vec<_>>();
store.delete_all(to_delete.clone()).unwrap();
assert!(store.read(to_delete[0]).unwrap().is_none());
assert!(store.read(to_delete[1]).unwrap().is_none());
}
}