-
Notifications
You must be signed in to change notification settings - Fork 296
/
lmdb_pool.rs
2185 lines (1997 loc) · 74.1 KB
/
lmdb_pool.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 crate::consensus_pool::{InitializablePoolSection, PoolSectionOp, PoolSectionOps};
use crate::lmdb_iterator::{LMDBEcdsaIterator, LMDBIterator};
use crate::metrics::EcdsaPoolMetrics;
use ic_config::artifact_pool::LMDBConfig;
use ic_interfaces::consensus_pool::PurgeableArtifactType;
use ic_interfaces::{
consensus_pool::{
HeightIndexedPool, HeightRange, OnlyError, PoolSection, ValidatedConsensusArtifact,
},
ecdsa::{EcdsaPoolSection, EcdsaPoolSectionOp, EcdsaPoolSectionOps, MutableEcdsaPoolSection},
};
use ic_logger::{error, info, ReplicaLogger};
use ic_metrics::MetricsRegistry;
use ic_protobuf::types::v1 as pb;
use ic_types::consensus::certification::CertificationMessageHash;
use ic_types::consensus::HasHash;
use ic_types::{
artifact::{CertificationMessageId, ConsensusMessageId, EcdsaMessageId},
batch::BatchPayload,
consensus::{
certification::{Certification, CertificationMessage, CertificationShare},
dkg,
ecdsa::{
EcdsaArtifactId, EcdsaComplaint, EcdsaMessage, EcdsaMessageType, EcdsaOpening,
EcdsaPrefix, EcdsaPrefixOf, EcdsaSigShare,
},
BlockPayload, BlockProposal, CatchUpPackage, CatchUpPackageShare, ConsensusMessage,
ConsensusMessageHash, ConsensusMessageHashable, Finalization, FinalizationShare, HasHeight,
Notarization, NotarizationShare, Payload, PayloadType, RandomBeacon, RandomBeaconShare,
RandomTape, RandomTapeShare,
},
crypto::canister_threshold_sig::idkg::{IDkgDealingSupport, SignedIDkgDealing},
crypto::{CryptoHash, CryptoHashOf, CryptoHashable},
Height, Time,
};
use lmdb::{
Cursor, Database, DatabaseFlags, Environment, EnvironmentFlags, RoTransaction, RwTransaction,
Transaction, WriteFlags,
};
use prost::Message;
use serde::{Deserialize, Serialize};
use std::convert::{TryFrom, TryInto};
use std::fmt::Debug;
use std::marker::PhantomData;
use std::{os::raw::c_uint, path::Path, sync::Arc};
use strum::IntoEnumIterator;
/// Implementation of a persistent, height indexed pool using LMDB.
///
/// Given an artifact, we calculate 3 keys: TypeKey, HeightKey and IdKey,
/// where TypeKey only depends on the type of an artifact, and IdKey
/// is prefixed by height value (in big endian), which makes them
/// ordered and can be purged by heights.
///
/// There are 3 kind of LMDB databases used:
///
/// 1. An "artifacts" database maps IdKey to bincode encoded bytes for fast
/// serialization and deserialization:
///
/// ```text
/// artifacts
/// --------------------------------------
/// | IdKey | (bincode serialized) Bytes |
/// --------------------------------------
/// ```
///
/// 2. A set of index databases, one for each message type. Each one of them
/// maps a HeightKey to a set of IdKeys:
///
/// ```text
/// --------------------------
/// | HeightKey | IdKey, ... |
/// --------------------------
/// ```
///
/// 3. A "meta" database maps each TypeKey to the metadata of this message type,
/// which at the moment is only the min and max height.
///
/// ```text
/// meta
/// ------------------
/// | TypeKey | Meta |
/// ------------------
/// ```
pub struct PersistentHeightIndexedPool<T> {
pool_type: PhantomData<T>,
db_env: Arc<Environment>,
meta: Database,
artifacts: Database,
indices: Vec<(TypeKey, Database)>,
log: ReplicaLogger,
}
/// A trait for loading/saving pool artifacts (of ArtifactKind). It allows a
/// flexible data schema to be used for pool objects. For example, objects may
/// be normalized and serialized into multiple data entries, and they are
/// re-constructed upon loading. This can be taken care of by the `save` and
/// `load_as` interface, subject to the actual implementation for each
/// ArtifactKind.
///
/// We differentiate between 3 types:
///
/// 1. Object that is serialized and stored in the pool. This can include
/// additional data such as timestamp.
///
/// 2. Artifact::Message is the message type (usually an enum) of each
/// ArtifactKind. It can be casted into individual messages using TryFrom.
///
/// 3. Individual message type.
pub trait PoolArtifact: Sized {
/// Type of the object to store.
type ObjectType;
type Id;
/// The set of TypeKeys, one for each individual message type.
/// This should be a const function.
fn type_keys() -> &'static [TypeKey];
/// Save an artifact to the database.
fn save(
key: &IdKey,
value: Self::ObjectType,
artifacts: Database,
tx: &mut RwTransaction,
log: &ReplicaLogger,
) -> lmdb::Result<()>;
/// Load an artifact from the database. This is parameterized
/// by the individual message type T.
fn load_as<T: TryFrom<Self>>(
key: &IdKey,
db_env: Arc<Environment>,
artifacts: Database,
tx: &RoTransaction,
log: &ReplicaLogger,
) -> lmdb::Result<T>
where
<T as TryFrom<Self>>::Error: Debug;
}
/// A unique representation for each type of supported message.
/// Internally it is just a const string.
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct TypeKey {
name: &'static str,
}
impl TypeKey {
const fn new(name: &'static str) -> TypeKey {
TypeKey { name }
}
}
impl AsRef<[u8]> for TypeKey {
fn as_ref(&self) -> &[u8] {
self.name.as_bytes()
}
}
/// Each support message gives a TypeKey.
pub trait HasTypeKey {
fn type_key() -> TypeKey;
}
/// Message id as Key. The first 8 bytes is the big-endian representation
/// of the height, and the rest is hash.
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
pub struct IdKey(Vec<u8>);
impl IdKey {
pub fn height(&self) -> Height {
let mut bytes = [0; 8];
bytes.copy_from_slice(&self.0[0..8]);
Height::from(u64::from_be_bytes(bytes))
}
#[allow(unused)]
pub fn hash(&self) -> CryptoHash {
CryptoHash(self.0[8..].to_vec())
}
}
impl AsRef<[u8]> for IdKey {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl From<&[u8]> for IdKey {
fn from(bytes: &[u8]) -> IdKey {
IdKey(bytes.to_vec())
}
}
impl From<(Height, &CryptoHash)> for IdKey {
fn from((height, hash): (Height, &CryptoHash)) -> IdKey {
let hash_bytes = &hash.0;
let len = hash_bytes.len() + 8;
let mut bytes: Vec<u8> = vec![0; len];
let (left, right) = bytes.split_at_mut(8);
left.copy_from_slice(&u64::to_be_bytes(height.get()));
right.copy_from_slice(hash_bytes);
IdKey(bytes)
}
}
// This conversion is lossy because height and type tag are not preserved.
// It is okay because we don't expect reverse conversion.
impl<T: HasHeight + HasHash> From<&T> for IdKey {
fn from(id: &T) -> IdKey {
IdKey::from((id.height(), id.hash()))
}
}
/// Height key.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Debug, Serialize, Deserialize)]
pub(crate) struct HeightKey([u8; 8]);
impl AsRef<[u8]> for HeightKey {
fn as_ref(&self) -> &[u8] {
&self.0
}
}
impl From<&[u8]> for HeightKey {
fn from(bytes: &[u8]) -> HeightKey {
let mut bs: [u8; 8] = [0; 8];
bs.copy_from_slice(bytes);
HeightKey(bs)
}
}
/// Use big-endian to ensure byte ordering.
impl From<Height> for HeightKey {
fn from(height: Height) -> HeightKey {
HeightKey(u64::to_be_bytes(height.get()))
}
}
impl From<HeightKey> for Height {
fn from(key: HeightKey) -> Height {
Height::from(u64::from_be_bytes(key.0))
}
}
/// DB Meta info about each message type is their min and max height
/// (inclusive).
#[derive(Debug, Clone, Serialize, Deserialize)]
struct Meta {
min: HeightKey,
max: HeightKey,
}
/// Macro that logs the error when result is not Ok.
macro_rules! log_err {
($r:expr, $log:expr, $reason:expr) => {
$r.map_err(|err| error!($log, "Error in DB operation {}: {:?}", $reason, err))
.ok()
};
}
/// Combination of type/height/id keys.
#[derive(Debug)]
struct ArtifactKey {
type_key: TypeKey,
height_key: HeightKey,
id_key: IdKey,
}
/// Like log_err, but won't log the error if it matches the given error code.
macro_rules! log_err_except {
($r:expr, $log:expr, $code:pat, $reason:expr) => {
$r.map_err(|err| match err {
$code => {}
_ => error!($log, "Error in DB operation {:?}: {:?}", $reason, err),
})
.ok()
};
}
/// The max size (in bytes) of a persistent pool, also know as the LMDB map
/// size. It is a constant because it cannot be changed once DB is created.
const MAX_PERSISTENT_POOL_SIZE: usize = 0x0010_0000_0000; // 64GB
/// Max number of DB readers.
const MAX_READERS: c_uint = 2048;
fn create_db_env(path: &Path, read_only: bool, max_dbs: c_uint) -> Environment {
let mut builder = Environment::new();
let mut builder_flags = EnvironmentFlags::NO_TLS;
let mut permission = 0o644;
if read_only {
builder_flags |= EnvironmentFlags::READ_ONLY;
builder_flags |= EnvironmentFlags::NO_LOCK;
permission = 0o444;
}
builder.set_flags(builder_flags);
builder.set_max_readers(MAX_READERS);
builder.set_max_dbs(max_dbs);
builder.set_map_size(MAX_PERSISTENT_POOL_SIZE);
let db_env = builder
.open_with_permissions(path, permission)
.unwrap_or_else(|err| {
panic!(
"Error opening LMDB environment with permissions at {:?}: {:?}",
path, err
)
});
unsafe {
// Mark fds created by lmdb as FD_CLOEXEC to prevent them from leaking into
// canister sandbox process. Details in NODE-166
let mut fd: lmdb_sys::mdb_filehandle_t = lmdb_sys::mdb_filehandle_t::default();
lmdb_sys::mdb_env_get_fd(db_env.env(), &mut fd);
nix::fcntl::fcntl(fd, nix::fcntl::F_SETFD(nix::fcntl::FdFlag::FD_CLOEXEC))
.expect("Unable to mark FD_CLOEXEC");
};
db_env
}
///////////////////////////// Generic Pool /////////////////////////////
/// Collection of generic pool functions, indexed by Artifact type.
impl<Artifact: PoolArtifact> PersistentHeightIndexedPool<Artifact> {
/// Return a persistent pool located the given directory path.
/// Create the pool if it does not already exist.
/// Panic if initialization fails.
fn new(
path: &Path,
read_only: bool,
log: ReplicaLogger,
) -> PersistentHeightIndexedPool<Artifact> {
let type_keys = Artifact::type_keys();
let db_env = create_db_env(path, read_only, (type_keys.len() + 2) as c_uint);
// Create all databases.
let meta = if read_only {
db_env
.open_db(Some("META"))
.unwrap_or_else(|err| panic!("Error opening db for metadata: {:?}", err))
} else {
db_env
.create_db(Some("META"), DatabaseFlags::empty())
.unwrap_or_else(|err| panic!("Error creating db for metadata: {:?}", err))
};
let artifacts = if read_only {
db_env
.open_db(Some("ARTS"))
.unwrap_or_else(|err| panic!("Error opening db for artifacts: {:?}", err))
} else {
db_env
.create_db(Some("ARTS"), DatabaseFlags::empty())
.unwrap_or_else(|err| panic!("Error creating db for artifacts: {:?}", err))
};
let indices = {
type_keys
.iter()
.map(|type_key| {
// Use DUP_SORT to enable multi-value for each HeightKey.
let store = if read_only {
db_env.open_db(Some(type_key.name)).unwrap_or_else(|err| {
panic!("Error opening db {}: {:?}", type_key.name, err)
})
} else {
db_env
.create_db(Some(type_key.name), DatabaseFlags::DUP_SORT)
.unwrap_or_else(|err| {
panic!("Error creating db {}: {:?}", type_key.name, err)
})
};
(*type_key, store)
})
.collect()
};
Self {
pool_type: PhantomData,
db_env: Arc::new(db_env),
meta,
artifacts,
indices,
log,
}
}
/// Update the meta data of the given type_key.
fn update_meta(
&self,
tx: &mut RwTransaction,
type_key: &TypeKey,
meta: &Meta,
) -> lmdb::Result<()> {
if let Some(bytes) = log_err!(
bincode::serialize::<Meta>(meta),
self.log,
"update_meta serialize"
) {
tx.put(self.meta, &type_key, &bytes, WriteFlags::empty())
} else {
Err(lmdb::Error::Panic)
}
}
/// Get the meta data of the given type_key.
fn get_meta<Tx: Transaction>(&self, tx: &mut Tx, type_key: &TypeKey) -> Option<Meta> {
log_err_except!(
tx.get(self.meta, &type_key),
self.log,
lmdb::Error::NotFound,
format!("get_meta {:?}", type_key)
)
.and_then(|bytes| bincode::deserialize::<Meta>(bytes).ok())
}
/// Get the index database of the given type_key.
/// Each index database maps [`HeightKey`] to a list of [`IdKey`].
fn get_index_db(&self, type_key: &TypeKey) -> Database {
self.indices
.iter()
.find(|(key, _)| type_key == key)
.unwrap_or_else(|| panic!("Error in get_index_db: {:?} does not exist", type_key))
.1
}
/// Iterate messages between min and max HeightKey (inclusive).
///
/// It is parameterized by an individual message type as long as it can be
/// casted from the main `Artifact::Message` type.
fn iterate<Message: TryFrom<Artifact> + HasTypeKey + 'static>(
&self,
min_key: HeightKey,
max_key: HeightKey,
) -> Box<dyn Iterator<Item = Message>>
where
<Message as TryFrom<Artifact>>::Error: Debug,
{
let type_key = Message::type_key();
let index_db = self.get_index_db(&type_key);
let db_env = self.db_env.clone();
let log = self.log.clone();
let artifacts = self.artifacts;
Box::new(LMDBIterator::new(
db_env.clone(),
index_db,
min_key,
max_key,
move |tx: &RoTransaction<'_>, key: &[u8]| {
Artifact::load_as::<Message>(&IdKey::from(key), db_env.clone(), artifacts, tx, &log)
},
self.log.clone(),
))
}
/// Insert a pool object under the given type/height/id key.
fn tx_insert<PoolObject>(
&self,
tx: &mut RwTransaction,
key: &ArtifactKey,
value: PoolObject,
) -> lmdb::Result<()>
where
Artifact: PoolArtifact<ObjectType = PoolObject>,
{
self.tx_insert_prepare(tx, key)?;
Artifact::save(&key.id_key, value, self.artifacts, tx, &self.log)
}
/// Prepares pool for artifact insertion, by checking index DB for duplicates and
/// updating the metadata.
fn tx_insert_prepare<PoolObject>(
&self,
tx: &mut RwTransaction,
key: &ArtifactKey,
) -> lmdb::Result<()>
where
Artifact: PoolArtifact<ObjectType = PoolObject>,
{
// update index db first, because requiring NO_DUP_DATA may lead to
// error when dup is detected. Insertion can be skipped in this case.
let index_db = self.get_index_db(&key.type_key);
tx.put(
index_db,
&key.height_key,
&key.id_key,
WriteFlags::NO_DUP_DATA,
)?;
// update meta
let meta = self
.get_meta(tx, &key.type_key)
.map(|meta| Meta {
min: meta.min.min(key.height_key),
max: meta.max.max(key.height_key),
})
.unwrap_or(Meta {
min: key.height_key,
max: key.height_key,
});
self.update_meta(tx, &key.type_key, &meta)
}
/// Remove the pool object of the given type/height/id key.
fn tx_remove(&self, tx: &mut RwTransaction, key: &ArtifactKey) -> lmdb::Result<()> {
if let Err(err) = tx.del(self.artifacts, &key.id_key, None) {
// skip the removal if it is not found in artifacts
return if lmdb::Error::NotFound == err {
Ok(())
} else {
Err(err)
};
}
let index_db = self.get_index_db(&key.type_key);
tx.del(index_db, &key.height_key, Some(&key.id_key.0))?;
let min_height;
let max_height;
{
let mut cursor = tx.open_ro_cursor(index_db)?;
let mut iter = cursor.iter_start();
min_height = iter
.next()
.transpose()?
.map(|(key, _)| HeightKey::from(key));
max_height = iter
.last()
.transpose()?
.map(|(key, _)| HeightKey::from(key));
}
match (min_height, max_height) {
(Some(min), Some(max)) => self.update_meta(tx, &key.type_key, &Meta { min, max }),
(Some(min), None) => self.update_meta(tx, &key.type_key, &Meta { min, max: min }),
_ => tx.del(self.meta, &key.type_key, None),
}
}
/// Remove all index entries for the given [`TypeKey`] with heights
/// less than the given [`HeightKey`]. Update the type's meta table
/// if necessary. Return the [`ArtifactKey`]s of deleted entries.
fn tx_purge_index_below(
&self,
tx: &mut RwTransaction,
type_key: TypeKey,
height_key: HeightKey,
) -> lmdb::Result<Vec<ArtifactKey>> {
let mut artifact_ids = Vec::new();
// only delete if meta exists
if let Some(meta) = self.get_meta(tx, &type_key) {
// nothing to delete if min height is already higher
if meta.min >= height_key {
return Ok(artifact_ids);
}
let index_db = self.get_index_db(&type_key);
{
let mut cursor = tx.open_rw_cursor(index_db)?;
loop {
match cursor.iter().next().transpose()? {
None => break,
Some((key, id)) => {
if HeightKey::from(key) >= height_key {
break;
}
artifact_ids.push(ArtifactKey {
type_key,
height_key: HeightKey::from(key),
id_key: IdKey::from(id),
});
cursor.del(WriteFlags::empty())?;
}
}
}
}
// update meta
let meta = if meta.max <= height_key {
None
} else {
let mut cursor = tx.open_rw_cursor(index_db)?;
cursor
.iter_start()
.next()
.transpose()?
.map(|(key, _)| Meta {
min: HeightKey::from(key),
max: meta.max,
})
};
match meta {
None => tx.del(self.meta, &type_key, None)?,
Some(meta) => self.update_meta(tx, &type_key, &meta)?,
}
}
Ok(artifact_ids)
}
/// Remove all artifacts with heights less than the given [`HeightKey`].
/// Return [`ArtifactKey`]s of the removed artifacts.
fn tx_purge_below(
&self,
tx: &mut RwTransaction,
height_key: HeightKey,
) -> lmdb::Result<Vec<ArtifactKey>> {
let mut purged = Vec::new();
// delete from all index tables
for &type_key in Artifact::type_keys() {
purged.append(&mut self.tx_purge_index_below(tx, type_key, height_key)?);
}
// delete from artifacts table
let mut cursor = tx.open_rw_cursor(self.artifacts)?;
let height = Height::from(height_key);
loop {
match cursor.iter().next().transpose()? {
None => break,
Some((key, _)) => {
let id_key = IdKey::from(key);
if id_key.height() >= height {
break;
}
cursor.del(WriteFlags::empty())?;
}
}
}
Ok(purged)
}
/// Remove all artifacts of the given [`TypeKey`] with heights less than the
/// given [`HeightKey`]. Return [`ArtifactKey`]s of the removed artifacts.
fn tx_purge_type_below(
&self,
tx: &mut RwTransaction,
type_key: TypeKey,
height_key: HeightKey,
) -> lmdb::Result<Vec<ArtifactKey>> {
let artifact_keys = self.tx_purge_index_below(tx, type_key, height_key)?;
// delete the corresponding artifacts, ignoring not found errors
for key in &artifact_keys {
if let Err(err) = tx.del(self.artifacts, &key.id_key, None) {
// Ignore not found errors, although they should not appear in practice.
if lmdb::Error::NotFound != err {
return Err(err);
}
}
}
Ok(artifact_keys)
}
}
impl InitializablePoolSection for PersistentHeightIndexedPool<ConsensusMessage> {
/// Insert a cup with the original bytes from which that cup was received.
fn insert_cup_with_proto(&self, cup_proto: pb::CatchUpPackage) {
let cup = CatchUpPackage::try_from(&cup_proto).expect("deserializing CUP failed");
let mut tx = self
.db_env
.begin_rw_txn()
.expect("Unable to begin transaction to initialize consensus pool");
let key = ArtifactKey::from(cup.get_id());
// convert cup to bytes
let bytes = &pb::ValidatedConsensusArtifact {
msg: Some(pb::ConsensusMessage {
msg: Some(pb::consensus_message::Msg::Cup(cup_proto)),
}),
timestamp: cup
.content
.block
.as_ref()
.context
.time
.as_nanos_since_unix_epoch(),
}
.encode_to_vec();
// insert raw bytes
self.tx_insert_prepare(&mut tx, &key)
.expect("Insertion of metadata or updating index failed");
tx.put(self.artifacts, &key.id_key, bytes, WriteFlags::empty())
.expect("Insertion of CUP into initial consensus pool failed");
tx.commit()
.expect("Transaction inserting initial CUP into pool failed to commit");
}
}
impl<Artifact: PoolArtifact, Message> HeightIndexedPool<Message>
for PersistentHeightIndexedPool<Artifact>
where
Message: TryFrom<Artifact> + HasTypeKey + 'static,
<Message as TryFrom<Artifact>>::Error: Debug,
{
fn height_range(&self) -> Option<HeightRange> {
let mut tx = log_err!(self.db_env.begin_ro_txn(), self.log, "begin_ro_txn")?;
self.get_meta(&mut tx, &Message::type_key())
.map(|meta| HeightRange::new(Height::from(meta.min), Height::from(meta.max)))
}
fn max_height(&self) -> Option<Height> {
<dyn HeightIndexedPool<Message>>::height_range(self).map(|range| range.max)
}
fn get_all(&self) -> Box<dyn Iterator<Item = Message>> {
match <dyn HeightIndexedPool<Message>>::height_range(self) {
None => Box::new(std::iter::empty()),
Some(range) => self.iterate::<Message>(range.min.into(), range.max.into()),
}
}
fn get_by_height(&self, h: Height) -> Box<dyn Iterator<Item = Message>> {
let key = HeightKey::from(h);
self.iterate(key, key)
}
fn get_only_by_height(&self, h: Height) -> Result<Message, OnlyError> {
let mut as_vec: Vec<Message> = self.get_by_height(h).collect();
match as_vec.len() {
0 => Err(OnlyError::NoneAvailable),
1 => Ok(as_vec.remove(0)),
_ => Err(OnlyError::MultipleValues),
}
}
fn get_by_height_range(&self, range: HeightRange) -> Box<dyn Iterator<Item = Message>> {
match <dyn HeightIndexedPool<Message>>::height_range(self) {
None => Box::new(std::iter::empty()),
Some(bounds) => self.iterate::<Message>(
HeightKey::from(range.min.max(bounds.min)),
HeightKey::from(range.max.min(bounds.max)),
),
}
}
fn get_highest_iter(&self) -> Box<dyn Iterator<Item = Message>> {
match <dyn HeightIndexedPool<Message>>::max_height(self) {
Some(height) => self.get_by_height(height),
None => Box::new(std::iter::empty()),
}
}
fn get_highest(&self) -> Result<Message, OnlyError> {
let mut as_vec: Vec<Message> = self.get_highest_iter().collect();
match as_vec.len() {
0 => Err(OnlyError::NoneAvailable),
1 => Ok(as_vec.remove(0)),
_ => Err(OnlyError::MultipleValues),
}
}
fn size(&self) -> usize {
let index_db = self.get_index_db(&Message::type_key());
let Some(tx) = log_err!(self.db_env.begin_ro_txn(), &self.log, "begin_ro_txn") else {
return 0;
};
let Some(mut cursor) = log_err!(tx.open_ro_cursor(index_db), &self.log, "open_ro_cursor")
else {
return 0;
};
cursor.iter().count()
}
}
///////////////////////////// Consensus Pool /////////////////////////////
const RANDOM_BEACON_KEY: TypeKey = TypeKey::new("RB");
const FINALIZATION_KEY: TypeKey = TypeKey::new("FZ");
const NOTARIZATION_KEY: TypeKey = TypeKey::new("NZ");
const BLOCK_PROPOSAL_KEY: TypeKey = TypeKey::new("BP");
const BLOCK_PAYLOAD_KEY: TypeKey = TypeKey::new("PL");
const RANDOM_BEACON_SHARE_KEY: TypeKey = TypeKey::new("RBS");
const NOTARIZATION_SHARE_KEY: TypeKey = TypeKey::new("NZS");
const FINALIZATION_SHARE_KEY: TypeKey = TypeKey::new("FZS");
const RANDOM_TAPE_KEY: TypeKey = TypeKey::new("RT");
const RANDOM_TAPE_SHARE_KEY: TypeKey = TypeKey::new("RTS");
const CATCH_UP_PACKAGE_KEY: TypeKey = TypeKey::new("CUP");
const CATCH_UP_PACKAGE_SHARE_KEY: TypeKey = TypeKey::new("CUS");
const CONSENSUS_KEYS: [TypeKey; 12] = [
RANDOM_BEACON_KEY,
FINALIZATION_KEY,
NOTARIZATION_KEY,
BLOCK_PROPOSAL_KEY,
BLOCK_PAYLOAD_KEY,
RANDOM_BEACON_SHARE_KEY,
NOTARIZATION_SHARE_KEY,
FINALIZATION_SHARE_KEY,
RANDOM_TAPE_KEY,
RANDOM_TAPE_SHARE_KEY,
CATCH_UP_PACKAGE_KEY,
CATCH_UP_PACKAGE_SHARE_KEY,
];
impl HasTypeKey for RandomBeacon {
fn type_key() -> TypeKey {
RANDOM_BEACON_KEY
}
}
impl HasTypeKey for Notarization {
fn type_key() -> TypeKey {
NOTARIZATION_KEY
}
}
impl HasTypeKey for Finalization {
fn type_key() -> TypeKey {
FINALIZATION_KEY
}
}
impl HasTypeKey for BlockProposal {
fn type_key() -> TypeKey {
BLOCK_PROPOSAL_KEY
}
}
impl HasTypeKey for RandomBeaconShare {
fn type_key() -> TypeKey {
RANDOM_BEACON_SHARE_KEY
}
}
impl HasTypeKey for NotarizationShare {
fn type_key() -> TypeKey {
NOTARIZATION_SHARE_KEY
}
}
impl HasTypeKey for FinalizationShare {
fn type_key() -> TypeKey {
FINALIZATION_SHARE_KEY
}
}
impl HasTypeKey for RandomTape {
fn type_key() -> TypeKey {
RANDOM_TAPE_KEY
}
}
impl HasTypeKey for RandomTapeShare {
fn type_key() -> TypeKey {
RANDOM_TAPE_SHARE_KEY
}
}
impl HasTypeKey for CatchUpPackage {
fn type_key() -> TypeKey {
CATCH_UP_PACKAGE_KEY
}
}
impl HasTypeKey for CatchUpPackageShare {
fn type_key() -> TypeKey {
CATCH_UP_PACKAGE_SHARE_KEY
}
}
impl From<ConsensusMessageId> for ArtifactKey {
fn from(msg_id: ConsensusMessageId) -> Self {
let type_key = match msg_id.hash {
ConsensusMessageHash::RandomBeacon(_) => RANDOM_BEACON_KEY,
ConsensusMessageHash::Finalization(_) => FINALIZATION_KEY,
ConsensusMessageHash::Notarization(_) => NOTARIZATION_KEY,
ConsensusMessageHash::BlockProposal(_) => BLOCK_PROPOSAL_KEY,
ConsensusMessageHash::RandomBeaconShare(_) => RANDOM_BEACON_SHARE_KEY,
ConsensusMessageHash::NotarizationShare(_) => NOTARIZATION_SHARE_KEY,
ConsensusMessageHash::FinalizationShare(_) => FINALIZATION_SHARE_KEY,
ConsensusMessageHash::RandomTape(_) => RANDOM_TAPE_KEY,
ConsensusMessageHash::RandomTapeShare(_) => RANDOM_TAPE_SHARE_KEY,
ConsensusMessageHash::CatchUpPackage(_) => CATCH_UP_PACKAGE_KEY,
ConsensusMessageHash::CatchUpPackageShare(_) => CATCH_UP_PACKAGE_SHARE_KEY,
};
Self {
type_key,
height_key: HeightKey::from(msg_id.height),
id_key: IdKey::from((msg_id.height, msg_id.hash.digest())),
}
}
}
impl TryFrom<ArtifactKey> for ConsensusMessageId {
type Error = String;
fn try_from(key: ArtifactKey) -> Result<Self, Self::Error> {
let h = key.id_key.hash();
let hash = match key.type_key {
RANDOM_BEACON_KEY => ConsensusMessageHash::RandomBeacon(h.into()),
FINALIZATION_KEY => ConsensusMessageHash::Finalization(h.into()),
NOTARIZATION_KEY => ConsensusMessageHash::Notarization(h.into()),
BLOCK_PROPOSAL_KEY => ConsensusMessageHash::BlockProposal(h.into()),
RANDOM_BEACON_SHARE_KEY => ConsensusMessageHash::RandomBeaconShare(h.into()),
NOTARIZATION_SHARE_KEY => ConsensusMessageHash::NotarizationShare(h.into()),
FINALIZATION_SHARE_KEY => ConsensusMessageHash::FinalizationShare(h.into()),
RANDOM_TAPE_KEY => ConsensusMessageHash::RandomTape(h.into()),
RANDOM_TAPE_SHARE_KEY => ConsensusMessageHash::RandomTapeShare(h.into()),
CATCH_UP_PACKAGE_KEY => ConsensusMessageHash::CatchUpPackage(h.into()),
CATCH_UP_PACKAGE_SHARE_KEY => ConsensusMessageHash::CatchUpPackageShare(h.into()),
BLOCK_PAYLOAD_KEY => {
return Err("Block payloads do not have a ConsensusMessageId".into())
}
other => {
return Err(format!(
"{:?} is not a valid ConsensusMessage TypeKey.",
other
))
}
};
Ok(ConsensusMessageId {
hash,
height: key.id_key.height(),
})
}
}
impl PoolArtifact for ConsensusMessage {
type ObjectType = ValidatedConsensusArtifact;
type Id = ConsensusMessageId;
fn type_keys() -> &'static [TypeKey] {
&CONSENSUS_KEYS
}
fn save(
key: &IdKey,
mut value: Self::ObjectType,
artifacts: Database,
tx: &mut RwTransaction,
log: &ReplicaLogger,
) -> lmdb::Result<()> {
// special handling for block proposal & its payload
if let ConsensusMessage::BlockProposal(mut proposal) = value.msg {
// store block payload separately
let block = proposal.content.as_mut();
let payload_hash = block.payload.get_hash().clone();
let payload = block.payload.as_ref();
let start_height = payload.dkg_interval_start_height();
let payload_type = payload.payload_type();
{
let payload_key = IdKey::from((block.height(), payload_hash.get_ref()));
let bytes = log_err!(
bincode::serialize::<BlockPayload>(payload),
log,
"ConsensusArtifact::save serialize BlockPayload"
)
.ok_or(lmdb::Error::Panic)?;
tx.put(artifacts, &payload_key, &bytes, WriteFlags::empty())?;
}
// replace block payload with an empty one
block.payload = Payload::new_with(
payload_hash,
payload_type,
// A dummy payload. Note that during deserialization, this dummy is
// used to determine the payload type. So it's important that the
// dummy has the SAME payload type as the real payload.
Box::new(move || match payload_type {
PayloadType::Summary => (dkg::Summary::default(), None).into(),
PayloadType::Data => (
BatchPayload::default(),
dkg::Dealings::new_empty(start_height),
None,
)
.into(),
}),
);
value.msg = proposal.into_message();
}
let bytes = pb::ValidatedConsensusArtifact::from(&value).encode_to_vec();
tx.put(artifacts, &key, &bytes, WriteFlags::empty())
}
fn load_as<T: TryFrom<Self>>(
key: &IdKey,
db_env: Arc<Environment>,
artifacts: Database,
tx: &RoTransaction,
log: &ReplicaLogger,
) -> lmdb::Result<T>
where
<T as TryFrom<Self>>::Error: Debug,
{
let bytes = tx.get(artifacts, &key)?;
let protobuf = log_err!(
pb::ValidatedConsensusArtifact::decode(bytes),
log,
"ConsensusArtifact::load_as protobuf decoding"
)
.ok_or(lmdb::Error::Panic)?;
let artifact: ValidatedConsensusArtifact = log_err!(
protobuf.try_into(),
log,
"ConsensusArtifact::load_as protobuf conversion"
)
.ok_or(lmdb::Error::Panic)?;
let msg = match artifact.msg {
ConsensusMessage::BlockProposal(mut proposal) => {
// Lazy loading of block proposal and its payload
let block = proposal.content.as_mut();
let payload_hash = block.payload.get_hash();
let payload_key = IdKey::from((block.height(), payload_hash.get_ref()));
let log_clone = log.clone();
block.payload = Payload::new_with(
payload_hash.clone(),
block.payload.payload_type(),
Box::new(move || {
log_err!(
load_block_payload(db_env, artifacts, &payload_key, &log_clone),