-
Notifications
You must be signed in to change notification settings - Fork 983
/
rocksdb.rs
1952 lines (1781 loc) · 66.5 KB
/
rocksdb.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 persistent storage in RocksDB.
//!
//! The current storage tree is:
//! - `state`: the latest ledger state
//! - `ethereum_height`: the height of the last eth block processed by the
//! oracle
//! - `eth_events_queue`: a queue of confirmed ethereum events to be processed
//! in order
//! - `height`: the last committed block height
//! - `tx_queue`: txs to be decrypted in the next block
//! - `next_epoch_min_start_height`: minimum block height from which the next
//! epoch can start
//! - `next_epoch_min_start_time`: minimum block time from which the next
//! epoch can start
//! - `replay_protection`: hashes of the processed transactions
//! - `pred`: predecessor values of the top-level keys of the same name
//! - `tx_queue`
//! - `next_epoch_min_start_height`
//! - `next_epoch_min_start_time`
//! - `subspace`: accounts sub-spaces
//! - `{address}/{dyn}`: any byte data associated with accounts
//! - `diffs`: diffs in account subspaces' key-vals
//! - `new/{dyn}`: value set in block height `h`
//! - `old/{dyn}`: value from predecessor block height
//! - `block`: block state
//! - `results/{h}`: block results at height `h`
//! - `h`: for each block at height `h`:
//! - `tree`: merkle tree
//! - `root`: root hash
//! - `store`: the tree's store
//! - `hash`: block hash
//! - `time`: block time
//! - `epoch`: block epoch
//! - `address_gen`: established address generator
//! - `header`: block's header
//! - `replay_protection`: hashes of processed tx
//! - `all`: the hashes included up to the last block
//! - `last`: the hashes included in the last block
use std::fs::File;
use std::io::BufWriter;
use std::path::Path;
use std::str::FromStr;
use std::sync::Mutex;
use ark_serialize::Write;
use borsh::BorshDeserialize;
use borsh_ext::BorshSerializeExt;
use data_encoding::HEXLOWER;
use namada::core::types::ethereum_structs;
use namada::ledger::storage::types::PrefixIterator;
use namada::ledger::storage::{
types, BlockStateRead, BlockStateWrite, DBIter, DBWriteBatch, Error,
MerkleTreeStoresRead, Result, StoreType, DB,
};
use namada::types::internal::TxQueue;
use namada::types::storage::{
BlockHeight, BlockResults, Epoch, Epochs, EthEventsQueue, Header, Key,
KeySeg, KEY_SEGMENT_SEPARATOR,
};
use namada::types::time::DateTimeUtc;
use rayon::prelude::*;
use rocksdb::{
BlockBasedOptions, ColumnFamily, ColumnFamilyDescriptor, Direction,
FlushOptions, IteratorMode, Options, ReadOptions, WriteBatch,
};
use crate::config::utils::num_of_threads;
// TODO the DB schema will probably need some kind of versioning
/// Env. var to set a number of Rayon global worker threads
const ENV_VAR_ROCKSDB_COMPACTION_THREADS: &str =
"NAMADA_ROCKSDB_COMPACTION_THREADS";
/// Column family names
const SUBSPACE_CF: &str = "subspace";
const DIFFS_CF: &str = "diffs";
const STATE_CF: &str = "state";
const BLOCK_CF: &str = "block";
const REPLAY_PROTECTION_CF: &str = "replay_protection";
/// RocksDB handle
#[derive(Debug)]
pub struct RocksDB(rocksdb::DB);
/// DB Handle for batch writes.
#[derive(Default)]
pub struct RocksDBWriteBatch(WriteBatch);
/// Open RocksDB for the DB
pub fn open(
path: impl AsRef<Path>,
cache: Option<&rocksdb::Cache>,
) -> Result<RocksDB> {
let logical_cores = num_cpus::get();
let compaction_threads = num_of_threads(
ENV_VAR_ROCKSDB_COMPACTION_THREADS,
// If not set, default to quarter of logical CPUs count
logical_cores / 4,
) as i32;
tracing::info!(
"Using {} compactions threads for RocksDB.",
compaction_threads
);
// DB options
let mut db_opts = Options::default();
// This gives `compaction_threads` number to compaction threads and 1 thread
// for flush background jobs: https://github.com/facebook/rocksdb/blob/17ce1ca48be53ba29138f92dafc9c853d9241377/options/options.cc#L622
db_opts.increase_parallelism(compaction_threads);
db_opts.set_bytes_per_sync(1048576);
set_max_open_files(&mut db_opts);
// TODO the recommended default `options.compaction_pri =
// kMinOverlappingRatio` doesn't seem to be available in Rust
db_opts.create_missing_column_families(true);
db_opts.create_if_missing(true);
db_opts.set_atomic_flush(true);
let mut cfs = Vec::new();
let mut table_opts = BlockBasedOptions::default();
table_opts.set_block_size(16 * 1024);
table_opts.set_cache_index_and_filter_blocks(true);
table_opts.set_pin_l0_filter_and_index_blocks_in_cache(true);
if let Some(cache) = cache {
table_opts.set_block_cache(cache);
}
// latest format versions https://github.com/facebook/rocksdb/blob/d1c510baecc1aef758f91f786c4fbee3bc847a63/include/rocksdb/table.h#L394
table_opts.set_format_version(5);
// for subspace (read/update-intensive)
let mut subspace_cf_opts = Options::default();
subspace_cf_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
subspace_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
// ! recommended initial setup https://github.com/facebook/rocksdb/wiki/Setup-Options-and-Basic-Tuning#other-general-options
subspace_cf_opts.set_level_compaction_dynamic_level_bytes(true);
subspace_cf_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
subspace_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(SUBSPACE_CF, subspace_cf_opts));
// for diffs (insert-intensive)
let mut diffs_cf_opts = Options::default();
diffs_cf_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
diffs_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
diffs_cf_opts.set_compaction_style(rocksdb::DBCompactionStyle::Universal);
diffs_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(DIFFS_CF, diffs_cf_opts));
// for the ledger state (update-intensive)
let mut state_cf_opts = Options::default();
// No compression since the size of the state is small
state_cf_opts.set_level_compaction_dynamic_level_bytes(true);
state_cf_opts.set_compaction_style(rocksdb::DBCompactionStyle::Level);
state_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(STATE_CF, state_cf_opts));
// for blocks (insert-intensive)
let mut block_cf_opts = Options::default();
block_cf_opts.set_compression_type(rocksdb::DBCompressionType::Zstd);
block_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
block_cf_opts.set_compaction_style(rocksdb::DBCompactionStyle::Universal);
block_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(BLOCK_CF, block_cf_opts));
// for replay protection (read/insert-intensive)
let mut replay_protection_cf_opts = Options::default();
replay_protection_cf_opts
.set_compression_type(rocksdb::DBCompressionType::Zstd);
replay_protection_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
replay_protection_cf_opts.set_level_compaction_dynamic_level_bytes(true);
// Prioritize minimizing read amplification
replay_protection_cf_opts
.set_compaction_style(rocksdb::DBCompactionStyle::Level);
replay_protection_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(
REPLAY_PROTECTION_CF,
replay_protection_cf_opts,
));
rocksdb::DB::open_cf_descriptors(&db_opts, path, cfs)
.map(RocksDB)
.map_err(|e| Error::DBError(e.into_string()))
}
impl Drop for RocksDB {
fn drop(&mut self) {
self.flush(true).expect("flush failed");
}
}
impl RocksDB {
fn get_column_family(&self, cf_name: &str) -> Result<&ColumnFamily> {
self.0
.cf_handle(cf_name)
.ok_or(Error::DBError("No {cf_name} column family".to_string()))
}
/// Persist the diff of an account subspace key-val under the height where
/// it was changed.
fn write_subspace_diff(
&self,
height: BlockHeight,
key: &Key,
old_value: Option<&[u8]>,
new_value: Option<&[u8]>,
) -> Result<()> {
let cf = self.get_column_family(DIFFS_CF)?;
let key_prefix = Key::from(height.to_db_key());
if let Some(old_value) = old_value {
let old_val_key = key_prefix
.push(&"old".to_owned())
.map_err(Error::KeyError)?
.join(key)
.to_string();
self.0
.put_cf(cf, old_val_key, old_value)
.map_err(|e| Error::DBError(e.into_string()))?;
}
if let Some(new_value) = new_value {
let new_val_key = key_prefix
.push(&"new".to_owned())
.map_err(Error::KeyError)?
.join(key)
.to_string();
self.0
.put_cf(cf, new_val_key, new_value)
.map_err(|e| Error::DBError(e.into_string()))?;
}
Ok(())
}
/// Persist the diff of an account subspace key-val under the height where
/// it was changed in a batch write.
fn batch_write_subspace_diff(
&self,
batch: &mut RocksDBWriteBatch,
height: BlockHeight,
key: &Key,
old_value: Option<&[u8]>,
new_value: Option<&[u8]>,
) -> Result<()> {
let cf = self.get_column_family(DIFFS_CF)?;
let key_prefix = Key::from(height.to_db_key());
if let Some(old_value) = old_value {
let old_val_key = key_prefix
.push(&"old".to_owned())
.map_err(Error::KeyError)?
.join(key)
.to_string();
batch.0.put_cf(cf, old_val_key, old_value);
}
if let Some(new_value) = new_value {
let new_val_key = key_prefix
.push(&"new".to_owned())
.map_err(Error::KeyError)?
.join(key)
.to_string();
batch.0.put_cf(cf, new_val_key, new_value);
}
Ok(())
}
fn exec_batch(&mut self, batch: WriteBatch) -> Result<()> {
self.0
.write(batch)
.map_err(|e| Error::DBError(e.into_string()))
}
/// Dump last known block
pub fn dump_block(
&self,
out_file_path: std::path::PathBuf,
historic: bool,
height: Option<BlockHeight>,
) {
// Find the last block height
let state_cf = self
.get_column_family(STATE_CF)
.expect("State column family should exist");
let last_height: BlockHeight = types::decode(
self.0
.get_cf(state_cf, "height")
.expect("Unable to read DB")
.expect("No block height found"),
)
.expect("Unable to decode block height");
let height = height.unwrap_or(last_height);
let full_path = out_file_path
.with_file_name(format!(
"{}_{height}",
out_file_path
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_else(|| "dump_db".to_string())
))
.with_extension("toml");
let mut file = File::options()
.append(true)
.create_new(true)
.open(&full_path)
.expect("Cannot open the output file");
println!("Will write to {} ...", full_path.to_string_lossy());
if historic {
// Dump the keys prepended with the selected block height (includes
// subspace diff keys)
// Diffs
let cf = self
.get_column_family(DIFFS_CF)
.expect("Diffs column family should exist");
let prefix = height.raw();
self.dump_it(cf, Some(prefix.clone()), &mut file);
// Block
let cf = self
.get_column_family(BLOCK_CF)
.expect("Block column family should exist");
self.dump_it(cf, Some(prefix), &mut file);
}
// subspace
if height != last_height {
// Restoring subspace at specified height
let restored_subspace = self
.iter_prefix(None)
.par_bridge()
.fold(
|| "".to_string(),
|mut cur, (key, _value, _gas)| match self
.read_subspace_val_with_height(
&Key::from(key.to_db_key()),
height,
last_height,
)
.expect("Unable to find subspace key")
{
Some(value) => {
let val = HEXLOWER.encode(&value);
let new_line = format!("\"{key}\" = \"{val}\"\n");
cur.push_str(new_line.as_str());
cur
}
None => cur,
},
)
.reduce(
|| "".to_string(),
|mut a: String, b: String| {
a.push_str(&b);
a
},
);
file.write_all(restored_subspace.as_bytes())
.expect("Unable to write to output file");
} else {
// Just dump the current subspace
let cf = self
.get_column_family(SUBSPACE_CF)
.expect("Subspace column family should exist");
self.dump_it(cf, None, &mut file);
}
// replay protection
// Dump of replay protection keys is possible only at the last height or
// the previous one
if height == last_height {
let cf = self
.get_column_family(REPLAY_PROTECTION_CF)
.expect("Replay protection column family should exist");
self.dump_it(cf, None, &mut file);
} else if height == last_height - 1 {
let cf = self
.get_column_family(REPLAY_PROTECTION_CF)
.expect("Replay protection column family should exist");
self.dump_it(cf, Some("all".to_string()), &mut file);
}
println!("Done writing to {}", full_path.to_string_lossy());
}
/// Dump data
fn dump_it(
&self,
cf: &ColumnFamily,
prefix: Option<String>,
file: &mut File,
) {
let read_opts = make_iter_read_opts(prefix.clone());
let iter = if let Some(prefix) = prefix {
self.0.iterator_cf_opt(
cf,
read_opts,
IteratorMode::From(prefix.as_bytes(), Direction::Forward),
)
} else {
self.0.iterator_cf_opt(cf, read_opts, IteratorMode::Start)
};
let mut buf = BufWriter::new(file);
for (key, raw_val, _gas) in PersistentPrefixIterator(
PrefixIterator::new(iter, String::default()),
// Empty string to prevent prefix stripping, the prefix is
// already in the enclosed iterator
) {
let val = HEXLOWER.encode(&raw_val);
let bytes = format!("\"{key}\" = \"{val}\"\n");
buf.write_all(bytes.as_bytes())
.expect("Unable to write to buffer");
}
buf.flush().expect("Unable to write to output file");
}
/// Rollback to previous block. Given the inner working of tendermint
/// rollback and of the key structure of Namada, calling rollback more than
/// once without restarting the chain results in a single rollback.
pub fn rollback(
&mut self,
tendermint_block_height: BlockHeight,
) -> Result<()> {
let last_block = self.read_last_block()?.ok_or(Error::DBError(
"Missing last block in storage".to_string(),
))?;
tracing::info!(
"Namada last block height: {}, Tendermint last block height: {}",
last_block.height,
tendermint_block_height
);
// If the block height to which tendermint rolled back matches the
// Namada height, there's no need to rollback
if tendermint_block_height == last_block.height {
tracing::info!(
"Namada height already matches the rollback Tendermint \
height, no need to rollback."
);
return Ok(());
}
let mut batch = WriteBatch::default();
let previous_height =
BlockHeight::from(u64::from(last_block.height) - 1);
let state_cf = self.get_column_family(STATE_CF)?;
// Revert the non-height-prepended metadata storage keys which get
// updated with every block. Because of the way we save these
// three keys in storage we can only perform one rollback before
// restarting the chain
tracing::info!("Reverting non-height-prepended metadata keys");
batch.put_cf(state_cf, "height", types::encode(&previous_height));
for metadata_key in [
"next_epoch_min_start_height",
"next_epoch_min_start_time",
"tx_queue",
] {
let previous_key = format!("pred/{}", metadata_key);
let previous_value = self
.0
.get_cf(state_cf, previous_key.as_bytes())
.map_err(|e| Error::DBError(e.to_string()))?
.ok_or(Error::UnknownKey { key: previous_key })?;
batch.put_cf(state_cf, metadata_key, previous_value);
// NOTE: we cannot restore the "pred/" keys themselves since we
// don't have their predecessors in storage, but there's no need to
// since we cannot do more than one rollback anyway because of
// Tendermint.
}
// Delete block results for the last block
let block_cf = self.get_column_family(BLOCK_CF)?;
tracing::info!("Removing last block results");
batch.delete_cf(block_cf, format!("results/{}", last_block.height));
// Delete the tx hashes included in the last block
let reprot_cf = self.get_column_family(REPLAY_PROTECTION_CF)?;
tracing::info!("Removing replay protection hashes");
batch.delete_cf(reprot_cf, "last");
// Execute next step in parallel
let batch = Mutex::new(batch);
tracing::info!("Restoring previous hight subspace diffs");
self.iter_prefix(None).par_bridge().try_for_each(
|(key, _value, _gas)| -> Result<()> {
// Restore previous height diff if present, otherwise delete the
// subspace key
let subspace_cf = self.get_column_family(SUBSPACE_CF)?;
match self.read_subspace_val_with_height(
&Key::from(key.to_db_key()),
previous_height,
last_block.height,
)? {
Some(previous_value) => batch.lock().unwrap().put_cf(
subspace_cf,
&key,
previous_value,
),
None => batch.lock().unwrap().delete_cf(subspace_cf, &key),
}
Ok(())
},
)?;
// Look for diffs in this block to find what has been deleted
let diff_new_key_prefix = Key {
segments: vec![
last_block.height.to_db_key(),
"new".to_string().to_db_key(),
],
};
{
let mut batch_guard = batch.lock().unwrap();
let subspace_cf = self.get_column_family(SUBSPACE_CF)?;
for (key, val, _) in
iter_diffs_prefix(self, last_block.height, true)
{
let key = Key::parse(key).unwrap();
let diff_new_key = diff_new_key_prefix.join(&key);
if self.read_subspace_val(&diff_new_key)?.is_none() {
// If there is no new value, it has been deleted in this
// block and we have to restore it
batch_guard.put_cf(subspace_cf, key.to_string(), val)
}
}
}
tracing::info!("Deleting keys prepended with the last height");
let mut batch = batch.into_inner().unwrap();
let prefix = last_block.height.to_string();
let mut delete_keys = |cf: &ColumnFamily| {
let read_opts = make_iter_read_opts(Some(prefix.clone()));
let iter = self.0.iterator_cf_opt(
cf,
read_opts,
IteratorMode::From(prefix.as_bytes(), Direction::Forward),
);
for (key, _value, _gas) in PersistentPrefixIterator(
// Empty prefix string to prevent stripping
PrefixIterator::new(iter, String::default()),
) {
batch.delete_cf(cf, key);
}
};
// Delete any height-prepended key in subspace diffs
let diffs_cf = self.get_column_family(DIFFS_CF)?;
delete_keys(diffs_cf);
// Delete any height-prepended key in the block
delete_keys(block_cf);
// Write the batch and persist changes to disk
tracing::info!("Flushing restored state to disk");
self.exec_batch(batch)
}
}
impl DB for RocksDB {
type Cache = rocksdb::Cache;
type WriteBatch = RocksDBWriteBatch;
fn open(
db_path: impl AsRef<std::path::Path>,
cache: Option<&Self::Cache>,
) -> Self {
open(db_path, cache).expect("cannot open the DB")
}
fn flush(&self, wait: bool) -> Result<()> {
let mut flush_opts = FlushOptions::default();
flush_opts.set_wait(wait);
self.0
.flush_opt(&flush_opts)
.map_err(|e| Error::DBError(e.into_string()))
}
fn read_last_block(&self) -> Result<Option<BlockStateRead>> {
// Block height
let state_cf = self.get_column_family(STATE_CF)?;
let height: BlockHeight = match self
.0
.get_cf(state_cf, "height")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => {
// TODO if there's an issue decoding this height, should we try
// load its predecessor instead?
types::decode(bytes).map_err(Error::CodingError)?
}
None => return Ok(None),
};
// Block results
let block_cf = self.get_column_family(BLOCK_CF)?;
let results_path = format!("results/{}", height.raw());
let results: BlockResults = match self
.0
.get_cf(block_cf, results_path)
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => return Ok(None),
};
// Epoch start height and time
let next_epoch_min_start_height: BlockHeight = match self
.0
.get_cf(state_cf, "next_epoch_min_start_height")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!(
"Couldn't load next epoch start height from the DB"
);
return Ok(None);
}
};
let next_epoch_min_start_time: DateTimeUtc = match self
.0
.get_cf(state_cf, "next_epoch_min_start_time")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!(
"Couldn't load next epoch start time from the DB"
);
return Ok(None);
}
};
let update_epoch_blocks_delay: Option<u32> = match self
.0
.get_cf(state_cf, "update_epoch_blocks_delay")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!(
"Couldn't load epoch update block delay from the DB"
);
return Ok(None);
}
};
let tx_queue: TxQueue = match self
.0
.get_cf(state_cf, "tx_queue")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!("Couldn't load tx queue from the DB");
return Ok(None);
}
};
let ethereum_height: Option<ethereum_structs::BlockHeight> = match self
.0
.get_cf(state_cf, "ethereum_height")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!("Couldn't load ethereum height from the DB");
return Ok(None);
}
};
let eth_events_queue: EthEventsQueue = match self
.0
.get_cf(state_cf, "eth_events_queue")
.map_err(|e| Error::DBError(e.into_string()))?
{
Some(bytes) => types::decode(bytes).map_err(Error::CodingError)?,
None => {
tracing::error!(
"Couldn't load the eth events queue from the DB"
);
return Ok(None);
}
};
// Load data at the height
let prefix = format!("{}/", height.raw());
let mut read_opts = ReadOptions::default();
read_opts.set_total_order_seek(false);
let next_height_prefix = format!("{}/", height.next_height().raw());
read_opts.set_iterate_upper_bound(next_height_prefix);
let mut merkle_tree_stores = MerkleTreeStoresRead::default();
let mut hash = None;
let mut time = None;
let mut epoch = None;
let mut pred_epochs = None;
let mut address_gen = None;
for value in self.0.iterator_cf_opt(
block_cf,
read_opts,
IteratorMode::From(prefix.as_bytes(), Direction::Forward),
) {
let (key, bytes) = match value {
Ok(data) => data,
Err(e) => return Err(Error::DBError(e.into_string())),
};
let path = &String::from_utf8((*key).to_vec()).map_err(|e| {
Error::Temporary {
error: format!(
"Cannot convert path from utf8 bytes to string: {}",
e
),
}
})?;
let segments: Vec<&str> =
path.split(KEY_SEGMENT_SEPARATOR).collect();
match segments.get(1) {
Some(prefix) => match *prefix {
"tree" => match segments.get(2) {
Some(s) => {
let st = StoreType::from_str(s)?;
match segments.get(3) {
Some(&"root") => merkle_tree_stores.set_root(
&st,
types::decode(bytes)
.map_err(Error::CodingError)?,
),
Some(&"store") => merkle_tree_stores
.set_store(st.decode_store(bytes)?),
_ => unknown_key_error(path)?,
}
}
None => unknown_key_error(path)?,
},
"header" => {
// the block header doesn't have to be restored
}
"hash" => {
hash = Some(
types::decode(bytes).map_err(Error::CodingError)?,
)
}
"time" => {
time = Some(
types::decode(bytes).map_err(Error::CodingError)?,
)
}
"epoch" => {
epoch = Some(
types::decode(bytes).map_err(Error::CodingError)?,
)
}
"pred_epochs" => {
pred_epochs = Some(
types::decode(bytes).map_err(Error::CodingError)?,
)
}
"address_gen" => {
address_gen = Some(
types::decode(bytes).map_err(Error::CodingError)?,
);
}
_ => unknown_key_error(path)?,
},
None => unknown_key_error(path)?,
}
}
match (hash, time, epoch, pred_epochs, address_gen) {
(
Some(hash),
Some(time),
Some(epoch),
Some(pred_epochs),
Some(address_gen),
) => Ok(Some(BlockStateRead {
merkle_tree_stores,
hash,
height,
time,
epoch,
pred_epochs,
results,
next_epoch_min_start_height,
next_epoch_min_start_time,
update_epoch_blocks_delay,
address_gen,
tx_queue,
ethereum_height,
eth_events_queue,
})),
_ => Err(Error::Temporary {
error: "Essential data couldn't be read from the DB"
.to_string(),
}),
}
}
fn add_block_to_batch(
&self,
state: BlockStateWrite,
batch: &mut Self::WriteBatch,
is_full_commit: bool,
) -> Result<()> {
let BlockStateWrite {
merkle_tree_stores,
header,
hash,
height,
time,
epoch,
pred_epochs,
next_epoch_min_start_height,
next_epoch_min_start_time,
update_epoch_blocks_delay,
address_gen,
results,
tx_queue,
ethereum_height,
eth_events_queue,
}: BlockStateWrite = state;
// Epoch start height and time
let state_cf = self.get_column_family(STATE_CF)?;
if let Some(current_value) = self
.0
.get_cf(state_cf, "next_epoch_min_start_height")
.map_err(|e| Error::DBError(e.into_string()))?
{
// Write the predecessor value for rollback
batch.0.put_cf(
state_cf,
"pred/next_epoch_min_start_height",
current_value,
);
}
batch.0.put_cf(
state_cf,
"next_epoch_min_start_height",
types::encode(&next_epoch_min_start_height),
);
if let Some(current_value) = self
.0
.get_cf(state_cf, "next_epoch_min_start_time")
.map_err(|e| Error::DBError(e.into_string()))?
{
// Write the predecessor value for rollback
batch.0.put_cf(
state_cf,
"pred/next_epoch_min_start_time",
current_value,
);
}
batch.0.put_cf(
state_cf,
"next_epoch_min_start_time",
types::encode(&next_epoch_min_start_time),
);
if let Some(current_value) = self
.0
.get_cf(state_cf, "update_epoch_blocks_delay")
.map_err(|e| Error::DBError(e.into_string()))?
{
// Write the predecessor value for rollback
batch.0.put_cf(
state_cf,
"pred/update_epoch_blocks_delay",
current_value,
);
}
batch.0.put_cf(
state_cf,
"update_epoch_blocks_delay",
types::encode(&update_epoch_blocks_delay),
);
// Tx queue
if let Some(pred_tx_queue) = self
.0
.get_cf(state_cf, "tx_queue")
.map_err(|e| Error::DBError(e.into_string()))?
{
// Write the predecessor value for rollback
batch.0.put_cf(state_cf, "pred/tx_queue", pred_tx_queue);
}
batch
.0
.put_cf(state_cf, "tx_queue", types::encode(&tx_queue));
batch.0.put_cf(
state_cf,
"ethereum_height",
types::encode(ðereum_height),
);
batch.0.put_cf(
state_cf,
"eth_events_queue",
types::encode(ð_events_queue),
);
let block_cf = self.get_column_family(BLOCK_CF)?;
let prefix_key = Key::from(height.to_db_key());
// Merkle tree
{
let prefix_key = prefix_key
.push(&"tree".to_owned())
.map_err(Error::KeyError)?;
for st in StoreType::iter() {
if *st == StoreType::Base || is_full_commit {
let prefix_key = prefix_key
.push(&st.to_string())
.map_err(Error::KeyError)?;
let root_key = prefix_key
.push(&"root".to_owned())
.map_err(Error::KeyError)?;
batch.0.put_cf(
block_cf,
root_key.to_string(),
types::encode(merkle_tree_stores.root(st)),
);
let store_key = prefix_key
.push(&"store".to_owned())
.map_err(Error::KeyError)?;
batch.0.put_cf(
block_cf,
store_key.to_string(),
merkle_tree_stores.store(st).encode(),
);
}
}
}
// Block header
{
if let Some(h) = header {
let key = prefix_key
.push(&"header".to_owned())
.map_err(Error::KeyError)?;
batch
.0
.put_cf(block_cf, key.to_string(), h.serialize_to_vec());
}
}
// Block hash
{
let key = prefix_key
.push(&"hash".to_owned())
.map_err(Error::KeyError)?;
batch
.0
.put_cf(block_cf, key.to_string(), types::encode(&hash));
}
// Block time
{
let key = prefix_key
.push(&"time".to_owned())
.map_err(Error::KeyError)?;
batch
.0
.put_cf(block_cf, key.to_string(), types::encode(&time));
}
// Block epoch
{
let key = prefix_key
.push(&"epoch".to_owned())
.map_err(Error::KeyError)?;
batch
.0
.put_cf(block_cf, key.to_string(), types::encode(&epoch));
}
// Block results
{
let results_path = format!("results/{}", height.raw());
batch
.0
.put_cf(block_cf, results_path, types::encode(&results));
}
// Predecessor block epochs
{
let key = prefix_key
.push(&"pred_epochs".to_owned())
.map_err(Error::KeyError)?;
batch.0.put_cf(
block_cf,
key.to_string(),
types::encode(&pred_epochs),
);
}
// Address gen
{
let key = prefix_key
.push(&"address_gen".to_owned())