-
Notifications
You must be signed in to change notification settings - Fork 715
/
final_state.rs
1325 lines (1157 loc) · 48.7 KB
/
final_state.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
//! Copyright (c) 2022 MASSA LABS <info@massa.net>
//! This file defines the final state of the node, which includes
//! the final ledger and asynchronous message pool that are kept at
//! the output of a given final slot (the latest executed final slot),
//! and need to be bootstrapped by nodes joining the network.
use crate::controller_trait::FinalStateController;
use crate::{config::FinalStateConfig, error::FinalStateError, state_changes::StateChanges};
use anyhow::{anyhow, Result as AnyResult};
use massa_async_pool::AsyncPool;
use massa_db_exports::{
DBBatch, MassaIteratorMode, ShareableMassaDBController, ASYNC_POOL_PREFIX,
CYCLE_HISTORY_PREFIX, DEFERRED_CREDITS_PREFIX, EXECUTED_DENUNCIATIONS_PREFIX,
EXECUTED_OPS_PREFIX, LEDGER_PREFIX, MIP_STORE_PREFIX, STATE_CF,
};
use massa_db_exports::{EXECUTION_TRAIL_HASH_PREFIX, MIP_STORE_STATS_PREFIX, VERSIONING_CF};
use massa_executed_ops::ExecutedDenunciations;
use massa_executed_ops::ExecutedOps;
use massa_hash::Hash;
use massa_ledger_exports::LedgerController;
use massa_ledger_exports::SetOrKeep;
use massa_models::operation::OperationId;
use massa_models::slot::Slot;
use massa_models::timeslots::get_block_slot_timestamp;
use massa_pos_exports::{PoSFinalState, SelectorController};
use massa_versioning::versioning::MipStore;
use tracing::{debug, info, warn};
/// Represents a final state `(ledger, async pool, executed_ops, executed_de and the state of the PoS)`
pub struct FinalState {
/// execution state configuration
pub(crate) config: FinalStateConfig,
/// final ledger associating addresses to their balance, executable bytecode and data
pub ledger: Box<dyn LedgerController>,
/// asynchronous pool containing messages sorted by priority and their data
pub async_pool: AsyncPool,
/// proof of stake state containing cycle history and deferred credits
pub pos_state: PoSFinalState,
/// executed operations
pub executed_ops: ExecutedOps,
/// executed denunciations
pub executed_denunciations: ExecutedDenunciations,
/// MIP store
pub mip_store: MipStore,
/// last_start_period
/// * If start new network: set to 0
/// * If from snapshot: retrieve from args
/// * If from bootstrap: set during bootstrap
pub last_start_period: u64,
/// last_slot_before_downtime
/// * None if start new network
/// * If from snapshot: retrieve from the slot attached to the snapshot
/// * If from bootstrap: set during bootstrap
pub last_slot_before_downtime: Option<Slot>,
/// the RocksDB instance used to write every final_state struct on disk
pub db: ShareableMassaDBController,
}
impl FinalState {
/// Initializes a new `FinalState`
///
/// # Arguments
/// * `config`: the configuration of the final state to use for initialization
/// * `ledger`: the instance of the ledger on disk. Used to apply changes to the ledger.
/// * `selector`: the pos selector. Used to send draw inputs when a new cycle is completed.
/// * `reset_final_state`: if true, we only keep the ledger, and we reset the other fields of the final state
pub fn new(
db: ShareableMassaDBController,
config: FinalStateConfig,
ledger: Box<dyn LedgerController>,
selector: Box<dyn SelectorController>,
mip_store: MipStore,
reset_final_state: bool,
) -> Result<Self, FinalStateError> {
let db_slot = db
.read()
.get_change_id()
.map_err(|_| FinalStateError::InvalidSlot(String::from("Could not get slot in db")))?;
// create the pos state
let pos_state = PoSFinalState::new(
config.pos_config.clone(),
&config.initial_seed_string,
&config.initial_rolls_path,
selector,
db.clone(),
)
.map_err(|err| FinalStateError::PosError(format!("PoS final state init error: {}", err)))?;
// attach at the output of the latest initial final slot, that is the last genesis slot
let slot = if reset_final_state {
Slot::new(0, config.thread_count.saturating_sub(1))
} else {
db_slot
};
// create the async pool
let async_pool = AsyncPool::new(config.async_pool_config.clone(), db.clone());
// create a default executed ops
let executed_ops = ExecutedOps::new(config.executed_ops_config.clone(), db.clone());
// create a default executed denunciations
let executed_denunciations =
ExecutedDenunciations::new(config.executed_denunciations_config.clone(), db.clone());
let mut final_state = FinalState {
ledger,
async_pool,
pos_state,
config,
executed_ops,
executed_denunciations,
mip_store,
last_start_period: 0,
last_slot_before_downtime: None,
db,
};
if reset_final_state {
final_state.db.read().set_initial_change_id(slot);
// delete the execution trail hash
final_state
.db
.write()
.delete_prefix(EXECUTION_TRAIL_HASH_PREFIX, STATE_CF, None);
final_state.async_pool.reset();
final_state.pos_state.reset();
final_state.executed_ops.reset();
final_state.executed_denunciations.reset();
}
info!(
"final_state hash at slot {}: {}",
slot,
final_state.db.read().get_xof_db_hash()
);
// create the final state
Ok(final_state)
}
/// Once we created a FinalState from a snapshot, we need to edit it to attach at the end_slot and handle the downtime.
/// This basically recreates the history of the final_state, without executing the slots.
fn interpolate_downtime(&mut self) -> Result<(), FinalStateError> {
let current_slot =
self.db.read().get_change_id().map_err(|_| {
FinalStateError::InvalidSlot(String::from("Could not get slot in db"))
})?;
let current_slot_cycle = current_slot.get_cycle(self.config.periods_per_cycle);
let end_slot = Slot::new(
self.last_start_period,
self.config.thread_count.saturating_sub(1),
);
let end_slot_cycle = end_slot.get_cycle(self.config.periods_per_cycle);
debug!(
"Interpolating downtime between slots {} and {}",
current_slot, end_slot
);
if current_slot_cycle == end_slot_cycle {
// In that case, we just complete the gap in the same cycle
self.interpolate_single_cycle(current_slot, end_slot)?;
} else {
// Here, we we also complete the cycle_infos in between
self.interpolate_multiple_cycles(
current_slot,
end_slot,
current_slot_cycle,
end_slot_cycle,
)?;
}
// Recompute the hash with the updated data and feed it to POS_state.
let final_state_hash = self.db.read().get_xof_db_hash();
info!(
"final_state hash at slot {}: {}",
end_slot, final_state_hash
);
// feed final_state_hash to the last cycle
let cycle = end_slot.get_cycle(self.config.periods_per_cycle);
self.pos_state
.feed_cycle_state_hash(cycle, final_state_hash);
Ok(())
}
/// This helper function is to be called if the downtime does not span over multiple cycles
fn interpolate_single_cycle(
&mut self,
current_slot: Slot,
end_slot: Slot,
) -> Result<(), FinalStateError> {
let latest_snapshot_cycle = self.pos_state.cycle_history_cache.back().cloned().ok_or(
FinalStateError::SnapshotError(String::from(
"Impossible to interpolate the downtime: no cycle in the given snapshot",
)),
)?;
let latest_snapshot_cycle_info = self
.pos_state
.get_cycle_info(latest_snapshot_cycle.0)
.ok_or_else(|| FinalStateError::SnapshotError(String::from("Missing cycle info")))?;
let mut batch = DBBatch::new();
self.pos_state
.cycle_history_cache
.pop_back()
.ok_or(FinalStateError::SnapshotError(String::from(
"Impossible to interpolate the downtime: no cycle in the given snapshot",
)))?;
self.pos_state
.delete_cycle_info(latest_snapshot_cycle.0, &mut batch);
self.pos_state
.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
let mut batch = DBBatch::new();
self.pos_state
.create_new_cycle_from_last(
&latest_snapshot_cycle_info,
current_slot
.get_next_slot(self.config.thread_count)
.expect("Cannot get next slot"),
end_slot,
&mut batch,
)
.map_err(|err| FinalStateError::PosError(format!("{}", err)))?;
self.pos_state
.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
Ok(())
}
/// This helper function is to be called if the downtime spans over multiple cycles
fn interpolate_multiple_cycles(
&mut self,
current_slot: Slot,
end_slot: Slot,
current_slot_cycle: u64,
end_slot_cycle: u64,
) -> Result<(), FinalStateError> {
let latest_snapshot_cycle = self.pos_state.cycle_history_cache.back().cloned().ok_or(
FinalStateError::SnapshotError(String::from(
"Impossible to interpolate the downtime: no cycle in the given snapshot",
)),
)?;
let latest_snapshot_cycle_info = self
.pos_state
.get_cycle_info(latest_snapshot_cycle.0)
.ok_or_else(|| FinalStateError::SnapshotError(String::from("Missing cycle info")))?;
let mut batch = DBBatch::new();
self.pos_state
.cycle_history_cache
.pop_back()
.ok_or(FinalStateError::SnapshotError(String::from(
"Impossible to interpolate the downtime: no cycle in the given snapshot",
)))?;
self.pos_state
.delete_cycle_info(latest_snapshot_cycle.0, &mut batch);
self.pos_state
.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
// Firstly, complete the first cycle
let last_slot = Slot::new_last_of_cycle(
current_slot_cycle,
self.config.periods_per_cycle,
self.config.thread_count,
)
.map_err(|err| {
FinalStateError::InvalidSlot(format!(
"Cannot create slot for interpolating downtime: {}",
err
))
})?;
let mut batch = DBBatch::new();
self.pos_state
.create_new_cycle_from_last(
&latest_snapshot_cycle_info,
current_slot
.get_next_slot(self.config.thread_count)
.expect("Cannot get next slot"),
last_slot,
&mut batch,
)
.map_err(|err| FinalStateError::PosError(format!("{}", err)))?;
self.pos_state
.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
// Feed final_state_hash to the completed cycle
self.feed_cycle_hash_and_selector_for_interpolation(current_slot_cycle)?;
// TODO: Bring back the following optimisation (it fails because of selector)
// Then, build all the completed cycles in betweens. If we have to build more cycles than the cycle_history_length, we only build the last ones.
//let current_slot_cycle = (current_slot_cycle + 1)
// .max(end_slot_cycle.saturating_sub(self.config.pos_config.cycle_history_length as u64));
let current_slot_cycle = current_slot_cycle + 1;
for cycle in current_slot_cycle..end_slot_cycle {
let first_slot = Slot::new_first_of_cycle(cycle, self.config.periods_per_cycle)
.map_err(|err| {
FinalStateError::InvalidSlot(format!(
"Cannot create slot for interpolating downtime: {}",
err
))
})?;
let last_slot = Slot::new_last_of_cycle(
cycle,
self.config.periods_per_cycle,
self.config.thread_count,
)
.map_err(|err| {
FinalStateError::InvalidSlot(format!(
"Cannot create slot for interpolating downtime: {}",
err
))
})?;
let mut batch = DBBatch::new();
self.pos_state
.create_new_cycle_from_last(
&latest_snapshot_cycle_info,
first_slot,
last_slot,
&mut batch,
)
.map_err(|err| FinalStateError::PosError(format!("{}", err)))?;
self.pos_state
.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
// Feed final_state_hash to the completed cycle
self.feed_cycle_hash_and_selector_for_interpolation(cycle)?;
}
// Then, build the last cycle
let first_slot = Slot::new_first_of_cycle(end_slot_cycle, self.config.periods_per_cycle)
.map_err(|err| {
FinalStateError::InvalidSlot(format!(
"Cannot create slot for interpolating downtime: {}",
err
))
})?;
let mut batch = DBBatch::new();
self.pos_state
.create_new_cycle_from_last(
&latest_snapshot_cycle_info,
first_slot,
end_slot,
&mut batch,
)
.map_err(|err| FinalStateError::PosError(format!("{}", err)))?;
// If the end_slot_cycle is completed
if end_slot.is_last_of_cycle(self.config.periods_per_cycle, self.config.thread_count) {
// Feed final_state_hash to the completed cycle
self.feed_cycle_hash_and_selector_for_interpolation(end_slot_cycle)?;
}
// We reduce the cycle_history len as needed
while self.pos_state.cycle_history_cache.len() > self.pos_state.config.cycle_history_length
{
if let Some((cycle, _)) = self.pos_state.cycle_history_cache.pop_front() {
self.pos_state.delete_cycle_info(cycle, &mut batch);
}
}
self.db
.write()
.write_batch(batch, Default::default(), Some(end_slot));
Ok(())
}
/// Used during interpolation, when a new cycle is set as completed
fn feed_cycle_hash_and_selector_for_interpolation(
&mut self,
cycle: u64,
) -> Result<(), FinalStateError> {
let final_state_hash = self.db.read().get_xof_db_hash();
self.pos_state
.feed_cycle_state_hash(cycle, final_state_hash);
self.pos_state
.feed_selector(cycle.checked_add(2).ok_or_else(|| {
FinalStateError::PosError("cycle overflow when feeding selector".into())
})?)
.map_err(|_| {
FinalStateError::PosError("cycle overflow when feeding selector".into())
})?;
Ok(())
}
fn _finalize(&mut self, slot: Slot, changes: StateChanges) -> AnyResult<()> {
let cur_slot = self.db.read().get_change_id()?;
// check slot consistency
let next_slot = cur_slot.get_next_slot(self.config.thread_count)?;
// .expect("overflow in execution state slot");
if slot != next_slot {
return Err(anyhow!(
"attempting to apply execution state changes at slot {} while the current slot is {}",
slot, cur_slot
));
}
let mut db_batch = DBBatch::new();
let mut db_versioning_batch = DBBatch::new();
// apply the state changes to the batch
self.async_pool
.apply_changes_to_batch(&changes.async_pool_changes, &mut db_batch);
self.pos_state
.apply_changes_to_batch(changes.pos_changes, slot, true, &mut db_batch)?;
// do not panic above, it might just mean that the lookback cycle is not available
// bootstrap again instead
self.ledger
.apply_changes_to_batch(changes.ledger_changes, &mut db_batch);
self.executed_ops
.apply_changes_to_batch(changes.executed_ops_changes, slot, &mut db_batch);
self.executed_denunciations.apply_changes_to_batch(
changes.executed_denunciations_changes,
slot,
&mut db_batch,
);
let slot_ts = get_block_slot_timestamp(
self.config.thread_count,
self.config.t0,
self.config.genesis_timestamp,
slot,
)?;
let slot_prev_ts = get_block_slot_timestamp(
self.config.thread_count,
self.config.t0,
self.config.genesis_timestamp,
slot.get_prev_slot(self.config.thread_count)?,
)?;
self.mip_store.update_batches(
&mut db_batch,
&mut db_versioning_batch,
Some((&slot_prev_ts, &slot_ts)),
)?;
// Update execution trail hash
if let SetOrKeep::Set(new_hash) = changes.execution_trail_hash_change {
db_batch.insert(
EXECUTION_TRAIL_HASH_PREFIX.as_bytes().to_vec(),
Some(new_hash.to_bytes().to_vec()),
);
}
self.db
.write()
.write_batch(db_batch, db_versioning_batch, Some(slot));
let final_state_hash = self.db.read().get_xof_db_hash();
// compute the final state hash
info!("final_state hash at slot {}: {}", slot, final_state_hash);
// Backup DB if needed
#[cfg(feature = "bootstrap_server")]
if slot.period % self.config.ledger_backup_periods_interval == 0
&& slot.period != 0
&& slot.thread == 0
{
let state_slot = self.db.read().get_change_id();
match state_slot {
Ok(slot) => {
info!(
"Backuping db for slot {}, state slot: {}, state hash: {}",
slot, slot, final_state_hash
);
}
Err(e) => {
info!("{}", e);
info!(
"Backuping db for unknown state slot, state hash: {}",
final_state_hash
);
}
}
self.db.read().backup_db(slot);
}
// feed final_state_hash to the last cycle
let cycle = slot.get_cycle(self.config.periods_per_cycle);
self.pos_state
.feed_cycle_state_hash(cycle, final_state_hash);
Ok(())
}
/// Internal function called by is_db_valid
fn _is_db_valid(&self) -> AnyResult<()> {
let db = self.db.read();
// check if the execution trial hash is present and valid
{
let execution_trail_hash_serialized =
match db.get_cf(STATE_CF, EXECUTION_TRAIL_HASH_PREFIX.as_bytes().to_vec()) {
Ok(Some(v)) => v,
Ok(None) => {
return Err(anyhow!("No execution trail hash found in DB"));
}
Err(err) => {
return Err(err.into());
}
};
if let Err(err) = massa_hash::Hash::try_from(&execution_trail_hash_serialized[..]) {
warn!("Invalid execution trail hash found in DB: {}", err);
return Err(err.into());
}
}
for (serialized_key, serialized_value) in db.iterator_cf(STATE_CF, MassaIteratorMode::Start)
{
#[allow(clippy::if_same_then_else)]
if serialized_key.starts_with(CYCLE_HISTORY_PREFIX.as_bytes()) {
if !self
.pos_state
.is_cycle_history_key_value_valid(&serialized_key, &serialized_value)
{
warn!(
"Wrong key/value for CYCLE_HISTORY_KEY PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Wrong key/value for CYCLE_HISTORY_KEY PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(DEFERRED_CREDITS_PREFIX.as_bytes()) {
if !self
.pos_state
.is_deferred_credits_key_value_valid(&serialized_key, &serialized_value)
{
warn!(
"Wrong key/value for DEFERRED_CREDITS PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Wrong key/value for DEFERRED_CREDITS PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(ASYNC_POOL_PREFIX.as_bytes()) {
if !self
.async_pool
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!(
"Wrong key/value for ASYNC_POOL PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Wrong key/value for ASYNC_POOL PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(EXECUTED_OPS_PREFIX.as_bytes()) {
if !self
.executed_ops
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!(
"Wrong key/value for EXECUTED_OPS PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Wrong key/value for EXECUTED_OPS PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(EXECUTED_DENUNCIATIONS_PREFIX.as_bytes()) {
if !self
.executed_denunciations
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!("Wrong key/value for EXECUTED_DENUNCIATIONS PREFIX serialized_key: {:?}, serialized_value: {:?}", serialized_key, serialized_value);
return Err(anyhow!(
"Wrong key/value for EXECUTED_DENUNCIATIONS PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(LEDGER_PREFIX.as_bytes()) {
if !self
.ledger
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!("Wrong key/value for LEDGER PREFIX serialized_key: {:?}, serialized_value: {:?}", serialized_key, serialized_value);
return Err(anyhow!(
"Wrong key/value for LEDGER PREFIX serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(MIP_STORE_PREFIX.as_bytes()) {
if !self
.mip_store
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!("Wrong key/value for MIP Store");
return Err(anyhow!(
"Wrong key/value for MIP Store serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else if serialized_key.starts_with(EXECUTION_TRAIL_HASH_PREFIX.as_bytes()) {
// no checks here as they are performed above by direct reading
} else {
warn!(
"Key/value does not correspond to any prefix: serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Key/value does not correspond to any prefix: serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
}
for (serialized_key, serialized_value) in
db.iterator_cf(VERSIONING_CF, MassaIteratorMode::Start)
{
if serialized_key.starts_with(MIP_STORE_PREFIX.as_bytes())
|| serialized_key.starts_with(MIP_STORE_STATS_PREFIX.as_bytes())
{
if !self
.mip_store
.is_key_value_valid(&serialized_key, &serialized_value)
{
warn!("Wrong key/value for MIP Store");
return Err(anyhow!(
"Wrong key/value for MIP Store serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
} else {
warn!(
"Key/value does not correspond to any prefix: serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
);
return Err(anyhow!(
"Key/value does not correspond to any prefix: serialized_key: {:?}, serialized_value: {:?}",
serialized_key, serialized_value
));
}
}
Ok(())
}
/// Initializes a `FinalState` from a snapshot.
///
/// # Arguments
/// * `db`: A type that implements the `MassaDBController` trait. Used to read and write to the database.
/// * `config`: the configuration of the final state to use for initialization
/// * `ledger`: the instance of the ledger on disk. Used to apply changes to the ledger.
/// * `selector`: the pos selector. Used to send draw inputs when a new cycle is completed.
/// * `last_start_period`: at what period we should attach the final_state
pub fn new_derived_from_snapshot(
db: ShareableMassaDBController,
config: FinalStateConfig,
ledger: Box<dyn LedgerController>,
selector: Box<dyn SelectorController>,
mip_store: MipStore,
last_start_period: u64,
) -> Result<Self, FinalStateError> {
info!("Restarting from snapshot");
let mut final_state =
FinalState::new(db, config.clone(), ledger, selector, mip_store, false)?;
let recovered_slot =
final_state.db.read().get_change_id().map_err(|_| {
FinalStateError::InvalidSlot(String::from("Could not get slot in db"))
})?;
// This is needed for `test_bootstrap_server` to work
if cfg!(feature = "test-exports") {
let mut batch = DBBatch::new();
final_state.pos_state.create_initial_cycle(&mut batch);
final_state
.db
.write()
.write_batch(batch, Default::default(), Some(recovered_slot));
}
final_state.last_slot_before_downtime = Some(recovered_slot);
// Check that MIP store is consistent with the network shutdown time range
// Assume that the final state has been edited during network shutdown
let shutdown_start = recovered_slot
.get_next_slot(config.thread_count)
.map_err(|e| {
FinalStateError::InvalidSlot(format!(
"Unable to get next slot from recovered slot: {:?}",
e
))
})?;
let shutdown_end = Slot::new(last_start_period, 0)
.get_prev_slot(config.thread_count)
.map_err(|e| {
FinalStateError::InvalidSlot(format!(
"Unable to compute prev slot from last start period: {:?}",
e
))
})?;
debug!(
"Checking if MIP store is consistent against shutdown period: {} - {}",
shutdown_start, shutdown_end
);
final_state
.mip_store
.is_consistent_with_shutdown_period(
shutdown_start,
shutdown_end,
config.thread_count,
config.t0,
config.genesis_timestamp,
)
.map_err(FinalStateError::from)?;
debug!(
"Latest consistent slot found in snapshot data: {}",
recovered_slot
);
info!(
"final_state hash at slot {}: {}",
recovered_slot,
final_state.db.read().get_xof_db_hash()
);
// Then, interpolate the downtime, to attach at end_slot;
final_state.last_start_period = last_start_period;
final_state.recompute_caches();
// We compute the draws here because we need to feed_cycles when interpolating
final_state.compute_initial_draws()?;
final_state.interpolate_downtime()?;
Ok(final_state)
}
}
impl FinalStateController for FinalState {
fn compute_initial_draws(&mut self) -> Result<(), FinalStateError> {
self.pos_state
.compute_initial_draws()
.map_err(|err| FinalStateError::PosError(err.to_string()))
}
fn finalize(&mut self, slot: Slot, changes: StateChanges) {
self._finalize(slot, changes).unwrap()
}
fn get_execution_trail_hash(&self) -> Hash {
let hash_bytes = self
.db
.read()
.get_cf(STATE_CF, EXECUTION_TRAIL_HASH_PREFIX.as_bytes().to_vec())
.expect("could not read execution trail hash from state DB")
.expect("could not find execution trail hash in state DB");
Hash::from_bytes(
hash_bytes
.as_slice()
.try_into()
.expect("invalid execution trail hash in state DB"),
)
}
fn get_fingerprint(&self) -> Hash {
let internal_hash = self.db.read().get_xof_db_hash();
Hash::compute_from(internal_hash.to_bytes())
}
fn get_slot(&self) -> Slot {
self.db
.read()
.get_change_id()
.expect("Critical error: Final state has no slot attached")
}
fn init_execution_trail_hash_to_batch(&mut self, batch: &mut DBBatch) {
batch.insert(
EXECUTION_TRAIL_HASH_PREFIX.as_bytes().to_vec(),
Some(massa_hash::Hash::zero().to_bytes().to_vec()),
);
}
fn is_db_valid(&self) -> bool {
self._is_db_valid().is_ok()
}
fn recompute_caches(&mut self) {
self.async_pool.recompute_message_info_cache();
self.executed_ops.recompute_sorted_ops_and_op_exec_status();
self.executed_denunciations.recompute_sorted_denunciations();
self.pos_state.recompute_pos_state_caches();
}
fn reset(&mut self) {
let slot = Slot::new(0, self.config.thread_count.saturating_sub(1));
self.db.write().reset(slot);
self.ledger.reset();
self.async_pool.reset();
self.pos_state.reset();
self.executed_ops.reset();
self.executed_denunciations.reset();
self.mip_store.reset_db(self.db.clone());
// delete the execution trail hash
self.db
.write()
.delete_prefix(EXECUTION_TRAIL_HASH_PREFIX, STATE_CF, None);
}
fn get_ledger(&self) -> &Box<dyn LedgerController> {
&self.ledger
}
fn get_ledger_mut(&mut self) -> &mut Box<dyn LedgerController> {
&mut self.ledger
}
fn get_async_pool(&self) -> &AsyncPool {
&self.async_pool
}
fn get_pos_state(&self) -> &PoSFinalState {
&self.pos_state
}
fn get_pos_state_mut(&mut self) -> &mut PoSFinalState {
&mut self.pos_state
}
fn executed_ops_contains(&self, op_id: &OperationId) -> bool {
self.executed_ops.contains(op_id)
}
fn get_ops_exec_status(&self, batch: &[OperationId]) -> Vec<Option<bool>> {
self.executed_ops.get_ops_exec_status(batch)
}
fn get_executed_denunciations(&self) -> &ExecutedDenunciations {
&self.executed_denunciations
}
fn get_database(&self) -> &ShareableMassaDBController {
&self.db
}
fn get_last_start_period(&self) -> u64 {
self.last_start_period
}
fn set_last_start_period(&mut self, last_start_period: u64) {
self.last_start_period = last_start_period;
}
fn get_last_slot_before_downtime(&self) -> &Option<Slot> {
&self.last_slot_before_downtime
}
fn set_last_slot_before_downtime(&mut self, last_slot_before_downtime: Option<Slot>) {
self.last_slot_before_downtime = last_slot_before_downtime;
}
fn get_mip_store_mut(&mut self) -> &mut MipStore {
&mut self.mip_store
}
fn get_mip_store(&self) -> &MipStore {
&self.mip_store
}
}
#[cfg(test)]
mod test {
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;
use num::rational::Ratio;
use parking_lot::RwLock;
use tempfile::tempdir;
use massa_async_pool::{AsyncMessage, AsyncPoolChanges, AsyncPoolConfig};
use massa_db_exports::{MassaDBConfig, MassaDBController, STATE_HASH_INITIAL_BYTES};
use massa_db_worker::MassaDB;
use massa_executed_ops::{ExecutedDenunciationsConfig, ExecutedOpsConfig};
use massa_hash::Hash;
use massa_ledger_exports::{LedgerChanges, LedgerConfig, LedgerEntryUpdate, SetUpdateOrDelete};
use massa_ledger_worker::FinalLedger;
use massa_models::address::Address;
use massa_models::amount::Amount;
use massa_models::bytecode::Bytecode;
use massa_models::config::{
DENUNCIATION_EXPIRE_PERIODS, ENDORSEMENT_COUNT, KEEP_EXECUTED_HISTORY_EXTRA_PERIODS,
MAX_ASYNC_POOL_LENGTH, MAX_DATASTORE_KEY_LENGTH, MAX_DATASTORE_VALUE_LENGTH,
MAX_DEFERRED_CREDITS_LENGTH, MAX_DENUNCIATIONS_PER_BLOCK_HEADER,
MAX_DENUNCIATION_CHANGES_LENGTH, MAX_FUNCTION_NAME_LENGTH, MAX_PARAMETERS_SIZE,
MAX_PRODUCTION_STATS_LENGTH, MAX_ROLLS_COUNT_LENGTH, MIP_STORE_STATS_BLOCK_CONSIDERED,
PERIODS_PER_CYCLE, POS_SAVED_CYCLES, T0, THREAD_COUNT,
};
use massa_pos_exports::MockSelectorController;
use massa_pos_exports::{PoSChanges, PoSConfig, PosError};
use massa_time::MassaTime;
use massa_versioning::versioning::MipStatsConfig;
use super::*;
fn get_final_state_config() -> (FinalStateConfig, LedgerConfig) {
let massa_node_base = PathBuf::from("../massa-node");
let genesis_timestamp = MassaTime::from_millis(0);
let ledger_config = LedgerConfig {
thread_count: THREAD_COUNT,
initial_ledger_path: massa_node_base.join("base_config/initial_ledger.json"),
max_key_length: MAX_DATASTORE_KEY_LENGTH,
max_datastore_value_length: MAX_DATASTORE_VALUE_LENGTH,
};
let async_pool_config = AsyncPoolConfig {
max_length: MAX_ASYNC_POOL_LENGTH,
max_function_length: MAX_FUNCTION_NAME_LENGTH,
max_function_params_length: MAX_PARAMETERS_SIZE as u64,
thread_count: THREAD_COUNT,
max_key_length: MAX_DATASTORE_KEY_LENGTH as u32,
};
let pos_config = PoSConfig {
periods_per_cycle: PERIODS_PER_CYCLE,
thread_count: THREAD_COUNT,
cycle_history_length: POS_SAVED_CYCLES,
max_rolls_length: MAX_ROLLS_COUNT_LENGTH,
max_production_stats_length: MAX_PRODUCTION_STATS_LENGTH,
max_credit_length: MAX_DEFERRED_CREDITS_LENGTH,
initial_deferred_credits_path: Some(
massa_node_base.join("base_config/deferred_credits.json"),
),
};
let executed_ops_config = ExecutedOpsConfig {
thread_count: THREAD_COUNT,
keep_executed_history_extra_periods: KEEP_EXECUTED_HISTORY_EXTRA_PERIODS,
};
let executed_denunciations_config = ExecutedDenunciationsConfig {
denunciation_expire_periods: DENUNCIATION_EXPIRE_PERIODS,
thread_count: THREAD_COUNT,
endorsement_count: ENDORSEMENT_COUNT,
keep_executed_history_extra_periods: KEEP_EXECUTED_HISTORY_EXTRA_PERIODS,
};
let final_state_config = FinalStateConfig {
ledger_config: ledger_config.clone(),
async_pool_config,