-
Notifications
You must be signed in to change notification settings - Fork 1k
Expand file tree
/
Copy pathrocksdb.rs
More file actions
3001 lines (2686 loc) · 101 KB
/
rocksdb.rs
File metadata and controls
3001 lines (2686 loc) · 101 KB
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
//! - `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
//! - `update_epoch_blocks_delay`: number of missing blocks before updating
//! PoS with CometBFT
//! - `pred`: predecessor values of the top-level keys of the same name
//! - `next_epoch_min_start_height`
//! - `next_epoch_min_start_time`
//! - `commit_only_data_commitment`
//! - `update_epoch_blocks_delay`
//! - `conversion_state`: MASP conversion state
//! - `subspace`: accounts sub-spaces
//! - `{address}/{dyn}`: any byte data associated with accounts
//! - `diffs`: diffs in account subspaces' key-vals modified with `persist_diff
//! == true`
//! - `{height}/new/{dyn}`: value set in block height `h`
//! - `{height}/old/{dyn}`: value from predecessor block height
//! - `rollback`: diffs in account subspaces' key-vals for keys modified with
//! `persist_diff == false` which are only kept for 1 block to support
//! rollback
//! - `{height}/new/{dyn}`: value set in block height `h`
//! - `{height}/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
//! - `time`: block time
//! - `epoch`: block epoch
//! - `address_gen`: established address generator
//! - `header`: block's header
//! - `replay_protection`: hashes of processed tx for replay protection purposes
//! - `current/{hash}`: a hash included in the current block
//! - `{hash}`: a hash included in previous blocks
use std::fs::File;
use std::io::{BufWriter, Read, Seek, Write};
use std::mem::ManuallyDrop;
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::sync::Mutex;
use data_encoding::HEXLOWER;
use itertools::Either;
use namada_replay_protection as replay_protection;
use namada_sdk::arith::checked;
use namada_sdk::borsh::{BorshDeserialize, BorshSerialize, BorshSerializeExt};
use namada_sdk::collections::HashSet;
use namada_sdk::eth_bridge::storage::bridge_pool;
use namada_sdk::eth_bridge::storage::proof::BridgePoolRootProof;
use namada_sdk::gas::Gas;
use namada_sdk::hash::Hash;
use namada_sdk::state::merkle_tree::{
tree_key_prefix_with_epoch, tree_key_prefix_with_height,
};
use namada_sdk::state::{
BlockStateRead, BlockStateWrite, DB, DBIter, DBWriteBatch,
DbError as Error, DbResult as Result, MerkleTreeStoresRead,
PatternIterator, PrefixIterator, StoreType,
};
use namada_sdk::storage::{
BLOCK_CF, BlockHeader, BlockHeight, DBUpdateVisitor, DIFFS_CF, DbColFam,
Epoch, Key, KeySeg, REPLAY_PROTECTION_CF, ROLLBACK_CF, STATE_CF,
SUBSPACE_CF,
};
use namada_sdk::{decode, encode, ethereum_events};
use rayon::prelude::*;
use regex::Regex;
use rocksdb::{
BlockBasedOptions, ColumnFamily, ColumnFamilyDescriptor, DBCompactionStyle,
DBCompressionType, 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";
const BLOCK_HEIGHT_KEY: &str = "height";
const NEXT_EPOCH_MIN_START_HEIGHT_KEY: &str = "next_epoch_min_start_height";
const NEXT_EPOCH_MIN_START_TIME_KEY: &str = "next_epoch_min_start_time";
const UPDATE_EPOCH_BLOCKS_DELAY_KEY: &str = "update_epoch_blocks_delay";
const COMMIT_ONLY_DATA_KEY: &str = "commit_only_data_commitment";
const CONVERSION_STATE_KEY: &str = "conversion_state";
const ETHEREUM_HEIGHT_KEY: &str = "ethereum_height";
const ETH_EVENTS_QUEUE_KEY: &str = "eth_events_queue";
const RESULTS_KEY_PREFIX: &str = "results";
const PRED_KEY_PREFIX: &str = "pred";
const MERKLE_TREE_ROOT_KEY_SEGMENT: &str = "root";
const MERKLE_TREE_STORE_KEY_SEGMENT: &str = "store";
const BLOCK_HEADER_KEY_SEGMENT: &str = "header";
const BLOCK_TIME_KEY_SEGMENT: &str = "time";
const EPOCH_KEY_SEGMENT: &str = "epoch";
const PRED_EPOCHS_KEY_SEGMENT: &str = "pred_epochs";
const ADDRESS_GEN_KEY_SEGMENT: &str = "address_gen";
const OLD_DIFF_PREFIX: &str = "old";
const NEW_DIFF_PREFIX: &str = "new";
// 10 MB
const MAX_STATE_SYNC_CHUNK_SIZE: usize = 10_000_000;
/// RocksDB handle
#[derive(Debug)]
pub struct RocksDB {
/// Handle to the db
inner: ManuallyDrop<rocksdb::DB>,
/// Indicates if read only
read_only: bool,
/// Whether the handle is invalid
invalid_handle: bool,
}
/// DB Handle for batch writes.
#[derive(Default)]
pub struct RocksDBWriteBatch(WriteBatch);
/// Open RocksDB for the DB
pub fn open(
path: impl AsRef<Path>,
read_only: bool,
cache: Option<&rocksdb::Cache>,
) -> Result<RocksDB> {
let logical_cores = num_cpus::get();
let compaction_threads = i32::try_from(num_of_threads(
ENV_VAR_ROCKSDB_COMPACTION_THREADS,
// If not set, default to quarter of logical CPUs count
logical_cores / 4,
))?;
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(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(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(DBCompressionType::Zstd);
diffs_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
diffs_cf_opts.set_compaction_style(DBCompactionStyle::Universal);
diffs_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(DIFFS_CF, diffs_cf_opts));
// for non-persisted diffs for rollback (read/update-intensive)
let mut rollback_cf_opts = Options::default();
rollback_cf_opts.set_compression_type(DBCompressionType::Zstd);
rollback_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
rollback_cf_opts.set_compaction_style(DBCompactionStyle::Level);
rollback_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(ROLLBACK_CF, rollback_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(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(DBCompressionType::Zstd);
block_cf_opts.set_compression_options(0, 0, 0, 1024 * 1024);
block_cf_opts.set_compaction_style(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(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(DBCompactionStyle::Level);
replay_protection_cf_opts.set_block_based_table_factory(&table_opts);
cfs.push(ColumnFamilyDescriptor::new(
REPLAY_PROTECTION_CF,
replay_protection_cf_opts,
));
Ok(if read_only {
RocksDB {
inner: ManuallyDrop::new(
rocksdb::DB::open_cf_descriptors_read_only(
&db_opts, path, cfs, false,
)
.map_err(|e| Error::DBError(e.into_string()))?,
),
invalid_handle: false,
read_only: true,
}
} else {
RocksDB {
inner: ManuallyDrop::new(
rocksdb::DB::open_cf_descriptors(&db_opts, path, cfs)
.map_err(|e| Error::DBError(e.into_string()))?,
),
invalid_handle: false,
read_only: false,
}
})
}
impl Drop for RocksDB {
fn drop(&mut self) {
if self.invalid_handle {
return;
}
if !self.read_only {
self.flush(true).expect("flush failed");
}
unsafe { ManuallyDrop::drop(&mut self.inner) }
}
}
impl RocksDB {
fn get_column_family(&self, cf_name: &str) -> Result<&ColumnFamily> {
self.inner
.cf_handle(cf_name)
.ok_or(Error::DBError("No {cf_name} column family".to_string()))
}
fn read_value<T>(
&self,
cf: &ColumnFamily,
key: impl AsRef<str>,
) -> Result<Option<T>>
where
T: BorshDeserialize,
{
self.read_value_bytes(cf, key)?
.map(|bytes| decode(bytes).map_err(Error::CodingError))
.transpose()
}
fn read_value_bytes(
&self,
cf: &ColumnFamily,
key: impl AsRef<str>,
) -> Result<Option<Vec<u8>>> {
self.inner
.get_cf(cf, key.as_ref())
.map_err(|e| Error::DBError(e.into_string()))
}
fn add_state_value_to_batch<T>(
&self,
cf: &ColumnFamily,
key: impl AsRef<str>,
value: &T,
batch: &mut RocksDBWriteBatch,
) -> Result<()>
where
T: BorshSerialize,
{
if let Some(current_value) = self
.inner
.get_cf(cf, key.as_ref())
.map_err(|e| Error::DBError(e.into_string()))?
{
batch.0.put_cf(
cf,
format!("{PRED_KEY_PREFIX}/{}", key.as_ref()),
current_value,
);
}
self.add_value_to_batch(cf, key, value, batch);
Ok(())
}
fn add_value_to_batch<T>(
&self,
cf: &ColumnFamily,
key: impl AsRef<str>,
value: &T,
batch: &mut RocksDBWriteBatch,
) where
T: BorshSerialize,
{
self.add_value_bytes_to_batch(cf, key, encode(&value), batch)
}
fn add_value_bytes_to_batch(
&self,
cf: &ColumnFamily,
key: impl AsRef<str>,
value: Vec<u8>,
batch: &mut RocksDBWriteBatch,
) {
batch.0.put_cf(cf, key.as_ref(), value);
}
/// 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]>,
persist_diffs: bool,
) -> Result<()> {
let cf = if persist_diffs {
self.get_column_family(DIFFS_CF)?
} else {
self.get_column_family(ROLLBACK_CF)?
};
let (old_val_key, new_val_key) = old_and_new_diff_key(key, height)?;
if let Some(old_value) = old_value {
batch.0.put_cf(cf, old_val_key, old_value);
}
if let Some(new_value) = new_value {
batch.0.put_cf(cf, new_val_key, new_value);
}
Ok(())
}
/// 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 = self
.read_value(state_cf, BLOCK_HEIGHT_KEY)
.expect("Unable to read DB")
.expect("No block height found");
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
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);
}
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.inner.iterator_cf_opt(
cf,
read_opts,
IteratorMode::From(prefix.as_bytes(), Direction::Forward),
)
} else {
self.inner
.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");
}
/// Create a checkpoint of the state in RocksDB at block height
/// `block_height`.
pub fn checkpoint(
&self,
base_dir: PathBuf,
block_height: BlockHeight,
) -> Result<DbSnapshot> {
let checkpoint = rocksdb::checkpoint::Checkpoint::new(&self.inner)
.map_err(|e| Error::DBError(e.to_string()))?;
let snapshot_path = SnapshotPath(base_dir, block_height);
std::fs::create_dir_all(snapshot_path.base()).or_else(|e| {
if e.kind() == std::io::ErrorKind::AlreadyExists {
Ok(())
} else {
Err(Error::DBError(e.to_string()))
}
})?;
checkpoint
.create_checkpoint(snapshot_path.temp_rocksdb())
.map_err(|e| Error::DBError(e.to_string()))?;
Ok(DbSnapshot(snapshot_path))
}
/// 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 = RocksDB::batch();
let previous_height =
last_block.height.prev_height().expect("Must have a pred");
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
.0
.put_cf(state_cf, BLOCK_HEIGHT_KEY, encode(&previous_height));
for metadata_key in [
NEXT_EPOCH_MIN_START_HEIGHT_KEY,
NEXT_EPOCH_MIN_START_TIME_KEY,
COMMIT_ONLY_DATA_KEY,
UPDATE_EPOCH_BLOCKS_DELAY_KEY,
] {
let previous_key = format!("{PRED_KEY_PREFIX}/{metadata_key}");
let previous_value = self
.read_value_bytes(state_cf, &previous_key)?
.ok_or(Error::UnknownKey { key: previous_key })?;
self.add_value_bytes_to_batch(
state_cf,
metadata_key,
previous_value,
&mut batch,
);
// 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
// CometBFT.
}
// Revert conversion state if the epoch had been changed
if last_block.pred_epochs.get_epoch(previous_height)
!= Some(last_block.epoch)
{
let previous_key =
format!("{PRED_KEY_PREFIX}/{CONVERSION_STATE_KEY}");
let previous_value = self
.read_value_bytes(state_cf, &previous_key)?
.ok_or(Error::UnknownKey { key: previous_key })?;
self.add_value_bytes_to_batch(
state_cf,
CONVERSION_STATE_KEY,
previous_value,
&mut batch,
);
}
// Delete block results for the last block
let block_cf = self.get_column_family(BLOCK_CF)?;
tracing::info!("Removing last block results");
batch.0.delete_cf(
block_cf,
format!("{RESULTS_KEY_PREFIX}/{}", last_block.height),
);
// Restore the state of replay protection to the last block
let reprot_cf = self.get_column_family(REPLAY_PROTECTION_CF)?;
tracing::info!("Restoring replay protection state");
// Remove the "current" tx hashes
for (current_key, _, _) in self.iter_current_replay_protection() {
batch.0.delete_cf(reprot_cf, current_key);
}
// Execute next step in parallel
let batch = Mutex::new(batch);
tracing::info!("Restoring previous height 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().0.put_cf(
subspace_cf,
&key,
previous_value,
),
None => {
batch.lock().unwrap().0.delete_cf(subspace_cf, &key)
}
}
Ok(())
},
)?;
let mut batch = batch.into_inner().unwrap();
let subspace_cf = self.get_column_family(SUBSPACE_CF)?;
let diffs_cf = self.get_column_family(DIFFS_CF)?;
// 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_DIFF_PREFIX.to_string().to_db_key(),
],
};
for (key_str, val, _) in
iter_diffs_prefix(self, diffs_cf, last_block.height, None, true)
{
let key = Key::parse(&key_str).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.0.put_cf(subspace_cf, key_str, val)
}
}
// Look for non-persisted diffs for rollback
let rollback_cf = self.get_column_family(ROLLBACK_CF)?;
// Iterate the old keys first and keep a set of keys that have old val
let mut keys_with_old_value = HashSet::<String>::new();
for (key_str, val, _) in
iter_diffs_prefix(self, rollback_cf, last_block.height, None, true)
{
// If there is no new value, it has been deleted in this
// block and we have to restore it
keys_with_old_value.insert(key_str.clone());
batch.0.put_cf(subspace_cf, key_str, val)
}
// Then the new keys
for (key_str, _val, _) in
iter_diffs_prefix(self, rollback_cf, last_block.height, None, false)
{
if !keys_with_old_value.contains(&key_str) {
// If there was no old value it means that the key was newly
// written in the last block and we have to delete it
batch.0.delete_cf(subspace_cf, key_str)
}
}
tracing::info!("Deleting keys prepended with the last height");
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.inner.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.0.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)
}
#[inline]
pub fn column_families(&self) -> [(&'static str, &ColumnFamily); 6] {
DbColFam::all()
.iter()
.map(|cf| {
(
*cf,
self.get_column_family(cf)
.expect("Failed to read column family"),
)
})
.collect::<Vec<_>>()
.try_into()
.map_err(|_| "There should be exactly six column families")
.unwrap()
}
/// Read diffs of non-persisted key-vals that are only kept for rollback of
/// one block height.
#[cfg(test)]
pub fn read_rollback_val(
&self,
key: &Key,
height: BlockHeight,
is_old: bool,
) -> Result<Option<Vec<u8>>> {
let rollback_cf = self.get_column_family(ROLLBACK_CF)?;
let key = if is_old {
old_and_new_diff_key(key, height)?.0
} else {
old_and_new_diff_key(key, height)?.1
};
self.inner
.get_cf(rollback_cf, key)
.map_err(|e| Error::DBError(e.into_string()))
}
/// Writes an entry directly to a db batch update
/// directly
pub fn insert_entry(
&self,
batch: &mut RocksDBWriteBatch,
cf: &DbColFam,
key: &Key,
new_value: impl AsRef<[u8]>,
) -> Result<()> {
// NB: the following code only updates values
// written to at the last committed height
let val = new_value.as_ref();
// Write the new key-val in the Db column family
let cf_name = self.get_column_family(cf.to_str())?;
self.add_value_bytes_to_batch(
cf_name,
key.to_string(),
val.to_vec(),
batch,
);
Ok(())
}
}
/// The path to a snapshot.
#[derive(Clone, Debug)]
pub struct SnapshotPath(pub PathBuf, pub BlockHeight);
impl SnapshotPath {
/// Return the root path where snapshots are stored.
pub fn snapshot_root_path(mut base_dir: PathBuf) -> PathBuf {
base_dir.push("snapshots");
base_dir
}
/// Remove all data pertaining to the current snapshot.
pub fn remove(&self) -> std::io::Result<()> {
std::fs::remove_dir_all(self.base())
}
/// Return the base path associated with this [`SnapshotPath`].
pub fn base(&self) -> PathBuf {
let mut buf = Self::snapshot_root_path(self.0.clone());
let height = self.1.0;
buf.push(format!("block-{height:016}"));
buf
}
/// Return the chunk hashes path associated with this [`SnapshotPath`].
pub fn chunk_hashes(&self) -> PathBuf {
let mut buf = self.base();
buf.push("chunks-hashed");
buf
}
/// Return the root of the chunk hashes tree path associated with this
/// [`SnapshotPath`].
pub fn chunks_root_hash(&self) -> PathBuf {
let mut buf = self.base();
buf.push("chunks-root-hash");
buf
}
/// Return the temporary rocksdb path associated with this [`SnapshotPath`].
pub fn temp_rocksdb(&self) -> PathBuf {
let mut buf = self.base();
buf.push("db");
buf
}
/// Return the temporary tarball path associated with this [`SnapshotPath`].
///
/// The value of `compression_extension` should reflect the compression
/// algorithm used (e.g. `gz` for Gzip).
pub fn temp_tarball(&self, compression_extension: &str) -> PathBuf {
let mut buf = self.base();
buf.push(format!("db.tar.{compression_extension}"));
buf
}
/// Return the path of the chunk `chk` associated with this
/// [`SnapshotPath`].
pub fn chunk_with_id(&self, chk: usize) -> PathBuf {
let mut buf = self.base();
buf.push(format!("chunk-{chk:032}"));
buf
}
}
/// Metadata pertaining to some database snapshot.
#[derive(Debug)]
pub struct DbSnapshotMeta {
/// The height of the snapshot.
pub height: BlockHeight,
/// List of the hashes of all chunks.
pub chunk_hashes: Vec<Hash>,
/// Hash of all the chunk hashes, forming a shallow tree.
pub root_hash: Hash,
}
#[derive(Clone)]
pub struct DbSnapshot(pub SnapshotPath);
impl DbSnapshot {
/// The magic number referring to the format of the snapshot.
pub const FORMAT_MAGIC: u32 = 0;
/// Package and chunk the contents of the db snapshot.
// NB: passing an owned `self` guarantees we don't attempt to call
// this method again, which removes the temporary checkpoint dir
// created by rocksdb
pub fn package(self) -> std::io::Result<()> {
self.build_tarball()?;
self.chunk_snapshot(MAX_STATE_SYNC_CHUNK_SIZE)?;
Ok(())
}
pub fn unpack(
archive_file: &mut std::fs::File,
dest: impl AsRef<Path>,
) -> std::io::Result<()> {
use zstd::stream::read::Decoder;
let file_buf_reader = std::io::BufReader::new(archive_file);
let zstd_decoder = Decoder::new(file_buf_reader)?;
let mut archive = tar::Archive::new(zstd_decoder);
archive.unpack(dest)?;
Ok(())
}
pub(crate) fn build_tarball(&self) -> std::io::Result<()> {
use zstd::stream::write::Encoder;
let snapshot_temp_db_path = self.0.temp_rocksdb();
let mut tar_builder = {
let file_handle = File::create(self.0.temp_tarball("zst"))?;
let zstd_encoder = Encoder::new(file_handle, 0)?.auto_finish();
tar::Builder::new(zstd_encoder)
};
// build tarball with rocksdb checkpoint contents
tar_builder.append_dir_all("db", &snapshot_temp_db_path)?;
tar_builder.finish()?;
_ = tar_builder;
// remove aux checkpoint dir
std::fs::remove_dir_all(&snapshot_temp_db_path)
}
fn chunk_snapshot(&self, max_chunk: usize) -> std::io::Result<()> {
let tarball_path = self.0.temp_tarball("zst");
let mut buf = vec![0; max_chunk];
let mut file = File::open(&tarball_path)?;
let mut eof = false;
let mut chunk_hashes = vec![];
// TODO: we can use tokio here to read chunks
// in parallel
//
// 1. determine tar archive size
// 2. spawn len / MAX_STATE_SYNC_CHUNK_SIZE tasks
// 3. spawn one more task if necessary to read chunk smaller than
// MAX_STATE_SYNC_CHUNK_SIZE
// 4. assemble read data (need to store hash of the chunk)
for chunk_id in 0.. {
let mut read = 0;
// read up to `MAX_STATE_SYNC_CHUNK_SIZE` bytes
while read != max_chunk {
match file.read(&mut buf[read..]) {
Ok(0) => {
eof = true;
break;
}
Ok(n) => checked!(read += n).unwrap(),
Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
let chunk = &buf[..read];
std::fs::write(self.0.chunk_with_id(chunk_id), chunk)?;
chunk_hashes.push(Hash::sha256(chunk));
if eof {
break;
}
}
let chunk_hashes = chunk_hashes.serialize_to_vec();
let hash_of_all_chunks = Hash::sha256(&chunk_hashes);
let snapshot_hash = Hash::sha256(
(Self::FORMAT_MAGIC, hash_of_all_chunks).serialize_to_vec(),
);
std::fs::remove_file(tarball_path)?;
std::fs::write(self.0.chunk_hashes(), chunk_hashes)?;
std::fs::write(self.0.chunks_root_hash(), snapshot_hash)?;
Ok(())
}
/// Keep `number_to_keep` latest snapshots. All others
/// are deleted.
pub fn cleanup(
latest_height: BlockHeight,
base_dir: &Path,
number_to_keep: u64,
) -> std::io::Result<()> {
let latest_height = latest_height.0;
for height in Self::heights_of_stored_snapshots(base_dir)? {
// this is correct... don't worry about it
if checked!(height + number_to_keep <= latest_height).unwrap() {
let snap = SnapshotPath(base_dir.into(), BlockHeight(height));
snap.remove()?;
}
}
Ok(())
}